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
8aa34a89aed65799e9d9b37c397092f0ee57fc5a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/finsupp/interval.lean
b05e89043e75b01263f6d878c47c6e84a35b3315
[ "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,507
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import data.finset.finsupp import data.finset.locally_finite import data.finsupp.order /-! # Finite intervals of finitely supported functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides the `locally_finite_order` instance for `ι →₀ α` when `α` itself is locally finite and calculates the cardinality of its finite intervals. ## Main declarations * `finsupp.range_singleton`: Postcomposition with `has_singleton.singleton` on `finset` as a `finsupp`. * `finsupp.range_Icc`: Postcomposition with `finset.Icc` as a `finsupp`. Both these definitions use the fact that `0 = {0}` to ensure that the resulting function is finitely supported. -/ noncomputable theory open finset finsupp function open_locale big_operators classical pointwise variables {ι α : Type*} namespace finsupp section range_singleton variables [has_zero α] {f : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.singleton` bundled as a `finsupp`. -/ @[simps] def range_singleton (f : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, {f i}, support := f.support, mem_support_to_fun := λ i, begin rw [←not_iff_not, not_mem_support_iff, not_ne_iff], exact singleton_injective.eq_iff.symm, end } lemma mem_range_singleton_apply_iff : a ∈ f.range_singleton i ↔ a = f i := mem_singleton end range_singleton section range_Icc variables [has_zero α] [partial_order α] [locally_finite_order α] {f g : ι →₀ α} {i : ι} {a : α} /-- Pointwise `finset.Icc` bundled as a `finsupp`. -/ @[simps to_fun] def range_Icc (f g : ι →₀ α) : ι →₀ finset α := { to_fun := λ i, Icc (f i) (g i), support := by haveI := classical.dec_eq ι; exact f.support ∪ g.support, mem_support_to_fun := λ i, begin rw [mem_union, ←not_iff_not, not_or_distrib, not_mem_support_iff, not_mem_support_iff, not_ne_iff], exact Icc_eq_singleton_iff.symm, end } @[simp] lemma range_Icc_support [decidable_eq ι] (f g : ι →₀ α) : (range_Icc f g).support = f.support ∪ g.support := by convert rfl lemma mem_range_Icc_apply_iff : a ∈ f.range_Icc g i ↔ f i ≤ a ∧ a ≤ g i := mem_Icc end range_Icc section partial_order variables [partial_order α] [has_zero α] [locally_finite_order α] (f g : ι →₀ α) instance : locally_finite_order (ι →₀ α) := by haveI := classical.dec_eq ι; haveI := classical.dec_eq α; exact locally_finite_order.of_Icc (ι →₀ α) (λ f g, (f.support ∪ g.support).finsupp $ f.range_Icc g) (λ f g x, begin refine (mem_finsupp_iff_of_support_subset $ finset.subset_of_eq $ range_Icc_support _ _).trans _, simp_rw mem_range_Icc_apply_iff, exact forall_and_distrib, end) lemma Icc_eq [decidable_eq ι] : Icc f g = (f.support ∪ g.support).finsupp (f.range_Icc g) := by convert rfl lemma card_Icc [decidable_eq ι] : (Icc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card := by simp_rw [Icc_eq, card_finsupp, range_Icc_to_fun] lemma card_Ico [decidable_eq ι] : (Ico f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ico_eq_card_Icc_sub_one, card_Icc] lemma card_Ioc [decidable_eq ι] : (Ioc f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 1 := by rw [card_Ioc_eq_card_Icc_sub_one, card_Icc] lemma card_Ioo [decidable_eq ι] : (Ioo f g).card = ∏ i in f.support ∪ g.support, (Icc (f i) (g i)).card - 2 := by rw [card_Ioo_eq_card_Icc_sub_two, card_Icc] end partial_order section lattice variables [lattice α] [has_zero α] [locally_finite_order α] (f g : ι →₀ α) lemma card_uIcc [decidable_eq ι] : (uIcc f g).card = ∏ i in f.support ∪ g.support, (uIcc (f i) (g i)).card := by { rw ←support_inf_union_support_sup, exact card_Icc _ _ } end lattice section canonically_ordered variables [canonically_ordered_add_monoid α] [locally_finite_order α] variables (f : ι →₀ α) lemma card_Iic : (Iic f).card = ∏ i in f.support, (Iic (f i)).card := begin classical, simp_rw [Iic_eq_Icc, card_Icc, finsupp.bot_eq_zero, support_zero, empty_union, zero_apply, bot_eq_zero] end lemma card_Iio : (Iio f).card = ∏ i in f.support, (Iic (f i)).card - 1 := by rw [card_Iio_eq_card_Iic_sub_one, card_Iic] end canonically_ordered end finsupp
a124d15cc4f3d32f55765589741e4d45dbe64adb
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/calc_auto_trans_eq.lean
e2036aeb46bd2fd0929fb3746d4170a8f470029d
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
533
lean
import data.list constant R : Π {A : Type}, A → A → Prop infix `~`:50 := R example {A : Type} {a b c d : list nat} (H₁ : a ~ b) (H₂ : b = c) (H₃ : c = d) : a ~ d := calc a ~ b : H₁ ... = c : H₂ ... = d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b = c) (H₃ : c ~ d) : a ~ d := calc a = b : H₁ ... = c : H₂ ... ~ d : H₃ example {A : Type} {a b c d : list nat} (H₁ : a = b) (H₂ : b ~ c) (H₃ : c = d) : a ~ d := calc a = b : H₁ ... ~ c : H₂ ... = d : H₃
e485fd25f63e9716ff2fec99e93896afbb35be9c
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/equiv/fin.lean
236ce6b605e66fa0531adeb25ab4487a5e62bce4
[ "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
13,799
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fin.basic import data.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universes u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv_punit_of_unique /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/ @[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim, left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } /-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where `γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and `fin_two_arrow_equiv`. -/ @[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) : α × β ≃ Π i : fin 2, @fin.cons _ (λ _, Type u) α (fin.cons β fin_zero_elim) i := (pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm /-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and `prod_equiv_pi_fin_two`. -/ @[simps {fully_applied := ff}] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α := pi_fin_two_equiv (λ _, α) /-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv` for a non-dependent version. -/ def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] : (Π i, α i) ≃o α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, map_rel_iff' := λ f g, iff.symm fin.forall_fin_two } /-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also `order_iso.pi_fin_two_iso`. -/ def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α := order_iso.pi_fin_two_iso (λ _, α) /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := (fin.cast h).to_equiv @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := { to_fun := i.insert_nth none some, inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x, right_inv := λ x, by cases x; dsimp; simp } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] @[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : fin_succ_equiv' i (i.succ_above j) = some j := @fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _ lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above] @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl @[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) : (fin_succ_equiv' i).symm (some j) = i.succ_above j := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := fin.succ_above_below i m h lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := fin.succ_above_above i m h lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := by cases n; refl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := fin_succ_equiv'_above (fin.zero_le _) @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := fin_succ_equiv'_symm_none _ @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := congr_fun fin.succ_above_zero m @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := sum.elim (fin.cast_add n) (fin.nat_add m), inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i, left_inv := λ x, by { cases x with y y; dsimp; simp }, right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x := fin_sum_fin_equiv.symm_apply_apply (sum.inl x) @[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) : fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x := fin_sum_fin_equiv.symm_apply_apply (sum.inr x) /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) : fin_add_flip (fin.cast_add n k) = fin.nat_add n k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) : fin_add_flip (fin.nat_add m k) = fin.cast_add m k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n @[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, tsub_le_self.trans_lt $ add_comm m n ▸ h₂⟩ := begin convert fin_add_flip_apply_nat_add ⟨k - m, (tsub_lt_iff_right h₁).2 _⟩ m, { simp [add_tsub_cancel_of_le h₁] }, { rwa add_comm } end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_mk_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
f4facc2d104014669366cc18de0422634db05701
7565ffb53cc64430691ce89265da0f944ee43051
/hott/types/pointed.hlean
78c677456c64ffa97788a9e171b95b6cf66979dc
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,326
hlean
/- Copyright (c) 2014-2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Floris van Doorn Early library ported from Coq HoTT, but greatly extended since. The basic definitions are in init.pointed See also .pointed2 -/ import .nat.basic ..arity ..prop_trunc open is_trunc eq prod sigma nat equiv option is_equiv bool unit sigma.ops sum algebra function namespace pointed variables {A B : Type} definition pointed_loop [instance] [constructor] (a : A) : pointed (a = a) := pointed.mk idp definition pointed_fun_closed [constructor] (f : A → B) [H : pointed A] : pointed B := pointed.mk (f pt) definition loop [reducible] [constructor] (A : Type*) : Type* := pointed.mk' (point A = point A) definition loopn [reducible] : ℕ → Type* → Type* | loopn 0 X := X | loopn (n+1) X := loop (loopn n X) notation `Ω` := loop notation `Ω[`:95 n:0 `]`:0 := loopn n namespace ops -- this is in a separate namespace because it caused type class inference to loop in some places definition is_trunc_pointed_MK [instance] [priority 1100] (n : ℕ₋₂) {A : Type} (a : A) [H : is_trunc n A] : is_trunc n (pointed.MK A a) := H end ops definition is_trunc_loop [instance] [priority 1100] (A : Type*) (n : ℕ₋₂) [H : is_trunc (n.+1) A] : is_trunc n (Ω A) := !is_trunc_eq definition loopn_zero_eq [unfold_full] (A : Type*) : Ω[0] A = A := rfl definition loopn_succ_eq [unfold_full] (k : ℕ) (A : Type*) : Ω[succ k] A = Ω (Ω[k] A) := rfl definition rfln [constructor] [reducible] {n : ℕ} {A : Type*} : Ω[n] A := pt definition refln [constructor] [reducible] (n : ℕ) (A : Type*) : Ω[n] A := pt definition refln_eq_refl [unfold_full] (A : Type*) (n : ℕ) : rfln = rfl :> Ω[succ n] A := rfl definition loopn_space [unfold 3] (A : Type) [H : pointed A] (n : ℕ) : Type := Ω[n] (pointed.mk' A) definition loop_mul {k : ℕ} {A : Type*} (mul : A → A → A) : Ω[k] A → Ω[k] A → Ω[k] A := begin cases k with k, exact mul, exact concat end definition pType_eq {A B : Type*} (f : A ≃ B) (p : f pt = pt) : A = B := begin cases A with A a, cases B with B b, esimp at *, fapply apdt011 @pType.mk, { apply ua f}, { rewrite [cast_ua, p]}, end definition pType_eq_elim {A B : Type*} (p : A = B :> Type*) : Σ(p : carrier A = carrier B :> Type), Point A =[p] Point B := by induction p; exact ⟨idp, idpo⟩ protected definition pType.sigma_char.{u} : pType.{u} ≃ Σ(X : Type.{u}), X := begin fapply equiv.MK, { intro x, induction x with X x, exact ⟨X, x⟩}, { intro x, induction x with X x, exact pointed.MK X x}, { intro x, induction x with X x, reflexivity}, { intro x, induction x with X x, reflexivity}, end definition pType.eta_expand [constructor] (A : Type*) : Type* := pointed.MK A pt definition add_point [constructor] (A : Type) : Type* := pointed.Mk (none : option A) postfix `₊`:(max+1) := add_point -- the inclusion A → A₊ is called "some", the extra point "pt" or "none" ("@none A") end pointed namespace pointed /- truncated pointed types -/ definition ptrunctype_eq {n : ℕ₋₂} {A B : n-Type*} (p : A = B :> Type) (q : Point A =[p] Point B) : A = B := begin induction A with A HA a, induction B with B HB b, esimp at *, induction q, esimp, refine ap010 (ptrunctype.mk A) _ a, exact !is_prop.elim end definition ptrunctype_eq_of_pType_eq {n : ℕ₋₂} {A B : n-Type*} (p : A = B :> Type*) : A = B := begin cases pType_eq_elim p with q r, exact ptrunctype_eq q r end definition is_trunc_ptrunctype [instance] {n : ℕ₋₂} (A : n-Type*) : is_trunc n A := trunctype.struct A end pointed open pointed namespace pointed variables {A B C D : Type*} {f g h : A →* B} /- categorical properties of pointed maps -/ definition pid [constructor] [refl] (A : Type*) : A →* A := pmap.mk id idp definition pcompose [constructor] [trans] {A B C : Type*} (g : B →* C) (f : A →* B) : A →* C := pmap.mk (λa, g (f a)) (ap g (respect_pt f) ⬝ respect_pt g) infixr ` ∘* `:60 := pcompose definition pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) : pointed.MK A a →* pointed.MK B (f a) := pmap.mk f idp definition respect_pt_pcompose {A B C : Type*} (g : B →* C) (f : A →* B) : respect_pt (g ∘* f) = ap g (respect_pt f) ⬝ respect_pt g := idp definition passoc [constructor] (h : C →* D) (g : B →* C) (f : A →* B) : (h ∘* g) ∘* f ~* h ∘* (g ∘* f) := phomotopy.mk (λa, idp) abstract !idp_con ⬝ whisker_right _ (!ap_con ⬝ whisker_right _ !ap_compose'⁻¹) ⬝ !con.assoc end definition pid_pcompose [constructor] (f : A →* B) : pid B ∘* f ~* f := begin fapply phomotopy.mk, { intro a, reflexivity}, { reflexivity} end definition pcompose_pid [constructor] (f : A →* B) : f ∘* pid A ~* f := begin fapply phomotopy.mk, { intro a, reflexivity}, { reflexivity} end /- equivalences and equalities -/ definition pmap.sigma_char [constructor] {A B : Type*} : (A →* B) ≃ Σ(f : A → B), f pt = pt := begin fapply equiv.MK : intros f, { exact ⟨f , respect_pt f⟩ }, all_goals cases f with f p, { exact pmap.mk f p }, all_goals reflexivity end definition pmap.eta_expand [constructor] {A B : Type*} (f : A →* B) : A →* B := pmap.mk f (pmap.resp_pt f) definition pmap_equiv_right (A : Type*) (B : Type) : (Σ(b : B), A →* (pointed.Mk b)) ≃ (A → B) := begin fapply equiv.MK, { intro u a, exact pmap.to_fun u.2 a}, { intro f, refine ⟨f pt, _⟩, fapply pmap.mk, intro a, esimp, exact f a, reflexivity}, { intro f, reflexivity}, { intro u, cases u with b f, cases f with f p, esimp at *, induction p, reflexivity} end /- some specific pointed maps -/ -- The constant pointed map between any two types definition pconst [constructor] (A B : Type*) : A →* B := pmap.mk (λ a, Point B) idp -- the pointed type of pointed maps definition ppmap [constructor] (A B : Type*) : Type* := pType.mk (A →* B) (pconst A B) definition pcast [constructor] {A B : Type*} (p : A = B) : A →* B := pmap.mk (cast (ap pType.carrier p)) (by induction p; reflexivity) definition pinverse [constructor] {X : Type*} : Ω X →* Ω X := pmap.mk eq.inverse idp /- we generalize the definition of ap1 to arbitrary paths, so that we can prove properties about it using path induction (see for example ap1_gen_con and ap1_gen_con_natural) -/ definition ap1_gen [reducible] [unfold 6 9 10] {A B : Type} (f : A → B) {a a' : A} {b b' : B} (q : f a = b) (q' : f a' = b') (p : a = a') : b = b' := q⁻¹ ⬝ ap f p ⬝ q' definition ap1_gen_idp [unfold 6] {A B : Type} (f : A → B) {a : A} {b : B} (q : f a = b) : ap1_gen f q q idp = idp := con.left_inv q definition ap1_gen_idp_left [unfold 6] {A B : Type} (f : A → B) {a a' : A} (p : a = a') : ap1_gen f idp idp p = ap f p := proof idp_con (ap f p) qed definition ap1_gen_idp_left_con {A B : Type} (f : A → B) {a : A} (p : a = a) (q : ap f p = idp) : ap1_gen_idp_left f p ⬝ q = proof ap (concat idp) q qed := proof idp_con_idp q qed definition ap1 [constructor] (f : A →* B) : Ω A →* Ω B := pmap.mk (λp, ap1_gen f (respect_pt f) (respect_pt f) p) (ap1_gen_idp f (respect_pt f)) definition apn (n : ℕ) (f : A →* B) : Ω[n] A →* Ω[n] B := begin induction n with n IH, { exact f}, { esimp [loopn], exact ap1 IH} end notation `Ω→`:(max+5) := ap1 notation `Ω→[`:95 n:0 `]`:0 := apn n definition ptransport [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : B a →* B a' := pmap.mk (transport B p) (apdt (λa, Point (B a)) p) definition pmap_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK A a →* pointed.MK A a' := pmap.mk id p definition pbool_pmap [constructor] {A : Type*} (a : A) : pbool →* A := pmap.mk (bool.rec pt a) idp /- properties of pointed maps -/ definition apn_zero [unfold_full] (f : A →* B) : Ω→[0] f = f := idp definition apn_succ [unfold_full] (n : ℕ) (f : A →* B) : Ω→[n + 1] f = Ω→ (Ω→[n] f) := idp definition ap1_gen_con {A B : Type} (f : A → B) {a₁ a₂ a₃ : A} {b₁ b₂ b₃ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (q₃ : f a₃ = b₃) (p₁ : a₁ = a₂) (p₂ : a₂ = a₃) : ap1_gen f q₁ q₃ (p₁ ⬝ p₂) = ap1_gen f q₁ q₂ p₁ ⬝ ap1_gen f q₂ q₃ p₂ := begin induction p₂, induction q₃, induction q₂, reflexivity end definition ap1_gen_inv {A B : Type} (f : A → B) {a₁ a₂ : A} {b₁ b₂ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (p₁ : a₁ = a₂) : ap1_gen f q₂ q₁ p₁⁻¹ = (ap1_gen f q₁ q₂ p₁)⁻¹ := begin induction p₁, induction q₁, induction q₂, reflexivity end definition ap1_con {A B : Type*} (f : A →* B) (p q : Ω A) : ap1 f (p ⬝ q) = ap1 f p ⬝ ap1 f q := ap1_gen_con f (respect_pt f) (respect_pt f) (respect_pt f) p q theorem ap1_inv (f : A →* B) (p : Ω A) : ap1 f p⁻¹ = (ap1 f p)⁻¹ := ap1_gen_inv f (respect_pt f) (respect_pt f) p -- the following two facts are used for the suspension axiom to define spectrum cohomology definition ap1_gen_con_natural {A B : Type} (f : A → B) {a₁ a₂ a₃ : A} {p₁ p₁' : a₁ = a₂} {p₂ p₂' : a₂ = a₃} {b₁ b₂ b₃ : B} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (q₃ : f a₃ = b₃) (r₁ : p₁ = p₁') (r₂ : p₂ = p₂') : square (ap1_gen_con f q₁ q₂ q₃ p₁ p₂) (ap1_gen_con f q₁ q₂ q₃ p₁' p₂') (ap (ap1_gen f q₁ q₃) (r₁ ◾ r₂)) (ap (ap1_gen f q₁ q₂) r₁ ◾ ap (ap1_gen f q₂ q₃) r₂) := begin induction r₁, induction r₂, exact vrfl end definition ap1_gen_con_idp {A B : Type} (f : A → B) {a : A} {b : B} (q : f a = b) : ap1_gen_con f q q q idp idp ⬝ con.left_inv q ◾ con.left_inv q = con.left_inv q := by induction q; reflexivity definition apn_con (n : ℕ) (f : A →* B) (p q : Ω[n+1] A) : apn (n+1) f (p ⬝ q) = apn (n+1) f p ⬝ apn (n+1) f q := ap1_con (apn n f) p q definition apn_inv (n : ℕ) (f : A →* B) (p : Ω[n+1] A) : apn (n+1) f p⁻¹ = (apn (n+1) f p)⁻¹ := ap1_inv (apn n f) p definition is_equiv_ap1 (f : A →* B) [is_equiv f] : is_equiv (ap1 f) := begin induction B with B b, induction f with f pf, esimp at *, cases pf, esimp, apply is_equiv.homotopy_closed (ap f), intro p, exact !idp_con⁻¹ end definition is_equiv_apn (n : ℕ) (f : A →* B) [H : is_equiv f] : is_equiv (apn n f) := begin induction n with n IH, { exact H}, { exact is_equiv_ap1 (apn n f)} end definition pinverse_con [constructor] {X : Type*} (p q : Ω X) : pinverse (p ⬝ q) = pinverse q ⬝ pinverse p := !con_inv definition pinverse_inv [constructor] {X : Type*} (p : Ω X) : pinverse p⁻¹ = (pinverse p)⁻¹ := idp definition is_equiv_pcast [instance] {A B : Type*} (p : A = B) : is_equiv (pcast p) := !is_equiv_cast /- categorical properties of pointed homotopies -/ protected definition phomotopy.refl [constructor] [refl] (f : A →* B) : f ~* f := begin fapply phomotopy.mk, { intro a, exact idp}, { apply idp_con} end protected definition phomotopy.rfl [constructor] [reducible] {f : A →* B} : f ~* f := phomotopy.refl f protected definition phomotopy.trans [constructor] [trans] (p : f ~* g) (q : g ~* h) : f ~* h := phomotopy.mk (λa, p a ⬝ q a) (!con.assoc ⬝ whisker_left (p pt) (to_homotopy_pt q) ⬝ to_homotopy_pt p) protected definition phomotopy.symm [constructor] [symm] (p : f ~* g) : g ~* f := phomotopy.mk (λa, (p a)⁻¹) (inv_con_eq_of_eq_con (to_homotopy_pt p)⁻¹) infix ` ⬝* `:75 := phomotopy.trans postfix `⁻¹*`:(max+1) := phomotopy.symm /- equalities and equivalences relating pointed homotopies -/ definition phomotopy.rec' [recursor] (P : f ~* g → Type) (H : Π(h : f ~ g) (p : h pt ⬝ respect_pt g = respect_pt f), P (phomotopy.mk h p)) (h : f ~* g) : P h := begin induction h with h p, refine transport (λp, P (ppi_gen.mk h p)) _ (H h (con_eq_of_eq_con_inv p)), apply to_left_inv !eq_con_inv_equiv_con_eq p end definition phomotopy.sigma_char [constructor] {A B : Type*} (f g : A →* B) : (f ~* g) ≃ Σ(p : f ~ g), p pt ⬝ respect_pt g = respect_pt f := begin fapply equiv.MK : intros h, { exact ⟨h , to_homotopy_pt h⟩ }, { cases h with h p, exact phomotopy.mk h p }, { cases h with h p, exact ap (dpair h) (to_right_inv !eq_con_inv_equiv_con_eq p) }, { induction h using phomotopy.rec' with h p, esimp, exact ap (phomotopy.mk h) (to_right_inv !eq_con_inv_equiv_con_eq p) }, end definition phomotopy.eta_expand [constructor] {A B : Type*} {f g : A →* B} (p : f ~* g) : f ~* g := phomotopy.mk p (to_homotopy_pt p) definition is_trunc_pmap [instance] (n : ℕ₋₂) (A B : Type*) [is_trunc n B] : is_trunc n (A →* B) := is_trunc_equiv_closed_rev _ !pmap.sigma_char definition is_trunc_ppmap [instance] (n : ℕ₋₂) {A B : Type*} [is_trunc n B] : is_trunc n (ppmap A B) := !is_trunc_pmap definition phomotopy_of_eq [constructor] {A B : Type*} {f g : A →* B} (p : f = g) : f ~* g := phomotopy.mk (ap010 pmap.to_fun p) begin induction p, apply idp_con end definition phomotopy_of_eq_idp {A B : Type*} (f : A →* B) : phomotopy_of_eq idp = phomotopy.refl f := idp definition pconcat_eq [constructor] {A B : Type*} {f g h : A →* B} (p : f ~* g) (q : g = h) : f ~* h := p ⬝* phomotopy_of_eq q definition eq_pconcat [constructor] {A B : Type*} {f g h : A →* B} (p : f = g) (q : g ~* h) : f ~* h := phomotopy_of_eq p ⬝* q infix ` ⬝*p `:75 := pconcat_eq infix ` ⬝p* `:75 := eq_pconcat definition pr1_phomotopy_eq {A B : Type*} {f g : A →* B} {p q : f ~* g} (r : p = q) (a : A) : p a = q a := ap010 to_homotopy r a definition pwhisker_left [constructor] (h : B →* C) (p : f ~* g) : h ∘* f ~* h ∘* g := phomotopy.mk (λa, ap h (p a)) abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con⁻¹ ⬝ ap02 _ (to_homotopy_pt p)) end definition pwhisker_right [constructor] (h : C →* A) (p : f ~* g) : f ∘* h ~* g ∘* h := phomotopy.mk (λa, p (h a)) abstract !con.assoc⁻¹ ⬝ whisker_right _ (!ap_con_eq_con_ap)⁻¹ ⬝ !con.assoc ⬝ whisker_left _ (to_homotopy_pt p) end definition pconcat2 [constructor] {A B C : Type*} {h i : B →* C} {f g : A →* B} (q : h ~* i) (p : f ~* g) : h ∘* f ~* i ∘* g := pwhisker_left _ p ⬝* pwhisker_right _ q definition pmap_eq_equiv_internal {A B : Type*} (f g : A →* B) : (f = g) ≃ (f ~* g) := calc (f = g) ≃ pmap.sigma_char f = pmap.sigma_char g : eq_equiv_fn_eq pmap.sigma_char f g ... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g), pathover (λh, h pt = pt) (respect_pt f) p (respect_pt g) : sigma_eq_equiv _ _ ... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g), respect_pt f = ap (λh, h pt) p ⬝ respect_pt g : sigma_equiv_sigma_right (λp, eq_pathover_equiv_Fl p (respect_pt f) (respect_pt g)) ... ≃ Σ(p : pmap.to_fun f = pmap.to_fun g), respect_pt f = ap10 p pt ⬝ respect_pt g : sigma_equiv_sigma_right (λp, equiv_eq_closed_right _ (whisker_right _ (ap_eq_apd10 p _))) ... ≃ Σ(p : pmap.to_fun f ~ pmap.to_fun g), respect_pt f = p pt ⬝ respect_pt g : sigma_equiv_sigma_left' eq_equiv_homotopy ... ≃ Σ(p : pmap.to_fun f ~ pmap.to_fun g), p pt ⬝ respect_pt g = respect_pt f : sigma_equiv_sigma_right (λp, eq_equiv_eq_symm _ _) ... ≃ (f ~* g) : phomotopy.sigma_char f g definition pmap_eq_equiv_internal_idp {A B : Type*} (f : A →* B) : pmap_eq_equiv_internal f f idp = phomotopy.refl f := begin apply ap (phomotopy.mk (homotopy.refl _)), induction B with B b₀, induction f with f f₀, esimp at *, induction f₀, reflexivity end definition eq_of_phomotopy' (p : f ~* g) : f = g := to_inv (pmap_eq_equiv_internal f g) p definition pmap_eq_equiv [constructor] {A B : Type*} (f g : A →* B) : (f = g) ≃ (f ~* g) := begin refine equiv_change_fun (pmap_eq_equiv_internal f g) _, { apply phomotopy_of_eq }, { intro p, induction p, exact pmap_eq_equiv_internal_idp f } end definition eq_of_phomotopy (p : f ~* g) : f = g := to_inv (pmap_eq_equiv f g) p definition eq_of_phomotopy_refl {X Y : Type*} (f : X →* Y) : eq_of_phomotopy (phomotopy.refl f) = idpath f := begin apply to_inv_eq_of_eq, reflexivity end definition phomotopy_of_homotopy {X Y : Type*} {f g : X →* Y} (h : f ~ g) [is_set Y] : f ~* g := begin fapply phomotopy.mk, { exact h }, { apply is_set.elim } end -- TODO: flip arguments in s definition pmap_eq (r : Πa, f a = g a) (s : respect_pt f = (r pt) ⬝ respect_pt g) : f = g := eq_of_phomotopy (phomotopy.mk r s⁻¹) definition pmap_eq_of_homotopy {A B : Type*} {f g : A →* B} [is_set B] (p : f ~ g) : f = g := pmap_eq p !is_set.elim definition phomotopy_of_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) : phomotopy_of_eq (eq_of_phomotopy p) = p := to_right_inv (pmap_eq_equiv f g) p definition phomotopy_rec_on_eq [recursor] {A B : Type*} {f g : A →* B} {Q : (f ~* g) → Type} (p : f ~* g) (H : Π(q : f = g), Q (phomotopy_of_eq q)) : Q p := phomotopy_of_eq_of_phomotopy p ▸ H (eq_of_phomotopy p) definition phomotopy_rec_on_idp [recursor] {A B : Type*} {f : A →* B} {Q : Π{g}, (f ~* g) → Type} {g : A →* B} (p : f ~* g) (H : Q (phomotopy.refl f)) : Q p := begin induction p using phomotopy_rec_on_eq, induction q, exact H end attribute phomotopy.rec' [recursor] definition phomotopy_rec_on_eq_phomotopy_of_eq {A B : Type*} {f g: A →* B} {Q : (f ~* g) → Type} (p : f = g) (H : Π(q : f = g), Q (phomotopy_of_eq q)) : phomotopy_rec_on_eq (phomotopy_of_eq p) H = H p := begin unfold phomotopy_rec_on_eq, refine ap (λp, p ▸ _) !adj ⬝ _, refine !tr_compose⁻¹ ⬝ _, apply apdt end definition phomotopy_rec_on_idp_refl {A B : Type*} (f : A →* B) {Q : Π{g}, (f ~* g) → Type} (H : Q (phomotopy.refl f)) : phomotopy_rec_on_idp phomotopy.rfl H = H := !phomotopy_rec_on_eq_phomotopy_of_eq /- adjunction between (-)₊ : Type → Type* and pType.carrier : Type* → Type -/ definition pmap_equiv_left (A : Type) (B : Type*) : A₊ →* B ≃ (A → B) := begin fapply equiv.MK, { intro f a, cases f with f p, exact f (some a)}, { intro f, fconstructor, intro a, cases a, exact pt, exact f a, reflexivity}, { intro f, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end -- pmap_pbool_pequiv is the pointed equivalence definition pmap_pbool_equiv [constructor] (B : Type*) : (pbool →* B) ≃ B := begin fapply equiv.MK, { intro f, cases f with f p, exact f tt}, { intro b, fconstructor, intro u, cases u, exact pt, exact b, reflexivity}, { intro b, reflexivity}, { intro f, cases f with f p, esimp, fapply pmap_eq, { intro a, cases a; all_goals (esimp at *), exact p⁻¹}, { esimp, exact !con.left_inv⁻¹}}, end /- Pointed maps respecting pointed homotopies. In general we need function extensionality for pap, but for particular F we can do it without function extensionality. This might be preferred, because such pointed homotopies compute. On the other hand, when using function extensionality, it's easier to prove that if p is reflexivity, then the resulting pointed homotopy is reflexivity -/ definition pap (F : (A →* B) → (C →* D)) {f g : A →* B} (p : f ~* g) : F f ~* F g := begin induction p using phomotopy_rec_on_idp, reflexivity end definition pap_refl (F : (A →* B) → (C →* D)) (f : A →* B) : pap F (phomotopy.refl f) = phomotopy.refl (F f) := !phomotopy_rec_on_idp_refl definition ap1_phomotopy {f g : A →* B} (p : f ~* g) : Ω→ f ~* Ω→ g := pap Ω→ p definition ap1_phomotopy_refl {X Y : Type*} (f : X →* Y) : ap1_phomotopy (phomotopy.refl f) = phomotopy.refl (Ω→ f) := !pap_refl --a proof not using function extensionality: definition ap1_phomotopy_explicit {f g : A →* B} (p : f ~* g) : Ω→ f ~* Ω→ g := begin induction p with p q, induction f with f pf, induction g with g pg, induction B with B b, esimp at *, induction q, induction pg, fapply phomotopy.mk, { intro l, refine _ ⬝ !idp_con⁻¹ᵖ, refine !con.assoc ⬝ _, apply inv_con_eq_of_eq_con, apply ap_con_eq_con_ap}, { induction A with A a, unfold [ap_con_eq_con_ap], generalize p a, generalize g a, intro b q, induction q, reflexivity} end definition apn_phomotopy {f g : A →* B} (n : ℕ) (p : f ~* g) : apn n f ~* apn n g := begin induction n with n IH, { exact p}, { exact ap1_phomotopy IH} end -- the following two definitiongs are mostly the same, maybe we should remove one definition ap_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) (a : A) : ap (λf : A →* B, f a) (eq_of_phomotopy p) = p a := ap010 to_homotopy (phomotopy_of_eq_of_phomotopy p) a definition to_fun_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) (a : A) : ap010 pmap.to_fun (eq_of_phomotopy p) a = p a := begin induction p using phomotopy_rec_on_idp, exact ap (λx, ap010 pmap.to_fun x a) !eq_of_phomotopy_refl end definition ap1_eq_of_phomotopy {A B : Type*} {f g : A →* B} (p : f ~* g) : ap Ω→ (eq_of_phomotopy p) = eq_of_phomotopy (ap1_phomotopy p) := begin induction p using phomotopy_rec_on_idp, refine ap02 _ !eq_of_phomotopy_refl ⬝ !eq_of_phomotopy_refl⁻¹ ⬝ ap eq_of_phomotopy _, exact !ap1_phomotopy_refl⁻¹ end /- pointed homotopies between the given pointed maps -/ definition ap1_pid [constructor] {A : Type*} : ap1 (pid A) ~* pid (Ω A) := begin fapply phomotopy.mk, { intro p, esimp, refine !idp_con ⬝ !ap_id}, { reflexivity} end definition ap1_pinverse [constructor] {A : Type*} : ap1 (@pinverse A) ~* @pinverse (Ω A) := begin fapply phomotopy.mk, { intro p, refine !idp_con ⬝ _, exact !inv_eq_inv2⁻¹ }, { reflexivity} end definition ap1_gen_compose {A B C : Type} (g : B → C) (f : A → B) {a₁ a₂ : A} {b₁ b₂ : B} {c₁ c₂ : C} (q₁ : f a₁ = b₁) (q₂ : f a₂ = b₂) (r₁ : g b₁ = c₁) (r₂ : g b₂ = c₂) (p : a₁ = a₂) : ap1_gen (g ∘ f) (ap g q₁ ⬝ r₁) (ap g q₂ ⬝ r₂) p = ap1_gen g r₁ r₂ (ap1_gen f q₁ q₂ p) := begin induction p, induction q₁, induction q₂, induction r₁, induction r₂, reflexivity end definition ap1_gen_compose_idp {A B C : Type} (g : B → C) (f : A → B) {a : A} {b : B} {c : C} (q : f a = b) (r : g b = c) : ap1_gen_compose g f q q r r idp ⬝ (ap (ap1_gen g r r) (ap1_gen_idp f q) ⬝ ap1_gen_idp g r) = ap1_gen_idp (g ∘ f) (ap g q ⬝ r) := begin induction q, induction r, reflexivity end definition ap1_pcompose [constructor] {A B C : Type*} (g : B →* C) (f : A →* B) : ap1 (g ∘* f) ~* ap1 g ∘* ap1 f := phomotopy.mk (ap1_gen_compose g f (respect_pt f) (respect_pt f) (respect_pt g) (respect_pt g)) (ap1_gen_compose_idp g f (respect_pt f) (respect_pt g)) definition ap1_pcompose_pinverse (f : A →* B) : ap1 f ∘* pinverse ~* pinverse ∘* ap1 f := begin fconstructor, { intro p, esimp, refine !con.assoc ⬝ _ ⬝ !con_inv⁻¹, apply whisker_left, refine whisker_right _ !ap_inv ⬝ _ ⬝ !con_inv⁻¹, apply whisker_left, exact !inv_inv⁻¹}, { induction B with B b, induction f with f pf, esimp at *, induction pf, reflexivity}, end definition ap1_pconst [constructor] (A B : Type*) : Ω→(pconst A B) ~* pconst (Ω A) (Ω B) := phomotopy.mk (λp, ap1_gen_idp_left (const A pt) p ⬝ ap_constant p pt) rfl definition ap1_gen_con_left {A B : Type} {a a' : A} {b₀ b₁ b₂ : B} {f : A → b₀ = b₁} {f' : A → b₁ = b₂} {q₀ q₁ : b₀ = b₁} {q₀' q₁' : b₁ = b₂} (r₀ : f a = q₀) (r₁ : f a' = q₁) (r₀' : f' a = q₀') (r₁' : f' a' = q₁') (p : a = a') : ap1_gen (λa, f a ⬝ f' a) (r₀ ◾ r₀') (r₁ ◾ r₁') p = whisker_right q₀' (ap1_gen f r₀ r₁ p) ⬝ whisker_left q₁ (ap1_gen f' r₀' r₁' p) := begin induction r₀, induction r₁, induction r₀', induction r₁', induction p, reflexivity end definition ap1_gen_con_left_idp {A B : Type} {a : A} {b₀ b₁ b₂ : B} {f : A → b₀ = b₁} {f' : A → b₁ = b₂} {q₀ : b₀ = b₁} {q₁ : b₁ = b₂} (r₀ : f a = q₀) (r₁ : f' a = q₁) : ap1_gen_con_left r₀ r₀ r₁ r₁ idp = !con.left_inv ⬝ (ap (whisker_right q₁) !con.left_inv ◾ ap (whisker_left _) !con.left_inv)⁻¹ := begin induction r₀, induction r₁, reflexivity end definition ptransport_change_eq [constructor] {A : Type} (B : A → Type*) {a a' : A} {p q : a = a'} (r : p = q) : ptransport B p ~* ptransport B q := phomotopy.mk (λb, ap (λp, transport B p b) r) begin induction r, apply idp_con end definition pnatural_square {A B : Type} (X : B → Type*) {f g : A → B} (h : Πa, X (f a) →* X (g a)) {a a' : A} (p : a = a') : h a' ∘* ptransport X (ap f p) ~* ptransport X (ap g p) ∘* h a := by induction p; exact !pcompose_pid ⬝* !pid_pcompose⁻¹* definition apn_pid [constructor] {A : Type*} (n : ℕ) : apn n (pid A) ~* pid (Ω[n] A) := begin induction n with n IH, { reflexivity}, { exact ap1_phomotopy IH ⬝* ap1_pid} end definition apn_pconst (A B : Type*) (n : ℕ) : apn n (pconst A B) ~* pconst (Ω[n] A) (Ω[n] B) := begin induction n with n IH, { reflexivity }, { exact ap1_phomotopy IH ⬝* !ap1_pconst } end definition apn_pcompose (n : ℕ) (g : B →* C) (f : A →* B) : apn n (g ∘* f) ~* apn n g ∘* apn n f := begin induction n with n IH, { reflexivity}, { refine ap1_phomotopy IH ⬝* _, apply ap1_pcompose} end definition pcast_idp [constructor] {A : Type*} : pcast (idpath A) ~* pid A := by reflexivity definition pinverse_pinverse (A : Type*) : pinverse ∘* pinverse ~* pid (Ω A) := begin fapply phomotopy.mk, { apply inv_inv}, { reflexivity} end definition pcast_ap_loop [constructor] {A B : Type*} (p : A = B) : pcast (ap Ω p) ~* ap1 (pcast p) := begin fapply phomotopy.mk, { intro a, induction p, esimp, exact (!idp_con ⬝ !ap_id)⁻¹}, { induction p, reflexivity} end definition ap1_pmap_of_map [constructor] {A B : Type} (f : A → B) (a : A) : ap1 (pmap_of_map f a) ~* pmap_of_map (ap f) (idpath a) := begin fapply phomotopy.mk, { intro a, esimp, apply idp_con}, { reflexivity} end definition pcast_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a) {a₁ a₂ : A} (p : a₁ = a₂) : pcast (ap C p) ∘* f a₁ ~* f a₂ ∘* pcast (ap B p) := phomotopy.mk begin induction p, reflexivity end begin induction p, esimp, refine !idp_con ⬝ !idp_con ⬝ !ap_id⁻¹ end /- pointed equivalences -/ structure pequiv (A B : Type*) := mk' :: (to_pmap : A →* B) (to_pinv1 : B →* A) (to_pinv2 : B →* A) (pright_inv : to_pmap ∘* to_pinv1 ~* pid B) (pleft_inv : to_pinv2 ∘* to_pmap ~* pid A) attribute pequiv.to_pmap [coercion] infix ` ≃* `:25 := pequiv definition to_pinv [unfold 3] (f : A ≃* B) : B →* A := pequiv.to_pinv1 f definition pleft_inv' (f : A ≃* B) : to_pinv f ∘* f ~* pid A := let g := to_pinv f in let h := pequiv.to_pinv2 f in calc g ∘* f ~* pid A ∘* (g ∘* f) : by exact !pid_pcompose⁻¹* ... ~* (h ∘* f) ∘* (g ∘* f) : by exact pwhisker_right _ (pequiv.pleft_inv f)⁻¹* ... ~* h ∘* (f ∘* g) ∘* f : by exact !passoc ⬝* pwhisker_left _ !passoc⁻¹* ... ~* h ∘* pid B ∘* f : by exact !pwhisker_left (!pwhisker_right !pequiv.pright_inv) ... ~* h ∘* f : by exact pwhisker_left _ !pid_pcompose ... ~* pid A : by exact pequiv.pleft_inv f definition equiv_of_pequiv [coercion] [constructor] (f : A ≃* B) : A ≃ B := have is_equiv f, from adjointify f (to_pinv f) (pequiv.pright_inv f) (pleft_inv' f), equiv.mk f _ attribute pointed._trans_of_equiv_of_pequiv pequiv._trans_of_to_pmap [unfold 3] definition pequiv.to_is_equiv [instance] [constructor] (f : A ≃* B) : is_equiv (pointed._trans_of_equiv_of_pequiv f) := adjointify f (to_pinv f) (pequiv.pright_inv f) (pleft_inv' f) definition pequiv.to_is_equiv' [instance] [constructor] (f : A ≃* B) : is_equiv (pequiv._trans_of_to_pmap f) := pequiv.to_is_equiv f protected definition pequiv.MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : A ≃* B := pequiv.mk' f g g fg gf definition pinv [constructor] (f : A →* B) (H : is_equiv f) : B →* A := pmap.mk f⁻¹ᶠ (ap f⁻¹ᶠ (respect_pt f)⁻¹ ⬝ (left_inv f pt)) definition pequiv_of_pmap [constructor] (f : A →* B) (H : is_equiv f) : A ≃* B := pequiv.mk' f (pinv f H) (pinv f H) abstract begin fapply phomotopy.mk, exact right_inv f, induction f with f f₀, induction B with B b₀, esimp at *, induction f₀, esimp, exact adj f pt ⬝ ap02 f !idp_con⁻¹ end end abstract begin fapply phomotopy.mk, exact left_inv f, induction f with f f₀, induction B with B b₀, esimp at *, induction f₀, esimp, exact !idp_con⁻¹ ⬝ !idp_con⁻¹ end end definition pequiv.mk [constructor] (f : A → B) (H : is_equiv f) (p : f pt = pt) : A ≃* B := pequiv_of_pmap (pmap.mk f p) H definition pequiv_of_equiv [constructor] (f : A ≃ B) (H : f pt = pt) : A ≃* B := pequiv.mk f _ H protected definition pequiv.MK' [constructor] (f : A →* B) (g : B → A) (gf : Πa, g (f a) = a) (fg : Πb, f (g b) = b) : A ≃* B := pequiv.mk f (adjointify f g fg gf) (respect_pt f) /- reflexivity and symmetry (transitivity is below) -/ protected definition pequiv.refl [refl] [constructor] (A : Type*) : A ≃* A := pequiv.mk' (pid A) (pid A) (pid A) !pid_pcompose !pcompose_pid protected definition pequiv.rfl [constructor] : A ≃* A := pequiv.refl A protected definition pequiv.symm [symm] [constructor] (f : A ≃* B) : B ≃* A := pequiv.MK (to_pinv f) f (pequiv.pright_inv f) (pleft_inv' f) postfix `⁻¹ᵉ*`:(max + 1) := pequiv.symm definition pleft_inv (f : A ≃* B) : f⁻¹ᵉ* ∘* f ~* pid A := pleft_inv' f definition pright_inv (f : A ≃* B) : f ∘* f⁻¹ᵉ* ~* pid B := pequiv.pright_inv f definition to_pmap_pequiv_of_pmap {A B : Type*} (f : A →* B) (H : is_equiv f) : pequiv.to_pmap (pequiv_of_pmap f H) = f := by reflexivity definition to_pmap_pequiv_MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : pequiv.MK f g gf fg ~* f := by reflexivity definition to_pinv_pequiv_MK [constructor] (f : A →* B) (g : B →* A) (gf : g ∘* f ~* !pid) (fg : f ∘* g ~* !pid) : to_pinv (pequiv.MK f g gf fg) ~* g := by reflexivity /- more on pointed equivalences -/ definition pequiv_ap [constructor] {A : Type} (B : A → Type*) {a a' : A} (p : a = a') : B a ≃* B a' := pequiv_of_pmap (ptransport B p) !is_equiv_tr definition pequiv_change_fun [constructor] (f : A ≃* B) (f' : A →* B) (Heq : f ~ f') : A ≃* B := pequiv_of_pmap f' (is_equiv.homotopy_closed f Heq) definition pequiv_change_inv [constructor] (f : A ≃* B) (f' : B →* A) (Heq : to_pinv f ~ f') : A ≃* B := pequiv.MK' f f' (to_left_inv (equiv_change_inv f Heq)) (to_right_inv (equiv_change_inv f Heq)) definition pequiv_rect' (f : A ≃* B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition pua {A B : Type*} (f : A ≃* B) : A = B := pType_eq (equiv_of_pequiv f) !respect_pt definition pequiv_of_eq [constructor] {A B : Type*} (p : A = B) : A ≃* B := pequiv_of_pmap (pcast p) !is_equiv_tr definition eq_of_pequiv {A B : Type*} (p : A ≃* B) : A = B := pType_eq (equiv_of_pequiv p) !respect_pt definition peap {A B : Type*} (F : Type* → Type*) (p : A ≃* B) : F A ≃* F B := pequiv_of_pmap (pcast (ap F (eq_of_pequiv p))) begin cases eq_of_pequiv p, apply is_equiv_id end -- rename pequiv_of_eq_natural definition pequiv_of_eq_commute [constructor] {A : Type} {B C : A → Type*} (f : Πa, B a →* C a) {a₁ a₂ : A} (p : a₁ = a₂) : pequiv_of_eq (ap C p) ∘* f a₁ ~* f a₂ ∘* pequiv_of_eq (ap B p) := pcast_commute f p -- definition pequiv.eta_expand [constructor] {A B : Type*} (f : A ≃* B) : A ≃* B := -- pequiv.mk' f (to_pinv f) (pequiv.to_pinv2 f) (pright_inv f) _ /- the theorem pequiv_eq, which gives a condition for two pointed equivalences are equal is in types.equiv to avoid circular imports -/ /- computation rules of pointed homotopies, possibly combined with pointed equivalences -/ definition pcancel_left (f : B ≃* C) {g h : A →* B} (p : f ∘* g ~* f ∘* h) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_left f⁻¹ᵉ* p ⬝* _: refine !passoc⁻¹* ⬝* _: refine pwhisker_right _ (pleft_inv f) ⬝* _: apply pid_pcompose end definition pcancel_right (f : A ≃* B) {g h : B →* C} (p : g ∘* f ~* h ∘* f) : g ~* h := begin refine _⁻¹* ⬝* pwhisker_right f⁻¹ᵉ* p ⬝* _: refine !passoc ⬝* _: refine pwhisker_left _ (pright_inv f) ⬝* _: apply pcompose_pid end definition phomotopy_pinv_right_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : g ∘* f ~* h) : g ~* h ∘* f⁻¹ᵉ* := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pright_inv f) ⬝* _, apply pcompose_pid end definition phomotopy_of_pinv_right_phomotopy {f : B ≃* A} {g : B →* C} {h : A →* C} (p : g ∘* f⁻¹ᵉ* ~* h) : g ~* h ∘* f := begin refine _ ⬝* pwhisker_right _ p, symmetry, refine !passoc ⬝* _, refine pwhisker_left _ (pleft_inv f) ⬝* _, apply pcompose_pid end definition pinv_right_phomotopy_of_phomotopy {f : A ≃* B} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f) : h ∘* f⁻¹ᵉ* ~* g := (phomotopy_pinv_right_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_right {f : B ≃* A} {g : B →* C} {h : A →* C} (p : h ~* g ∘* f⁻¹ᵉ*) : h ∘* f ~* g := (phomotopy_of_pinv_right_phomotopy p⁻¹*)⁻¹* definition phomotopy_pinv_left_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : f ∘* g ~* h) : g ~* f⁻¹ᵉ* ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pleft_inv f) ⬝* _, apply pid_pcompose end definition phomotopy_of_pinv_left_phomotopy {f : C ≃* B} {g : A →* B} {h : A →* C} (p : f⁻¹ᵉ* ∘* g ~* h) : g ~* f ∘* h := begin refine _ ⬝* pwhisker_left _ p, symmetry, refine !passoc⁻¹* ⬝* _, refine pwhisker_right _ (pright_inv f) ⬝* _, apply pid_pcompose end definition pinv_left_phomotopy_of_phomotopy {f : B ≃* C} {g : A →* B} {h : A →* C} (p : h ~* f ∘* g) : f⁻¹ᵉ* ∘* h ~* g := (phomotopy_pinv_left_of_phomotopy p⁻¹*)⁻¹* definition phomotopy_of_phomotopy_pinv_left {f : C ≃* B} {g : A →* B} {h : A →* C} (p : h ~* f⁻¹ᵉ* ∘* g) : f ∘* h ~* g := (phomotopy_of_pinv_left_phomotopy p⁻¹*)⁻¹* definition pcompose2 {A B C : Type*} {g g' : B →* C} {f f' : A →* B} (q : g ~* g') (p : f ~* f') : g ∘* f ~* g' ∘* f' := pwhisker_right f q ⬝* pwhisker_left g' p infixr ` ◾* `:80 := pcompose2 definition phomotopy_pinv_of_phomotopy_pid {A B : Type*} {f : A →* B} {g : B ≃* A} (p : g ∘* f ~* pid A) : f ~* g⁻¹ᵉ* := phomotopy_pinv_left_of_phomotopy p ⬝* !pcompose_pid definition phomotopy_pinv_of_phomotopy_pid' {A B : Type*} {f : A →* B} {g : B ≃* A} (p : f ∘* g ~* pid B) : f ~* g⁻¹ᵉ* := phomotopy_pinv_right_of_phomotopy p ⬝* !pid_pcompose definition pinv_phomotopy_of_pid_phomotopy {A B : Type*} {f : A →* B} {g : B ≃* A} (p : pid A ~* g ∘* f) : g⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid p⁻¹*)⁻¹* definition pinv_phomotopy_of_pid_phomotopy' {A B : Type*} {f : A →* B} {g : B ≃* A} (p : pid B ~* f ∘* g) : g⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid' p⁻¹*)⁻¹* definition pinv_pcompose_cancel_left {A B C : Type*} (g : B ≃* C) (f : A →* B) : g⁻¹ᵉ* ∘* (g ∘* f) ~* f := !passoc⁻¹* ⬝* pwhisker_right f !pleft_inv ⬝* !pid_pcompose definition pcompose_pinv_cancel_left {A B C : Type*} (g : C ≃* B) (f : A →* B) : g ∘* (g⁻¹ᵉ* ∘* f) ~* f := !passoc⁻¹* ⬝* pwhisker_right f !pright_inv ⬝* !pid_pcompose definition pinv_pcompose_cancel_right {A B C : Type*} (g : B →* C) (f : B ≃* A) : (g ∘* f⁻¹ᵉ*) ∘* f ~* g := !passoc ⬝* pwhisker_left g !pleft_inv ⬝* !pcompose_pid definition pcompose_pinv_cancel_right {A B C : Type*} (g : B →* C) (f : A ≃* B) : (g ∘* f) ∘* f⁻¹ᵉ* ~* g := !passoc ⬝* pwhisker_left g !pright_inv ⬝* !pcompose_pid definition pinv_pinv {A B : Type*} (f : A ≃* B) : (f⁻¹ᵉ*)⁻¹ᵉ* ~* f := (phomotopy_pinv_of_phomotopy_pid (pleft_inv f))⁻¹* definition pinv2 {A B : Type*} {f f' : A ≃* B} (p : f ~* f') : f⁻¹ᵉ* ~* f'⁻¹ᵉ* := phomotopy_pinv_of_phomotopy_pid (pinv_right_phomotopy_of_phomotopy (!pid_pcompose ⬝* p)⁻¹*) postfix [parsing_only] `⁻²*`:(max+10) := pinv2 protected definition pequiv.trans [trans] [constructor] (f : A ≃* B) (g : B ≃* C) : A ≃* C := pequiv.MK (g ∘* f) (f⁻¹ᵉ* ∘* g⁻¹ᵉ*) abstract !passoc ⬝* pwhisker_left _ (pinv_pcompose_cancel_left g f) ⬝* pleft_inv f end abstract !passoc ⬝* pwhisker_left _ (pcompose_pinv_cancel_left f g⁻¹ᵉ*) ⬝* pright_inv g end definition pequiv_compose {A B C : Type*} (g : B ≃* C) (f : A ≃* B) : A ≃* C := pequiv.trans f g infix ` ⬝e* `:75 := pequiv.trans infixr ` ∘*ᵉ `:60 := pequiv_compose definition to_pmap_pequiv_trans {A B C : Type*} (f : A ≃* B) (g : B ≃* C) : pequiv.to_pmap (f ⬝e* g) = g ∘* f := by reflexivity definition to_fun_pequiv_trans {X Y Z : Type*} (f : X ≃* Y) (g :Y ≃* Z) : f ⬝e* g ~ g ∘ f := λx, idp definition peconcat_eq {A B C : Type*} (p : A ≃* B) (q : B = C) : A ≃* C := p ⬝e* pequiv_of_eq q definition eq_peconcat {A B C : Type*} (p : A = B) (q : B ≃* C) : A ≃* C := pequiv_of_eq p ⬝e* q infix ` ⬝e*p `:75 := peconcat_eq infix ` ⬝pe* `:75 := eq_peconcat definition trans_pinv {A B C : Type*} (f : A ≃* B) (g : B ≃* C) : (f ⬝e* g)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g⁻¹ᵉ* := by reflexivity definition pinv_trans_pinv_left {A B C : Type*} (f : B ≃* A) (g : B ≃* C) : (f⁻¹ᵉ* ⬝e* g)⁻¹ᵉ* ~* f ∘* g⁻¹ᵉ* := by reflexivity definition pinv_trans_pinv_right {A B C : Type*} (f : A ≃* B) (g : C ≃* B) : (f ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f⁻¹ᵉ* ∘* g := by reflexivity definition pinv_trans_pinv_pinv {A B C : Type*} (f : B ≃* A) (g : C ≃* B) : (f⁻¹ᵉ* ⬝e* g⁻¹ᵉ*)⁻¹ᵉ* ~* f ∘* g := by reflexivity /- pointed equivalences between particular pointed types -/ -- TODO: remove is_equiv_apn, which is proven again here definition loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : Ω[n] A ≃* Ω[n] B := pequiv.MK (apn n f) (apn n f⁻¹ᵉ*) abstract begin induction n with n IH, { apply pleft_inv}, { replace nat.succ n with n + 1, rewrite [+apn_succ], refine !ap1_pcompose⁻¹* ⬝* _, refine ap1_phomotopy IH ⬝* _, apply ap1_pid} end end abstract begin induction n with n IH, { apply pright_inv}, { replace nat.succ n with n + 1, rewrite [+apn_succ], refine !ap1_pcompose⁻¹* ⬝* _, refine ap1_phomotopy IH ⬝* _, apply ap1_pid} end end definition loop_pequiv_loop [constructor] (f : A ≃* B) : Ω A ≃* Ω B := loopn_pequiv_loopn 1 f definition loop_pequiv_eq_closed [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK (a = a) idp ≃* pointed.MK (a' = a') idp := pequiv_of_equiv (loop_equiv_eq_closed p) (con.left_inv p) definition to_pmap_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : loopn_pequiv_loopn n f ~* apn n f := by reflexivity definition to_pinv_loopn_pequiv_loopn [constructor] (n : ℕ) (f : A ≃* B) : (loopn_pequiv_loopn n f)⁻¹ᵉ* ~* apn n f⁻¹ᵉ* := by reflexivity definition loopn_pequiv_loopn_con (n : ℕ) (f : A ≃* B) (p q : Ω[n+1] A) : loopn_pequiv_loopn (n+1) f (p ⬝ q) = loopn_pequiv_loopn (n+1) f p ⬝ loopn_pequiv_loopn (n+1) f q := ap1_con (loopn_pequiv_loopn n f) p q definition loop_pequiv_loop_con {A B : Type*} (f : A ≃* B) (p q : Ω A) : loop_pequiv_loop f (p ⬝ q) = loop_pequiv_loop f p ⬝ loop_pequiv_loop f q := loopn_pequiv_loopn_con 0 f p q definition loopn_pequiv_loopn_rfl (n : ℕ) (A : Type*) : loopn_pequiv_loopn n (pequiv.refl A) ~* pequiv.refl (Ω[n] A) := begin exact !to_pmap_loopn_pequiv_loopn ⬝* apn_pid n, end definition loop_pequiv_loop_rfl (A : Type*) : loop_pequiv_loop (pequiv.refl A) ~* pequiv.refl (Ω A) := loopn_pequiv_loopn_rfl 1 A definition apn_pinv (n : ℕ) {A B : Type*} (f : A ≃* B) : Ω→[n] f⁻¹ᵉ* ~* (loopn_pequiv_loopn n f)⁻¹ᵉ* := by reflexivity definition pmap_functor [constructor] {A A' B B' : Type*} (f : A' →* A) (g : B →* B') : ppmap A B →* ppmap A' B' := pmap.mk (λh, g ∘* h ∘* f) abstract begin fapply pmap_eq, { esimp, intro a, exact respect_pt g}, { rewrite [▸*, ap_constant], apply idp_con} end end definition pequiv_pinverse (A : Type*) : Ω A ≃* Ω A := pequiv_of_pmap pinverse !is_equiv_eq_inverse definition pequiv_of_eq_pt [constructor] {A : Type} {a a' : A} (p : a = a') : pointed.MK A a ≃* pointed.MK A a' := pequiv_of_pmap (pmap_of_eq_pt p) !is_equiv_id definition pointed_eta_pequiv [constructor] (A : Type*) : A ≃* pointed.MK A pt := pequiv.mk id !is_equiv_id idp /- every pointed map is homotopic to one of the form `pmap_of_map _ _`, up to some pointed equivalences -/ definition phomotopy_pmap_of_map {A B : Type*} (f : A →* B) : (pointed_eta_pequiv B ⬝e* (pequiv_of_eq_pt (respect_pt f))⁻¹ᵉ*) ∘* f ∘* (pointed_eta_pequiv A)⁻¹ᵉ* ~* pmap_of_map f pt := begin fapply phomotopy.mk, { reflexivity}, { symmetry, exact (!ap_id ⬝ !idp_con) ◾ (!idp_con ⬝ !ap_id) ⬝ !con.right_inv } end /- properties of iterated loop space -/ variable (A) definition loopn_succ_in (n : ℕ) : Ω[succ n] A ≃* Ω[n] (Ω A) := begin induction n with n IH, { reflexivity}, { exact loop_pequiv_loop IH} end definition loopn_add (n m : ℕ) : Ω[n] (Ω[m] A) ≃* Ω[m+n] (A) := begin induction n with n IH, { reflexivity}, { exact loop_pequiv_loop IH} end definition loopn_succ_out (n : ℕ) : Ω[succ n] A ≃* Ω(Ω[n] A) := by reflexivity variable {A} definition loopn_succ_in_con {n : ℕ} (p q : Ω[succ (succ n)] A) : loopn_succ_in A (succ n) (p ⬝ q) = loopn_succ_in A (succ n) p ⬝ loopn_succ_in A (succ n) q := !loop_pequiv_loop_con definition loopn_loop_irrel (p : point A = point A) : Ω(pointed.Mk p) = Ω[2] A := begin intros, fapply pType_eq, { esimp, transitivity _, apply eq_equiv_fn_eq_of_equiv (equiv_eq_closed_right _ p⁻¹), esimp, apply eq_equiv_eq_closed, apply con.right_inv, apply con.right_inv}, { esimp, apply con.left_inv} end definition loopn_space_loop_irrel (n : ℕ) (p : point A = point A) : Ω[succ n](pointed.Mk p) = Ω[succ (succ n)] A :> pType := calc Ω[succ n](pointed.Mk p) = Ω[n](Ω (pointed.Mk p)) : eq_of_pequiv !loopn_succ_in ... = Ω[n] (Ω[2] A) : loopn_loop_irrel ... = Ω[2+n] A : eq_of_pequiv !loopn_add ... = Ω[n+2] A : by rewrite [algebra.add.comm] definition apn_succ_phomotopy_in (n : ℕ) (f : A →* B) : loopn_succ_in B n ∘* Ω→[n + 1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n := begin induction n with n IH, { reflexivity}, { exact !ap1_pcompose⁻¹* ⬝* ap1_phomotopy IH ⬝* !ap1_pcompose} end definition loopn_succ_in_natural {A B : Type*} (n : ℕ) (f : A →* B) : loopn_succ_in B n ∘* Ω→[n+1] f ~* Ω→[n] (Ω→ f) ∘* loopn_succ_in A n := !apn_succ_phomotopy_in definition loopn_succ_in_inv_natural {A B : Type*} (n : ℕ) (f : A →* B) : Ω→[n + 1] f ∘* (loopn_succ_in A n)⁻¹ᵉ* ~* (loopn_succ_in B n)⁻¹ᵉ* ∘* Ω→[n] (Ω→ f):= begin apply pinv_right_phomotopy_of_phomotopy, refine _ ⬝* !passoc⁻¹*, apply phomotopy_pinv_left_of_phomotopy, apply apn_succ_phomotopy_in end end pointed
3b520cb8468765f9985a1801a1350d1473b6c874
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/complex.lean
88b939cc3fb71afa76f707d7b31ff0b9cd36fd8f
[ "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
1,550
lean
/- Copyright (c) 2023 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import data.complex.module import ring_theory.norm import ring_theory.trace /-! # Lemmas about `algebra.trace` and `algebra.norm` on `ℂ` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4.-/ open complex lemma algebra.left_mul_matrix_complex (z : ℂ) : algebra.left_mul_matrix complex.basis_one_I z = !![z.re, -z.im; z.im, z.re] := begin ext i j, rw [algebra.left_mul_matrix_eq_repr_mul, complex.coe_basis_one_I_repr, complex.coe_basis_one_I, mul_re, mul_im, matrix.of_apply], fin_cases j, { simp_rw [matrix.cons_val_zero, one_re, one_im, mul_zero, mul_one, sub_zero, zero_add], fin_cases i; refl }, { simp_rw [matrix.cons_val_one, matrix.head_cons, I_re, I_im, mul_zero, mul_one, zero_sub, add_zero], fin_cases i; refl }, end lemma algebra.trace_complex_apply (z : ℂ) : algebra.trace ℝ ℂ z = 2*z.re := begin rw [algebra.trace_eq_matrix_trace complex.basis_one_I, algebra.left_mul_matrix_complex, matrix.trace_fin_two], exact (two_mul _).symm end lemma algebra.norm_complex_apply (z : ℂ) : algebra.norm ℝ z = z.norm_sq := begin rw [algebra.norm_eq_matrix_det complex.basis_one_I, algebra.left_mul_matrix_complex, matrix.det_fin_two, norm_sq_apply], simp, end lemma algebra.norm_complex_eq : algebra.norm ℝ = norm_sq.to_monoid_hom := monoid_hom.ext algebra.norm_complex_apply
a2e3a1182cb6df22e3e7b3839ac58e439bbb130b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/star/spectrum.lean
863448cb51d90c263789fc2ebc2883d1268f114b
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
7,825
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.basic import analysis.normed_space.spectrum import algebra.star.module import analysis.normed_space.star.exponential import algebra.star.star_alg_hom /-! # Spectral properties in C⋆-algebras In this file, we establish various propreties related to the spectrum of elements in C⋆-algebras. -/ local postfix `⋆`:std.prec.max_plus := star section open_locale topological_space ennreal open filter ennreal spectrum cstar_ring section unitary_spectrum variables {𝕜 : Type*} [normed_field 𝕜] {E : Type*} [normed_ring E] [star_ring E] [cstar_ring E] [normed_algebra 𝕜 E] [complete_space E] [nontrivial E] lemma unitary.spectrum_subset_circle (u : unitary E) : spectrum 𝕜 (u : E) ⊆ metric.sphere 0 1 := begin refine λ k hk, mem_sphere_zero_iff_norm.mpr (le_antisymm _ _), { simpa only [cstar_ring.norm_coe_unitary u] using norm_le_norm_of_mem hk }, { rw ←unitary.coe_to_units_apply u at hk, have hnk := ne_zero_of_mem_of_unit hk, rw [←inv_inv (unitary.to_units u), ←spectrum.map_inv, set.mem_inv] at hk, have : ∥k∥⁻¹ ≤ ∥↑((unitary.to_units u)⁻¹)∥, simpa only [norm_inv] using norm_le_norm_of_mem hk, simpa using inv_le_of_inv_le (norm_pos_iff.mpr hnk) this } end lemma spectrum.subset_circle_of_unitary {u : E} (h : u ∈ unitary E) : spectrum 𝕜 u ⊆ metric.sphere 0 1 := unitary.spectrum_subset_circle ⟨u, h⟩ end unitary_spectrum section complex_scalars open complex variables {A : Type*} [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] [cstar_ring A] local notation `↑ₐ` := algebra_map ℂ A lemma is_self_adjoint.spectral_radius_eq_nnnorm [norm_one_class A] {a : A} (ha : is_self_adjoint a) : spectral_radius ℂ a = ∥a∥₊ := begin have hconst : tendsto (λ n : ℕ, (∥a∥₊ : ℝ≥0∞)) at_top _ := tendsto_const_nhds, refine tendsto_nhds_unique _ hconst, convert (spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a : A)).comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two), refine funext (λ n, _), rw [function.comp_app, ha.nnnorm_pow_two_pow, ennreal.coe_pow, ←rpow_nat_cast, ←rpow_mul], simp, end lemma is_star_normal.spectral_radius_eq_nnnorm [norm_one_class A] (a : A) [is_star_normal a] : spectral_radius ℂ a = ∥a∥₊ := begin refine (ennreal.pow_strict_mono two_ne_zero).injective _, have heq : (λ n : ℕ, ((∥(a⋆ * a) ^ n∥₊ ^ (1 / n : ℝ)) : ℝ≥0∞)) = (λ x, x ^ 2) ∘ (λ n : ℕ, ((∥a ^ n∥₊ ^ (1 / n : ℝ)) : ℝ≥0∞)), { funext, rw [function.comp_apply, ←rpow_nat_cast, ←rpow_mul, mul_comm, rpow_mul, rpow_nat_cast, ←coe_pow, sq, ←nnnorm_star_mul_self, commute.mul_pow (star_comm_self' a), star_pow], }, have h₂ := ((ennreal.continuous_pow 2).tendsto (spectral_radius ℂ a)).comp (spectrum.pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius a), rw ←heq at h₂, convert tendsto_nhds_unique h₂ (pow_nnnorm_pow_one_div_tendsto_nhds_spectral_radius (a⋆ * a)), rw [(is_self_adjoint.star_mul_self a).spectral_radius_eq_nnnorm, sq, nnnorm_star_mul_self, coe_mul], end /-- Any element of the spectrum of a selfadjoint is real. -/ theorem is_self_adjoint.mem_spectrum_eq_re [star_module ℂ A] [nontrivial A] {a : A} (ha : is_self_adjoint a) {z : ℂ} (hz : z ∈ spectrum ℂ a) : z = z.re := begin let Iu := units.mk0 I I_ne_zero, have : exp ℂ (I • z) ∈ spectrum ℂ (exp ℂ (I • a)), by simpa only [units.smul_def, units.coe_mk0] using spectrum.exp_mem_exp (Iu • a) (smul_mem_smul_iff.mpr hz), exact complex.ext (of_real_re _) (by simpa only [←complex.exp_eq_exp_ℂ, mem_sphere_zero_iff_norm, norm_eq_abs, abs_exp, real.exp_eq_one_iff, smul_eq_mul, I_mul, neg_eq_zero] using spectrum.subset_circle_of_unitary ha.exp_i_smul_unitary this), end /-- Any element of the spectrum of a selfadjoint is real. -/ theorem self_adjoint.mem_spectrum_eq_re [star_module ℂ A] [nontrivial A] (a : self_adjoint A) {z : ℂ} (hz : z ∈ spectrum ℂ (a : A)) : z = z.re := a.prop.mem_spectrum_eq_re hz /-- The spectrum of a selfadjoint is real -/ theorem is_self_adjoint.coe_re_map_spectrum [star_module ℂ A] [nontrivial A] {a : A} (ha : is_self_adjoint a) : spectrum ℂ a = (coe ∘ re '' (spectrum ℂ a) : set ℂ) := le_antisymm (λ z hz, ⟨z, hz, (ha.mem_spectrum_eq_re hz).symm⟩) (λ z, by { rintros ⟨z, hz, rfl⟩, simpa only [(ha.mem_spectrum_eq_re hz).symm, function.comp_app] using hz }) /-- The spectrum of a selfadjoint is real -/ theorem self_adjoint.coe_re_map_spectrum [star_module ℂ A] [nontrivial A] (a : self_adjoint A) : spectrum ℂ (a : A) = (coe ∘ re '' (spectrum ℂ (a : A)) : set ℂ) := a.property.coe_re_map_spectrum end complex_scalars namespace star_alg_hom variables {F A B : Type*} [normed_ring A] [normed_algebra ℂ A] [norm_one_class A] [complete_space A] [star_ring A] [cstar_ring A] [normed_ring B] [normed_algebra ℂ B] [norm_one_class B] [complete_space B] [star_ring B] [cstar_ring B] [hF : star_alg_hom_class F ℂ A B] (φ : F) include hF /-- A star algebra homomorphism of complex C⋆-algebras is norm contractive. -/ lemma nnnorm_apply_le (a : A) : ∥(φ a : B)∥₊ ≤ ∥a∥₊ := begin suffices : ∀ s : A, is_self_adjoint s → ∥φ s∥₊ ≤ ∥s∥₊, { exact nonneg_le_nonneg_of_sq_le_sq zero_le' (by simpa only [nnnorm_star_mul_self, map_star, map_mul] using this _ (is_self_adjoint.star_mul_self a)) }, { intros s hs, simpa only [hs.spectral_radius_eq_nnnorm, (hs.star_hom_apply φ).spectral_radius_eq_nnnorm, coe_le_coe] using (show spectral_radius ℂ (φ s) ≤ spectral_radius ℂ s, from supr_le_supr_of_subset (alg_hom.spectrum_apply_subset φ s)) } end /-- A star algebra homomorphism of complex C⋆-algebras is norm contractive. -/ lemma norm_apply_le (a : A) : ∥(φ a : B)∥ ≤ ∥a∥ := nnnorm_apply_le φ a /-- Star algebra homomorphisms between C⋆-algebras are continuous linear maps. See note [lower instance priority] -/ @[priority 100] noncomputable instance : continuous_linear_map_class F ℂ A B := { map_continuous := λ φ, add_monoid_hom_class.continuous_of_bound φ 1 (by simpa only [one_mul] using nnnorm_apply_le φ), .. alg_hom_class.linear_map_class } end star_alg_hom end namespace weak_dual open continuous_map complex open_locale complex_star_module variables {F A : Type*} [normed_ring A] [normed_algebra ℂ A] [nontrivial A] [complete_space A] [star_ring A] [cstar_ring A] [star_module ℂ A] [hF : alg_hom_class F ℂ A ℂ] include hF /-- This instance is provided instead of `star_alg_hom_class` to avoid type class inference loops. See note [lower instance priority] -/ @[priority 100] noncomputable instance : star_hom_class F A ℂ := { coe := λ φ, φ, coe_injective' := fun_like.coe_injective', map_star := λ φ a, begin suffices hsa : ∀ s : self_adjoint A, (φ s)⋆ = φ s, { rw ←real_part_add_I_smul_imaginary_part a, simp only [map_add, map_smul, star_add, star_smul, hsa, self_adjoint.star_coe_eq] }, { intros s, have := alg_hom.apply_mem_spectrum φ (s : A), rw self_adjoint.coe_re_map_spectrum s at this, rcases this with ⟨⟨_, _⟩, _, heq⟩, rw [←heq, is_R_or_C.star_def, is_R_or_C.conj_of_real] } end } /-- This is not an instance to avoid type class inference loops. See `weak_dual.complex.star_hom_class`. -/ noncomputable def _root_.alg_hom_class.star_alg_hom_class : star_alg_hom_class F ℂ A ℂ := { .. hF, .. weak_dual.complex.star_hom_class } end weak_dual
64a2fc390ee3cd040ad32607d5b0080a80f28787
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/algebra/ring/basic.lean
229d60a8c747f1ae3c9baf48a3302d995eceb123
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
40,588
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ /-- A semiring is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative monoid (`monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). The actual definition extends `monoid_with_zero` instead of `monoid` and `mul_zero_class`. -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } /-- An element `a` of a semiring is even if there exists `k` such `a = 2*k`. -/ def even (a : α) : Prop := ∃ k, a = 2*k lemma even_iff_two_dvd {a : α} : even a ↔ 2 ∣ a := iff.rfl /-- An element `a` of a semiring is odd if there exists `k` such `a = 2*k + 1`. -/ def odd (a : α) : Prop := ∃ k, a = 2*k + 1 theorem dvd_add {a b c : α} (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma coe_mul_right {R : Type*} [semiring R] (r : R) : ⇑(mul_right r) = (* r) := rfl lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : mul_right r a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. This extends from both `monoid_hom` and `monoid_with_zero_hom` in order to put the fields in a sensible order, even though `monoid_with_zero_hom` already extends `monoid_hom`. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β, monoid_with_zero_hom α β infixr ` →+* `:25 := ring_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a `monoid_with_zero_hom R S`. The `simp`-normal form is `(f : monoid_with_zero_hom R S)`. -/ add_decl_doc ring_hom.to_monoid_with_zero_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as a monoid homomorphism `R →* S`. The `simp`-normal form is `(f : R →* S)`. -/ add_decl_doc ring_hom.to_monoid_hom /-- Reinterpret a ring homomorphism `f : R →+* S` as an additive monoid homomorphism `R →+ S`. The `simp`-normal form is `(f : R →+ S)`. -/ add_decl_doc ring_hom.to_add_monoid_hom namespace ring_hom section coe /-! Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`. See note [implicit instance arguments]. -/ variables {rα : semiring α} {rβ : semiring β} include rα rβ instance : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ initialize_simps_projections ring_hom (to_fun → apply) @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl instance has_coe_monoid_hom : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp] lemma to_monoid_hom_eq_coe (f : α →+* β) : f.to_monoid_hom = f := rfl @[simp] lemma coe_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →* β) = ⟨f, h₁, h₂⟩ := rfl instance has_coe_add_monoid_hom : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_add_monoid_hom (f : α →+* β) : ⇑(f : α →+ β) = f := rfl @[simp] lemma to_add_monoid_hom_eq_coe (f : α →+* β) : f.to_add_monoid_hom = f := rfl @[simp] lemma coe_add_monoid_hom_mk (f : α → β) (h₁ h₂ h₃ h₄) : ((⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) : α →+ β) = ⟨f, h₃, h₄⟩ := rfl end coe variables [rα : semiring α] [rβ : semiring β] section include rα rβ variables (f : α →+* β) {x y : α} {rα rβ} theorem congr_fun {f g : α →+* β} (h : f = g) (x : α) : f x = g x := congr_arg (λ h : α →+* β, h x) h theorem congr_arg (f : α →+* β) {x y : α} (h : x = y) : f x = f y := congr_arg (λ x : α, f x) h theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ @[simp] lemma mk_coe (f : α →+* β) (h₁ h₂ h₃ h₄) : ring_hom.mk f h₁ h₂ h₃ h₄ = f := ext $ λ _, rfl theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, ext (λ x, add_monoid_hom.congr_fun h x) theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, ext (λ x, monoid_hom.congr_fun h x) /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- Ring homomorphisms preserve `bit0`. -/ @[simp] lemma map_bit0 (f : α →+* β) (a : α) : f (bit0 a) = bit0 (f a) := map_add _ _ _ /-- Ring homomorphisms preserve `bit1`. -/ @[simp] lemma map_bit1 (f : α →+* β) (a : α) : f (bit1 a) = bit1 (f a) := by simp [bit1] /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map (f.to_monoid_hom) end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα instance : inhabited (α →+* α) := ⟨id α⟩ @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom /-- A commutative semiring is a `semiring` with commutative multiplication. In other words, it is a type with the following structures: additive commutative monoid (`add_comm_monoid`), multiplicative commutative monoid (`comm_monoid`), distributive laws (`distrib`), and multiplication by zero law (`mul_zero_class`). -/ @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α @[priority 100] -- see Note [lower instance priority] instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := by simp only [two_mul, add_mul, mul_add, add_assoc, mul_comm b] @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ /-- A ring is a type with the following structures: additive commutative group (`add_comm_group`), multiplicative monoid (`monoid`), and distributive laws (`distrib`). Equivalently, a ring is a `semiring` with a negation operation making it an additive group. -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ @[priority 200] instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : ring β := { .. hf.add_comm_group_sub f zero add neg sub, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := by simpa only [sub_eq_add_neg, neg_mul_eq_mul_neg] using mul_add a b (-c) alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := by simpa only [sub_eq_add_neg, neg_mul_eq_neg_mul] using add_mul a (-b) c alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom /-- A commutative ring is a `ring` with commutative multiplication. -/ @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α @[priority 100] -- see Note [lower instance priority] instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.injective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `comm_ring` instance along an injective function, with a subtraction (`-`) that is not necessarily defeq to `a + -b`. -/ protected def function.surjective.comm_ring_sub [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] [has_sub β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) (sub : ∀ x y, f (x - y) = f x - f y) : comm_ring β := { .. hf.ring_sub f zero one add mul neg sub, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := by { rw sub_eq_add_neg, exact dvd_add h₁ (dvd_neg_of_dvd h₂) } theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] lemma mul_self_sub_one (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self, mul_one] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by simpa [sub_eq_add_neg] using h))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] @[priority 100] -- see Note [lower instance priority] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ @[priority 100] -- see Note [lower instance priority] instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ /-- An integral domain is a commutative ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, an integral domain is a domain with commutative multiplication. -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} @[priority 100] -- see Note [lower instance priority] instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } end integral_domain namespace ring variables [ring R] open_locale classical /-- Introduce a function `inverse` on a ring `R`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : R → R := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units R) : R) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ @[simp] lemma inverse_unit (a : units R) : inverse (a : R) = (a⁻¹ : units R) := begin simp [is_unit_unit, inverse], exact units.inv_unique (classical.some_spec (is_unit_unit a)), end /-- By definition, if `x` is not invertible then `inverse x = 0`. -/ @[simp] lemma inverse_non_unit (x : R) (h : ¬(is_unit x)) : inverse x = 0 := dif_neg h end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
f43a29141cb53380bad908c15ca7eacdae77339f
137c667471a40116a7afd7261f030b30180468c2
/src/measure_theory/integrable_on.lean
5e13c4c3a297f764c6d3cf944a2e5ecee0d0d327
[ "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
18,432
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_measurable f (μ.restrict s) @[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ := ⟨∅, mem_bot_sets, by simp⟩ protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) := (eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) : measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) : measurable_at_filter f l μ := ⟨univ, univ_mem_sets, by rwa measure.restrict_univ⟩ lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s)) (hl : s ∈ l): measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measurable.measurable_at_filter (h : measurable f) : measurable_at_filter f l μ := h.ae_measurable.measurable_at_filter end namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α]: integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)], assume a ha, simp only [mem_singleton_iff.1 ha] }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_union s.finite_to_set lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.indicator hs lemma integrable_indicator_const_Lp {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C, from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift' with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) }, { rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) } end end normed_group end measure_theory open measure_theory asymptotics metric variables [measurable_space E] [normed_group E] /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E] {f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [indicator_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_zero ht.measurable_set).diff hs) end lemma continuous_on.integrable_at_nhds_within [topological_space α] [opens_measurable_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩ (μ.finite_at_nhds_within _ _) /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [borel_space E] [t2_space α] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx lemma continuous_on.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f (Icc a b)) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous_on.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f (interval a b)) : integrable_on f (interval a b) μ := hf.integrable_on_compact is_compact_interval /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs lemma continuous.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (interval a b) μ := hf.integrable_on_compact is_compact_interval /-- A continuous function with compact closure of the support is integrable on the whole space. -/ lemma continuous.integrable_of_compact_closure_support [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure $ support f)) : integrable f μ := begin rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)), integrable_indicator_iff is_closed_closure.measurable_set], { exact hf.integrable_on_compact hfc }, { apply_instance } end lemma measure_theory.integrable_on.mul_continuous_on [topological_space α] [opens_measurable_space α] [t2_space α] {μ : measure α} {s : set α} {f g : α → ℝ} (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, f x * g x) s μ := begin rcases is_compact.exists_bound_of_continuous_on hs hg with ⟨C, hC⟩, rw [integrable_on, ← mem_ℒp_one_iff_integrable] at hf ⊢, have : ∀ᵐ x ∂(μ.restrict s), ∥f x * g x∥ ≤ C * ∥f x∥, { filter_upwards [ae_restrict_mem hs.measurable_set], assume x hx, rw [real.norm_eq_abs, abs_mul, mul_comm, real.norm_eq_abs], apply mul_le_mul_of_nonneg_right (hC x hx) (abs_nonneg _) }, exact mem_ℒp.of_le_mul hf (hf.ae_measurable.mul (hg.ae_measurable hs.measurable_set)) this end lemma measure_theory.integrable_on.continuous_on_mul [topological_space α] [opens_measurable_space α] [t2_space α] {μ : measure α} {s : set α} {f g : α → ℝ} (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, g x * f x) s μ := by simpa [mul_comm] using hf.mul_continuous_on hg hs
db8f6b77a097fcaa28ae417a170bd0564464a50a
93b17e1ec33b7fd9fb0d8f958cdc9f2214b131a2
/src/top/sheaf.lean
d606b9b79a3f0ce6e47324c4fdb6ec5d86428548
[]
no_license
intoverflow/timesink
93f8535cd504bc128ba1b57ce1eda4efc74e5136
c25be4a2edb866ad0a9a87ee79e209afad6ab303
refs/heads/master
1,620,033,920,087
1,524,995,105,000
1,524,995,105,000
120,576,102
1
0
null
null
null
null
UTF-8
Lean
false
false
8,241
lean
/- Sheaves - -/ import .basic import ..cat.basic namespace Top universes ℓ ℓ₁ ℓ₂ ℓ₃ ℓ₄ open Cat structure PreSheaf {A : Type.{ℓ₁}} (TA : Topology A) (C : Cat.{ℓ₂ ℓ₃}) := (Section : TA.OI → C.obj) (ρ : ∀ (U₁ U₂ : TA.OI) (Res : TA.Open U₂ ⊆ TA.Open U₁) , C.hom (Section U₁) (Section U₂)) (ρ_id : ∀ (U : TA.OI) (Res : TA.Open U ⊆ TA.Open U) , (ρ U U Res) = C.id _) (ρ_circ : ∀ (U₁ U₂ U₃ : TA.OI) (Res₁₂ : TA.Open U₂ ⊆ TA.Open U₁) (Res₂₃ : TA.Open U₃ ⊆ TA.Open U₂) (Res₁₃ : TA.Open U₃ ⊆ TA.Open U₁) , C.circ (ρ U₂ U₃ Res₂₃) (ρ U₁ U₂ Res₁₂) = ρ U₁ U₃ Res₁₃) def PreSheaf.Eql.Codom {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) := CProd { u₁u₂ : TA.OI × TA.OI // u₁u₂.1 ∈ UU ∧ u₁u₂.2 ∈ UU } (λ u₁u₂, Psh.Section (TA.inter u₁u₂.val.1 u₁u₂.val.2)) def PreSheaf.Eql.Dom {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) := CProd { u : TA.OI // u ∈ UU } (λ u, Psh.Section u) def PreSheaf.Eql.left {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) : C.hom (PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.obj (PreSheaf.Eql.Codom CProd Psh U UU Ucover).1.obj := (PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.univ { obj := (PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.obj , proj := λ u₁u₂, C.circ (Psh.ρ _ _ (Topology.Inter.Subset_l _ _)) ((PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.proj { val := u₁u₂.val.1 , property := u₁u₂.property.1 }) } def PreSheaf.Eql.right {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) : C.hom (PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.obj (PreSheaf.Eql.Codom CProd Psh U UU Ucover).1.obj := (PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.univ { obj := (PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.obj , proj := λ u₁u₂, C.circ (Psh.ρ _ _ (Topology.Inter.Subset_r _ _)) ((PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.proj { val := u₁u₂.val.2 , property := u₁u₂.property.2 }) } def PreSheaf.Eql.direct {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) : C.hom (Psh.Section U) (PreSheaf.Eql.Codom CProd Psh U UU Ucover).1.obj := (PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.univ { obj := Psh.Section U , proj := λ u₁u₂ , Psh.ρ _ _ begin intros p H, apply Topology.Cover.Subset Ucover u₁u₂.property.1, apply Topology.Inter.Subset_l _ _ H, end } def PreSheaf.Eql.eq {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) : C.hom (Psh.Section U) (PreSheaf.Eql.Dom CProd Psh U UU Ucover).1.obj := (PreSheaf.Eql.Dom CProd Psh U UU Ucover).2.univ { obj := Psh.Section U , proj := λ u, Psh.ρ _ _ (Topology.Cover.Subset Ucover u.property) } def PreSheaf.Eql {C : Cat.{ℓ₂ ℓ₃}} {A : Type.{ℓ₁}} {TA : Topology A} (CProd : C.HasProducts) (Psh : PreSheaf TA C) (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) : C.Eql (PreSheaf.Eql.left CProd Psh U UU Ucover) (PreSheaf.Eql.right CProd Psh U UU Ucover) := { obj := Psh.Section U , eq := PreSheaf.Eql.eq CProd Psh U UU Ucover , Eeq := begin refine @eq.trans _ _ (PreSheaf.Eql.direct CProd Psh U UU Ucover) _ _ _, { apply (PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.uniq { obj := _, proj := _ }, intro u₁u₂, rw C.circ_assoc, apply eq.symm, have Q := ((PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.eq _ u₁u₂).symm, refine eq.trans (Cat.circ_congr Q rfl) _, clear Q, rw (Cat.circ_assoc _).symm, have Q := ((PreSheaf.Eql.Dom CProd Psh U UU Ucover).2.eq _ { val := u₁u₂.val.1, property := u₁u₂.property.1 }).symm, refine eq.trans (Cat.circ_congr rfl Q) _, clear Q, simp, apply Psh.ρ_circ }, { apply eq.symm, apply (PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.uniq { obj := _, proj := _ }, intro u₁u₂, rw C.circ_assoc, apply eq.symm, have Q := ((PreSheaf.Eql.Codom CProd Psh U UU Ucover).2.eq _ u₁u₂).symm, refine eq.trans (Cat.circ_congr Q rfl) _, clear Q, rw (Cat.circ_assoc _).symm, have Q := ((PreSheaf.Eql.Dom CProd Psh U UU Ucover).2.eq _ { val := u₁u₂.val.2, property := u₁u₂.property.2 }).symm, refine eq.trans (Cat.circ_congr rfl Q) _, clear Q, simp, apply Psh.ρ_circ } end } structure Sheaf {A : Type.{ℓ₁}} (TA : Topology A) (C : Cat.{ℓ₂ ℓ₃}) (CProd : C.HasProducts) := (sh : PreSheaf TA C) (glue : ∀ (U : TA.OI) (UU : set TA.OI) (Ucover : TA.Open U = set.sUnion (TA.Open <$> UU)) , C.Equalizer (PreSheaf.Eql CProd sh U UU Ucover)) def PreSheaf.DirectIm {A : Type.{ℓ₁}} {B : Type.{ℓ₂}} {TA : Topology A} {TB : Topology B} {C : Cat.{ℓ₃ ℓ₄}} (S : PreSheaf.{ℓ₁ ℓ₃} TA C) (f : Map TA TB) : PreSheaf.{ℓ₂ ℓ₃} TB C := { Section := λ U, S.Section (f.preimage U).val , ρ := λ U₁ U₂ H, S.ρ _ _ (f.subset H) , ρ_id := λ U H, S.ρ_id _ (f.subset H) , ρ_circ := λ U₁ U₂ U₃ H₁₂ H₂₃ H₁₃ , S.ρ_circ _ _ _ (f.subset H₁₂) (f.subset H₂₃) (f.subset H₁₃) } def Sheaf.DirectIm {A : Type.{ℓ₁}} {B : Type.{ℓ₂}} {TA : Topology A} {TB : Topology B} {C : Cat.{ℓ₃ ℓ₄}} {CProd₁ : C.HasProducts} {CProd₂ : C.HasProducts} (S : Sheaf.{ℓ₁ ℓ₃} TA C CProd₁) (f : Map TA TB) : Sheaf.{ℓ₂ ℓ₃} TB C CProd₂ := { sh := PreSheaf.DirectIm S.sh f , glue := λ U UU Ucover, sorry } structure PreSheafHom {A : Type.{ℓ₁}} {TA : Topology A} {C : Cat.{ℓ₂ ℓ₃}} (Sh₁ Sh₂ : PreSheaf TA C) := (hom : ∀ (U : TA.OI), C.hom (Sh₁.Section U) (Sh₂.Section U)) (natural : ∀ (U₁ U₂ : TA.OI) (H : TA.Open U₂ ⊆ TA.Open U₁) , C.circ (Sh₂.ρ U₁ U₂ H) (hom U₁) = C.circ (hom U₂) (Sh₁.ρ U₁ U₂ H)) def SheafHom {A : Type.{ℓ₁}} {TA : Topology A} {C : Cat.{ℓ₂ ℓ₃}} {CProd : C.HasProducts} (Sh₁ Sh₂ : Sheaf TA C CProd) := PreSheafHom Sh₁.sh Sh₂.sh structure {i c₁ c₂} ShSpace (C : Cat.{c₁ c₂}) := (Pt : Type.{i}) (Top : Topology Pt) (Prod : C.HasProducts) (Sh : Sheaf Top C Prod) structure {i j c₁ c₂} ShHom {C : Cat.{c₁ c₂}} (GA : ShSpace.{i c₁ c₂} C) (GB : ShSpace.{j c₁ c₂} C) := (map : Map GA.Top GB.Top) (sh : SheafHom GB.Sh (GA.Sh.DirectIm map)) end Top
8c252403539a43eb38bfc4fb4e404306bb84d8a6
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/data/nat/factorial.lean
2296220fa82c5cf9d16e6f4f1454a5d61e7058b6
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,813
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, Yaël Dillies -/ import data.nat.basic import data.nat.pow /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## Main declarations * `factorial`: The factorial. * `asc_factorial`: The ascending factorial. Note that it runs from `n + 1` to `n + k` and *not* from`n` to `n + k - 1`. We might want to change that in the future. * `desc_factorial`: The descending factorial. It runs from `n - k` to `n`. -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : ℕ → ℕ | 0 := 1 | (succ n) := succ n * factorial n localized "notation n `!`:10000 := nat.factorial n" in nat section factorial variables {m n : ℕ} @[simp] theorem factorial_zero : 0! = 1 := rfl @[simp] theorem factorial_succ (n : ℕ) : n.succ! = succ n * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl theorem mul_factorial_pred (hn : 0 < n) : n * (n - 1)! = n! := nat.sub_add_cancel hn ▸ rfl theorem factorial_pos : ∀ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n! ≠ 0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m! ∣ n! := begin induction n with n IH; simp, { have := nat.eq_zero_of_le_zero h, subst m, simp }, obtain he | hl := h.eq_or_lt, { subst m, simp }, exact (IH (le_of_lt_succ hl)).mul_left _, end theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) @[mono] theorem factorial_le {m n} (h : m ≤ n) : m! ≤ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m! * m.succ ^ n ≤ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := λ n m, factorial_le lemma factorial_lt (hn : 0 < n) : n! < m! ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (factorial_le hmn) }, have : ∀ n, 0 < n → n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (factorial_pos k) }, induction h with k hnk generalizing hn, { exact this _ hn, }, refine lt_trans (h_ih hn) (this _ _), exact lt_trans hn (lt_of_succ_le hnk), end lemma one_lt_factorial : 1 < n! ↔ 1 < n := by { convert factorial_lt _, refl, exact one_pos } lemma factorial_eq_one : n! = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl }, cases h with h h, refl, cases h, refl, end lemma factorial_inj (hn : 1 < n!) : n! = m! ↔ n = m := begin split; intro h, { obtain hnm | hnm | hnm := lt_trichotomy n m, { exfalso, rw [← factorial_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_factorial] at hn, exact lt_trans one_pos hn }, { exact hnm }, exfalso, rw [h, one_lt_factorial] at hn, rw [←factorial_lt (lt_trans one_pos hn), h] at hnm, exact lt_irrefl _ hnm, }, { rw h }, end lemma self_le_factorial : ∀ n : ℕ, n ≤ n! | 0 := zero_le_one | (k + 1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) lemma lt_factorial_self {n : ℕ} (hi : 3 ≤ n) : n < n! := begin rw [← succ_pred_eq_of_pos ((zero_lt_two.trans (lt.base 2)).trans_le hi), factorial_succ], exact lt_mul_of_one_lt_right ((pred n).succ_pos) ((one_lt_two.trans_le (le_pred_of_lt (succ_le_iff.mp hi))).trans_le (self_le_factorial _)), end lemma add_factorial_succ_lt_factorial_add_succ {i : ℕ} (n : ℕ) (hi : 2 ≤ i) : i + (n + 1)! < (i + n + 1)! := begin rw [factorial_succ (i + _), succ_eq_add_one, add_mul, one_mul], have : i ≤ i + n := le.intro rfl, exact add_lt_add_of_lt_of_le (this.trans_lt ((lt_mul_iff_one_lt_right (zero_lt_two.trans_le (hi.trans this))).mpr (lt_iff_le_and_ne.mpr ⟨(i + n).factorial_pos, λ g, nat.not_succ_le_self 1 ((hi.trans this).trans (factorial_eq_one.mp g.symm))⟩))) (factorial_le ((le_of_eq (add_comm n 1)).trans ((add_le_add_iff_right n).mpr (one_le_two.trans hi)))), end lemma add_factorial_lt_factorial_add {i n : ℕ} (hi : 2 ≤ i) (hn : 1 ≤ n) : i + n! < (i + n)! := begin cases hn, { rw factorial_one, exact lt_factorial_self (succ_le_succ hi) }, exact add_factorial_succ_lt_factorial_add_succ _ hi, end lemma add_factorial_succ_le_factorial_add_succ (i : ℕ) (n : ℕ) : i + (n + 1)! ≤ (i + (n + 1))! := begin obtain i2 | (_ | ⟨_, i0⟩) := le_or_lt 2 i, { exact (n.add_factorial_succ_lt_factorial_add_succ i2).le }, { change 1 + (n + 1)! ≤ (1 + n + 1) * (1 + n)!, rw [add_mul, one_mul, add_comm 1 n], exact (add_le_add_iff_right _).mpr (one_le_mul (nat.le_add_left 1 n) (n + 1).factorial_pos) }, rw [nat.le_zero_iff.mp (nat.succ_le_succ_iff.mp i0), zero_add, zero_add] end lemma add_factorial_le_factorial_add (i : ℕ) {n : ℕ} (n1 : 1 ≤ n) : i + n! ≤ (i + n)! := begin cases n1 with h, { exact self_le_factorial _ }, exact add_factorial_succ_le_factorial_add_succ i h, end lemma factorial_mul_pow_sub_le_factorial {n m : ℕ} (hnm : n ≤ m) : n! * n ^ (m - n) ≤ m! := begin suffices : n! * (n + 1) ^ (m - n) ≤ m!, { apply trans _ this, rw mul_le_mul_left, apply pow_le_pow_of_le_left (zero_le n) (le_succ n), exact factorial_pos n,}, convert nat.factorial_mul_pow_le_factorial, exact (nat.add_sub_of_le hnm).symm, end end factorial /-! ### Ascending and descending factorials -/ section asc_factorial /-- `n.asc_factorial k = (n + k)! / n!` (as seen in `nat.asc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def asc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n + k + 1) * asc_factorial k @[simp] lemma asc_factorial_zero (n : ℕ) : n.asc_factorial 0 = 1 := rfl @[simp] lemma zero_asc_factorial (k : ℕ) : (0 : ℕ).asc_factorial k = k! := begin induction k with t ht, refl, unfold asc_factorial, rw [ht, zero_add, nat.factorial_succ], end lemma asc_factorial_succ {n k : ℕ} : n.asc_factorial k.succ = (n + k + 1) * n.asc_factorial k := rfl lemma succ_asc_factorial (n : ℕ) : ∀ k, (n + 1) * n.succ.asc_factorial k = (n + k + 1) * n.asc_factorial k | 0 := by rw [add_zero, asc_factorial_zero, asc_factorial_zero] | (k + 1) := by rw [asc_factorial, mul_left_comm, succ_asc_factorial, asc_factorial, succ_add, ←add_assoc] /-- `n.asc_factorial k = (n + k)! / n!` but without ℕ-division. See `nat.asc_factorial_eq_div` for the version with ℕ-division. -/ theorem factorial_mul_asc_factorial (n : ℕ) : ∀ k, n! * n.asc_factorial k = (n + k)! | 0 := by rw [asc_factorial, add_zero, mul_one] | (k + 1) := by rw [asc_factorial_succ, mul_left_comm, factorial_mul_asc_factorial, ← add_assoc, factorial] /-- Avoid in favor of `nat.factorial_mul_asc_factorial` if you can. ℕ-division isn't worth it. -/ lemma asc_factorial_eq_div (n k : ℕ) : n.asc_factorial k = (n + k)! / n! := begin apply mul_left_cancel' (factorial_ne_zero n), rw factorial_mul_asc_factorial, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ le.intro rfl).symm end lemma asc_factorial_of_sub {n k : ℕ} (h : k < n) : (n - k) * (n - k).asc_factorial k = (n - (k + 1)).asc_factorial (k + 1) := begin set t := n - k.succ with ht, suffices h' : n - k = t.succ, by rw [←ht, h', succ_asc_factorial, asc_factorial_succ], rw [ht, succ_eq_add_one, ←sub_sub_assoc h (succ_pos _), succ_sub_one], end lemma pow_succ_le_asc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1)^k ≤ n.asc_factorial k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw pow_succ, exact nat.mul_le_mul (nat.add_le_add_right le_self_add _) (pow_succ_le_asc_factorial k), end lemma pow_lt_asc_factorial' (n k : ℕ) : (n + 1)^(k + 2) < n.asc_factorial (k + 2) := begin rw pow_succ, exact nat.mul_lt_mul (nat.add_lt_add_right (nat.lt_add_of_pos_right succ_pos') 1) (pow_succ_le_asc_factorial n _) (pow_pos succ_pos' _), end lemma pow_lt_asc_factorial (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1)^k < n.asc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, pow_lt_asc_factorial' n k lemma asc_factorial_le_pow_add (n : ℕ) : ∀ (k : ℕ), n.asc_factorial k ≤ (n + k)^k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw [asc_factorial_succ, pow_succ], exact nat.mul_le_mul_of_nonneg_left ((asc_factorial_le_pow_add k).trans (nat.pow_le_pow_of_le_left (le_succ _) _)), end lemma asc_factorial_lt_pow_add (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → n.asc_factorial k < (n + k)^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [asc_factorial_succ, pow_succ], refine nat.mul_lt_mul' (le_refl _) ((asc_factorial_le_pow_add n _).trans_lt (pow_lt_pow_of_lt_left (lt_add_one _) (succ_pos _))) (succ_pos _), end lemma asc_factorial_pos (n k : ℕ) : 0 < n.asc_factorial k := (pow_pos (succ_pos n) k).trans_le (pow_succ_le_asc_factorial n k) end asc_factorial section desc_factorial /-- `n.desc_factorial k = n! / (n - k)!` (as seen in `nat.desc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def desc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n - k) * desc_factorial k @[simp] lemma desc_factorial_zero (n : ℕ) : n.desc_factorial 0 = 1 := rfl @[simp] lemma desc_factorial_succ (n k : ℕ) : n.desc_factorial k.succ = (n - k) * n.desc_factorial k := rfl lemma zero_desc_factorial_succ (k : ℕ) : (0 : ℕ).desc_factorial k.succ = 0 := by rw [desc_factorial_succ, nat.zero_sub, zero_mul] @[simp] lemma desc_factorial_one (n : ℕ) : n.desc_factorial 1 = n := by rw [desc_factorial_succ, desc_factorial_zero, mul_one, nat.sub_zero] @[simp] lemma succ_desc_factorial_succ (n : ℕ) : ∀ k : ℕ, (n + 1).desc_factorial (k + 1) = (n + 1) * n.desc_factorial k | 0 := by rw [desc_factorial_zero, desc_factorial_one, mul_one] | (succ k) := by rw [desc_factorial_succ, succ_desc_factorial_succ, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma succ_desc_factorial (n : ℕ) : ∀ k, (n + 1 - k) * (n + 1).desc_factorial k = (n + 1) * n.desc_factorial k | 0 := by rw [nat.sub_zero, desc_factorial_zero, desc_factorial_zero] | (k + 1) := by rw [desc_factorial, succ_desc_factorial, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma desc_factorial_self : ∀ n : ℕ, n.desc_factorial n = n! | 0 := by rw [desc_factorial_zero, factorial_zero] | (succ n) := by rw [succ_desc_factorial_succ, desc_factorial_self, factorial_succ] @[simp] lemma desc_factorial_eq_zero_iff_lt {n : ℕ} : ∀ {k : ℕ}, n.desc_factorial k = 0 ↔ n < k | 0 := by simp only [desc_factorial_zero, nat.one_ne_zero, nat.not_lt_zero] | (succ k) := begin rw [desc_factorial_succ, mul_eq_zero, desc_factorial_eq_zero_iff_lt, lt_succ_iff, nat.sub_eq_zero_iff_le, lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp], exact λ h _, h, end lemma add_desc_factorial_eq_asc_factorial (n : ℕ) : ∀ k : ℕ, (n + k).desc_factorial k = n.asc_factorial k | 0 := by rw [asc_factorial_zero, desc_factorial_zero] | (succ k) := by rw [nat.add_succ, succ_desc_factorial_succ, asc_factorial_succ, add_desc_factorial_eq_asc_factorial] /-- `n.desc_factorial k = n! / (n - k)!` but without ℕ-division. See `nat.desc_factorial_eq_div` for the version using ℕ-division. -/ theorem factorial_mul_desc_factorial : ∀ {n k : ℕ}, k ≤ n → (n - k)! * n.desc_factorial k = n! | n 0 := λ _, by rw [desc_factorial_zero, mul_one, nat.sub_zero] | 0 (succ k) := λ h, by { exfalso, exact not_succ_le_zero k h } | (succ n) (succ k) := λ h, by rw [succ_desc_factorial_succ, succ_sub_succ, ←mul_assoc, mul_comm (n - k)!, mul_assoc, factorial_mul_desc_factorial (nat.succ_le_succ_iff.1 h), factorial_succ] /-- Avoid in favor of `nat.factorial_mul_desc_factorial` if you can. ℕ-division isn't worth it. -/ lemma desc_factorial_eq_div {n k : ℕ} (h : k ≤ n) : n.desc_factorial k = n! / (n - k)! := begin apply mul_left_cancel' (factorial_ne_zero (n - k)), rw factorial_mul_desc_factorial h, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ nat.sub_le n k).symm, end lemma pow_sub_le_desc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1 - k)^k ≤ n.desc_factorial k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ, succ_sub_succ], exact nat.mul_le_mul_of_nonneg_left (le_trans (nat.pow_le_pow_of_le_left (nat.sub_le_sub_right (le_succ _) _) k) (pow_sub_le_desc_factorial k)), end lemma pow_sub_lt_desc_factorial' {n : ℕ} : ∀ {k : ℕ}, k + 2 ≤ n → (n - (k + 1))^(k + 2) < n.desc_factorial (k + 2) | 0 := λ h, begin rw [desc_factorial_succ, pow_succ, pow_one, desc_factorial_one], exact nat.mul_lt_mul_of_pos_left (nat.sub_lt_self (lt_of_lt_of_le zero_lt_two h) zero_lt_one) (nat.sub_pos_of_lt h), end | (k + 1) := λ h, begin rw [desc_factorial_succ, pow_succ], refine nat.mul_lt_mul_of_pos_left ((nat.pow_le_pow_of_le_left (nat.sub_le_sub_right (le_succ n) _) _).trans_lt _) (nat.sub_pos_of_lt h), rw succ_sub_succ, exact (pow_sub_lt_desc_factorial' ((le_succ _).trans h)), end lemma pow_sub_lt_desc_factorial {n : ℕ} : ∀ {k : ℕ}, 2 ≤ k → k ≤ n → (n + 1 - k)^k < n.desc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _ h, by { rw succ_sub_succ, exact pow_sub_lt_desc_factorial' h } lemma desc_factorial_le_pow (n : ℕ) : ∀ (k : ℕ), n.desc_factorial k ≤ n^k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ], exact nat.mul_le_mul (nat.sub_le _ _) (desc_factorial_le_pow k), end lemma desc_factorial_lt_pow {n : ℕ} (hn : 1 ≤ n) : ∀ {k : ℕ}, 2 ≤ k → n.desc_factorial k < n^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [desc_factorial_succ, pow_succ', mul_comm], exact nat.mul_lt_mul' (desc_factorial_le_pow _ _) (nat.sub_lt_self hn k.zero_lt_succ) (pow_pos hn _), end end desc_factorial end nat
ab56c2b9ddc7784f27d24965bc1d716a3020f644
4fa161becb8ce7378a709f5992a594764699e268
/src/topology/dense_embedding.lean
599d1639b1a9f4f978cd3370aa0884e2e3693a98
[ "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,507
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation /-! # Dense embeddings This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`; * `dense_embedding e` means `e` is also an `embedding`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a regular (T₃) space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter open_locale classical topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section dense_range variables [topological_space β] [topological_space γ] (f : α → β) (g : β → γ) /-- `f : α → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := ∀ x, x ∈ closure (range f) variables {f} lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := eq_univ_iff_forall.symm lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := eq_univ_iff_forall.mpr h lemma dense_range.comp (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := begin have : g '' (closure $ range f) ⊆ closure (g '' range f), from image_closure_subset_closure_image cg, have : closure (g '' closure (range f)) ⊆ closure (g '' range f), by simpa [closure_closure] using (closure_mono this), intro c, rw range_comp, apply this, rw [hf.closure_range, image_univ], exact hg c end /-- If `f : α → β` has dense range and `β` contains some element, then `α` must too. -/ def dense_range.inhabited (df : dense_range f) (b : β) : inhabited α := ⟨classical.choice $ by simpa only [univ_inter, range_nonempty_iff_nonempty] using mem_closure_iff.1 (df b) _ is_open_univ trivial⟩ lemma dense_range.nonempty (hf : dense_range f) : nonempty α ↔ nonempty β := ⟨nonempty.map f, λ ⟨b⟩, @nonempty_of_inhabited _ (hf.inhabited b)⟩ lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) := have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ end dense_range /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) : is_open s → s ⊆ closure (i '' (i ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, exact (dense_iff_inter_open.1 di.closure_range) _ (is_open_inter U_op s_op) ⟨b, b_in, b_in_s⟩ end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) : s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op ... ⊆ closure (i '' s) : closure_mono (image_subset i this), have U_nhd : U ∈ 𝓝 (i a) := mem_nhds_sets U_op e_a_in_U, exact (𝓝 (i a)).sets_of_superset U_nhd this end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod de₂.dense } variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_inf_ne_bot (di : dense_inducing i) {b : β} : 𝓝 b ⊓ principal (range i) ≠ ⊥ := begin convert di.dense b, simp [closure_eq_nhds] end lemma comap_nhds_ne_bot (di : dense_inducing i) {b : β} : comap i (𝓝 b) ≠ ⊥ := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @@lim _ ⟨f (di.dense.inhabited b).default⟩ (comap i (𝓝 b)) f lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : tendsto f (comap i (𝓝 b)) (𝓝 c)) : di.extend f b = c := hf.lim_eq di.comap_nhds_ne_bot lemma extend_e_eq [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq_of_cont [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_e_eq a (continuous_iff_continuous_at.1 hf a) lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : {b | ∃c, tendsto f (comap i $ 𝓝 b) (𝓝 c)} ∈ 𝓝 b) : tendsto (di.extend f) (𝓝 b) (𝓝 (di.extend f b)) := let φ := {b | tendsto f (comap i $ 𝓝 b) (𝓝 $ di.extend f b)} in have hφ : φ ∈ 𝓝 b, from (𝓝 b).sets_of_superset hf $ assume b ⟨c, hc⟩, show tendsto f (comap i (𝓝 b)) (𝓝 (di.extend f b)), from (di.extend_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : i ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (i ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)), from assume b' hb', have 𝓝 b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (comap i (𝓝 b')) ≤ 𝓝 (di.extend f b') ⊓ principal (f '' (i ⁻¹' t)), from calc _ ≤ map f (comap i (𝓝 b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this ... ≤ map f (comap i (𝓝 b')) ⊓ map f (comap i (principal t)) : le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right) ... ≤ map f (comap i (𝓝 b')) ⊓ principal (f '' (i ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf_right _ (ht₁ hb').left, show di.extend f b' ∈ closure (f '' (i ⁻¹' t)), begin rw [closure_eq_nhds], apply ne_bot_of_le_ne_bot _ this, simp, exact di.comap_nhds_ne_bot end, (𝓝 b).sets_of_superset (show t ∈ 𝓝 b, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)) : h₂ ... ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ di.extend f ⁻¹' s'' : preimage_mono h₁ ... ⊆ di.extend f ⁻¹' s : preimage_mono hs''₂) lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.tendsto_extend $ univ_mem_sets' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- The product of two dense embeddings is a dense embedding -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) } end dense_embedding lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end
030a67c5b6d57020b5b697f6f49b5fe9d2ab3157
53618200bef52920c1e974173f78cd378d268f3e
/hott/homotopy/wedge.hlean
6f4891f9e176c3feb5ea16ac6d8d66021223f048
[ "Apache-2.0" ]
permissive
sayantangkhan/lean2
cc41e61102e0fcc8b65e8501186dcca40b19b22e
0fc0378969678eec25ea425a426bb48a184a6db0
refs/heads/master
1,590,323,112,724
1,489,425,932,000
1,489,425,932,000
84,854,525
0
0
null
1,489,425,509,000
1,489,425,509,000
null
UTF-8
Lean
false
false
3,642
hlean
/- Copyright (c) 2016 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer, Ulrik Buchholtz The Wedge Sum of Two Pointed Types -/ import hit.pushout .connectedness types.unit open eq pushout pointed unit trunc_index definition wedge (A B : Type*) : Type := ppushout (pconst punit A) (pconst punit B) local attribute wedge [reducible] definition pwedge (A B : Type*) : Type* := pointed.mk' (wedge A B) infixr ` ∨ ` := pwedge namespace wedge protected definition rec {A B : Type*} {P : wedge A B → Type} (Pinl : Π(x : A), P (inl x)) (Pinr : Π(x : B), P (inr x)) (Pglue : pathover P (Pinl pt) (glue ⋆) (Pinr pt)) (y : wedge A B) : P y := by induction y; apply Pinl; apply Pinr; induction x; exact Pglue protected definition elim {A B : Type*} {P : Type} (Pinl : A → P) (Pinr : B → P) (Pglue : Pinl pt = Pinr pt) (y : wedge A B) : P := by induction y with a b x; exact Pinl a; exact Pinr b; induction x; exact Pglue end wedge attribute wedge.rec wedge.elim [recursor 7] [unfold 7] namespace wedge -- TODO maybe find a cleaner proof protected definition unit (A : Type*) : A ≃* pwedge punit A := begin fapply pequiv_of_pmap, { fapply pmap.mk, intro a, apply pinr a, apply respect_pt }, { fapply is_equiv.adjointify, intro x, fapply pushout.elim_on x, exact λ x, Point A, exact id, intro u, reflexivity, intro x, fapply pushout.rec_on x, intro u, cases u, esimp, apply (glue unit.star)⁻¹, intro a, reflexivity, intro u, cases u, esimp, apply eq_pathover, refine _ ⬝hp !ap_id⁻¹, fapply eq_hconcat, apply ap_compose inr, krewrite elim_glue, fapply eq_hconcat, apply ap_idp, apply square_of_eq, apply con.left_inv, intro a, reflexivity}, end end wedge open trunc is_trunc is_conn function namespace wedge_extension section -- The wedge connectivity lemma (Lemma 8.6.2) parameters {A B : Type*} (n m : ℕ) [cA : is_conn n A] [cB : is_conn m B] (P : A → B → Type) [HP : Πa b, is_trunc (m + n) (P a b)] (f : Πa : A, P a pt) (g : Πb : B, P pt b) (p : f pt = g pt) include cA cB HP private definition Q (a : A) : Type := fiber (λs : (Πb : B, P a b), s (Point B)) (f a) private definition is_trunc_Q (a : A) : is_trunc (n.-1) (Q a) := begin refine @is_conn.elim_general (m.-1) _ _ _ (P a) _ (f a), rewrite [-succ_add_succ, of_nat_add_of_nat], intro b, apply HP end local attribute is_trunc_Q [instance] private definition Q_sec : Πa : A, Q a := is_conn.elim (n.-1) Q (fiber.mk g p⁻¹) protected definition ext : Π(a : A)(b : B), P a b := λa, fiber.point (Q_sec a) protected definition β_left (a : A) : ext a (Point B) = f a := fiber.point_eq (Q_sec a) private definition coh_aux : Σq : ext (Point A) = g, β_left (Point A) = ap (λs : (Πb : B, P (Point A) b), s (Point B)) q ⬝ p⁻¹ := equiv.to_fun (fiber.fiber_eq_equiv (Q_sec (Point A)) (fiber.mk g p⁻¹)) (is_conn.elim_β (n.-1) Q (fiber.mk g p⁻¹)) protected definition β_right (b : B) : ext (Point A) b = g b := apd10 (sigma.pr1 coh_aux) b private definition lem : β_left (Point A) = β_right (Point B) ⬝ p⁻¹ := begin unfold β_right, unfold β_left, krewrite (apd10_eq_ap_eval (sigma.pr1 coh_aux) (Point B)), exact sigma.pr2 coh_aux, end protected definition coh : (β_left (Point A))⁻¹ ⬝ β_right (Point B) = p := by rewrite [lem,con_inv,inv_inv,con.assoc,con.left_inv] end end wedge_extension
62d40e211f33c7d2ce8b7658e18a3e2f1c0dc697
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/hott/algebra/category/constructions/set.hlean
0e5a2fadca0a3bf2c036b41746c43e027398aa42
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,588
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, Jakob von Raumer Category of sets -/ import ..functor.basic ..category types.equiv types.lift open eq category equiv iso is_equiv is_trunc function sigma namespace category definition precategory_Set.{u} [reducible] [constructor] : precategory Set.{u} := precategory.mk (λx y : Set, x → y) (λx y z g f a, g (f a)) (λx a, a) (λx y z w h g f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) definition Precategory_Set [reducible] [constructor] : Precategory := Precategory.mk Set precategory_Set abbreviation set [constructor] := Precategory_Set namespace set local attribute is_equiv_subtype_eq [instance] definition iso_of_equiv [constructor] {A B : set} (f : A ≃ B) : A ≅ B := iso.MK (to_fun f) (to_inv f) (eq_of_homotopy (left_inv (to_fun f))) (eq_of_homotopy (right_inv (to_fun f))) definition equiv_of_iso [constructor] {A B : set} (f : A ≅ B) : A ≃ B := begin apply equiv.MK (to_hom f) (iso.to_inv f), exact ap10 (to_right_inverse f), exact ap10 (to_left_inverse f) end definition is_equiv_iso_of_equiv [constructor] (A B : set) : is_equiv (@iso_of_equiv A B) := adjointify _ (λf, equiv_of_iso f) (λf, proof iso_eq idp qed) (λf, equiv_eq idp) local attribute is_equiv_iso_of_equiv [instance] definition iso_of_eq_eq_compose (A B : Set) : @iso_of_eq _ _ A B = @iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B := eq_of_homotopy (λp, eq.rec_on p idp) definition equiv_equiv_iso (A B : set) : (A ≃ B) ≃ (A ≅ B) := equiv.MK (λf, iso_of_equiv f) (λf, proof equiv.MK (to_hom f) (iso.to_inv f) (ap10 (to_right_inverse f)) (ap10 (to_left_inverse f)) qed) (λf, proof iso_eq idp qed) (λf, proof equiv_eq idp qed) definition equiv_eq_iso (A B : set) : (A ≃ B) = (A ≅ B) := ua !equiv_equiv_iso definition is_univalent_Set (A B : set) : is_equiv (iso_of_eq : A = B → A ≅ B) := assert H₁ : is_equiv (@iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B), from @is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ _ (@is_equiv_subtype_eq_inv _ _ _ _ _)) !univalence) !is_equiv_iso_of_equiv, let H₂ := (iso_of_eq_eq_compose A B)⁻¹ in begin rewrite H₂ at H₁, assumption end end set definition category_Set [instance] [constructor] [reducible] : category Set := category.mk precategory_Set set.is_univalent_Set definition Category_Set [reducible] [constructor] : Category := Category.mk Set category_Set abbreviation cset [constructor] := Category_Set open functor lift definition functor_lift.{u v} [constructor] : set.{u} ⇒ set.{max u v} := functor.mk tlift (λa b, lift_functor) (λa, eq_of_homotopy (λx, by induction x; reflexivity)) (λa b c g f, eq_of_homotopy (λx, by induction x; reflexivity)) end category
5ca09a6a761a17c0375fbc4e11aa4d20e2087bed
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/algebra/classes.lean
74d3b59cd245a04eccfaa95257a15e47b67f4ffb
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
12,182
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.logic init.data.ordering.basic universes u v @[algebra] class is_symm_op (α : Type u) (β : out_param (Type v)) (op : α → α → β) : Prop := (symm_op : ∀ a b, op a b = op b a) @[algebra] class is_commutative (α : Type u) (op : α → α → α) : Prop := (comm : ∀ a b, op a b = op b a) instance is_symm_op_of_is_commutative (α : Type u) (op : α → α → α) [is_commutative α op] : is_symm_op α α op := {symm_op := is_commutative.comm op} @[algebra] class is_associative (α : Type u) (op : α → α → α) : Prop := (assoc : ∀ a b c, op (op a b) c = op a (op b c)) @[algebra] class is_left_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_id : ∀ a, op o a = a) @[algebra] class is_right_id (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_id : ∀ a, op a o = a) @[algebra] class is_left_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (left_null : ∀ a, op o a = o) @[algebra] class is_right_null (α : Type u) (op : α → α → α) (o : out_param α) : Prop := (right_null : ∀ a, op a o = o) @[algebra] class is_left_cancel (α : Type u) (op : α → α → α) : Prop := (left_cancel : ∀ a b c, op a b = op a c → b = c) @[algebra] class is_right_cancel (α : Type u) (op : α → α → α) : Prop := (right_cancel : ∀ a b c, op a b = op c b → a = c) @[algebra] class is_idempotent (α : Type u) (op : α → α → α) : Prop := (idempotent : ∀ a, op a a = a) @[algebra] class is_left_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (left_distrib : ∀ a b c, op₁ a (op₂ b c) = op₂ (op₁ a b) (op₁ a c)) @[algebra] class is_right_distrib (α : Type u) (op₁ : α → α → α) (op₂ : out_param $ α → α → α) : Prop := (right_distrib : ∀ a b c, op₁ (op₂ a b) c = op₂ (op₁ a c) (op₁ b c)) @[algebra] class is_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (left_inv : ∀ a, op (inv a) a = o) @[algebra] class is_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) : Prop := (right_inv : ∀ a, op a (inv a) = o) @[algebra] class is_cond_left_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (left_inv : ∀ a, p a → op (inv a) a = o) @[algebra] class is_cond_right_inv (α : Type u) (op : α → α → α) (inv : out_param $ α → α) (o : out_param α) (p : out_param $ α → Prop) : Prop := (right_inv : ∀ a, p a → op a (inv a) = o) @[algebra] class is_distinct (α : Type u) (a : α) (b : α) : Prop := (distinct : a ≠ b) /- -- The following type class doesn't seem very useful, a regular simp lemma should work for this. class is_inv (α : Type u) (β : Type v) (f : α → β) (g : out β → α) : Prop := (inv : ∀ a, g (f a) = a) -- The following one can also be handled using a regular simp lemma class is_idempotent (α : Type u) (f : α → α) : Prop := (idempotent : ∀ a, f (f a) = f a) -/ @[algebra] class is_irrefl (α : Type u) (r : α → α → Prop) : Prop := (irrefl : ∀ a, ¬ r a a) @[algebra] class is_refl (α : Type u) (r : α → α → Prop) : Prop := (refl : ∀ a, r a a) @[algebra] class is_symm (α : Type u) (r : α → α → Prop) : Prop := (symm : ∀ a b, r a b → r b a) instance is_symm_op_of_is_symm (α : Type u) (r : α → α → Prop) [is_symm α r] : is_symm_op α Prop r := {symm_op := λ a b, propext $ iff.intro (is_symm.symm a b) (is_symm.symm b a)} @[algebra] class is_asymm (α : Type u) (r : α → α → Prop) : Prop := (asymm : ∀ a b, r a b → ¬ r b a) @[algebra] class is_antisymm (α : Type u) (r : α → α → Prop) : Prop := (antisymm : ∀ a b, r a b → r b a → a = b) @[algebra] class is_trans (α : Type u) (r : α → α → Prop) : Prop := (trans : ∀ a b c, r a b → r b c → r a c) @[algebra] class is_total (α : Type u) (r : α → α → Prop) : Prop := (total : ∀ a b, r a b ∨ r b a) @[algebra] class is_preorder (α : Type u) (r : α → α → Prop) extends is_refl α r, is_trans α r : Prop. @[algebra] class is_total_preorder (α : Type u) (r : α → α → Prop) extends is_trans α r, is_total α r : Prop. instance is_total_preorder_is_preorder (α : Type u) (r : α → α → Prop) [s : is_total_preorder α r] : is_preorder α r := {trans := s.trans, refl := λ a, or.elim (is_total.total r a a) id id} @[algebra] class is_partial_order (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_antisymm α r : Prop. @[algebra] class is_linear_order (α : Type u) (r : α → α → Prop) extends is_partial_order α r, is_total α r : Prop. @[algebra] class is_equiv (α : Type u) (r : α → α → Prop) extends is_preorder α r, is_symm α r : Prop. @[algebra] class is_per (α : Type u) (r : α → α → Prop) extends is_symm α r, is_trans α r : Prop. @[algebra] class is_strict_order (α : Type u) (r : α → α → Prop) extends is_irrefl α r, is_trans α r : Prop. @[algebra] class is_incomp_trans (α : Type u) (lt : α → α → Prop) : Prop := (incomp_trans : ∀ a b c, (¬ lt a b ∧ ¬ lt b a) → (¬ lt b c ∧ ¬ lt c b) → (¬ lt a c ∧ ¬ lt c a)) @[algebra] class is_strict_weak_order (α : Type u) (lt : α → α → Prop) extends is_strict_order α lt, is_incomp_trans α lt : Prop. @[algebra] class is_trichotomous (α : Type u) (lt : α → α → Prop) : Prop := (trichotomous : ∀ a b, lt a b ∨ a = b ∨ lt b a) @[algebra] class is_strict_total_order (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_weak_order α lt. instance eq_is_equiv (α : Type u) : is_equiv α (=) := {symm := @eq.symm _, trans := @eq.trans _, refl := eq.refl} section variables {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r lemma irrefl [is_irrefl α r] (a : α) : ¬ a ≺ a := is_irrefl.irrefl _ a lemma refl [is_refl α r] (a : α) : a ≺ a := is_refl.refl _ a lemma trans [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := is_trans.trans _ _ _ lemma symm [is_symm α r] {a b : α} : a ≺ b → b ≺ a := is_symm.symm _ _ lemma antisymm [is_antisymm α r] {a b : α} : a ≺ b → b ≺ a → a = b := is_antisymm.antisymm _ _ lemma asymm [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := is_asymm.asymm _ _ lemma trichotomous [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := is_trichotomous.trichotomous r lemma incomp_trans [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := is_incomp_trans.incomp_trans _ _ _ instance is_asymm_of_is_trans_of_is_irrefl [is_trans α r] [is_irrefl α r] : is_asymm α r := ⟨λ a b h₁ h₂, absurd (trans h₁ h₂) (irrefl a)⟩ section explicit_relation_variants variable (r) @[elab_simple] lemma irrefl_of [is_irrefl α r] (a : α) : ¬ a ≺ a := irrefl a @[elab_simple] lemma refl_of [is_refl α r] (a : α) : a ≺ a := refl a @[elab_simple] lemma trans_of [is_trans α r] {a b c : α} : a ≺ b → b ≺ c → a ≺ c := trans @[elab_simple] lemma symm_of [is_symm α r] {a b : α} : a ≺ b → b ≺ a := symm @[elab_simple] lemma asymm_of [is_asymm α r] {a b : α} : a ≺ b → ¬ b ≺ a := asymm @[elab_simple] lemma total_of [is_total α r] (a b : α) : a ≺ b ∨ b ≺ a := is_total.total _ _ _ @[elab_simple] lemma trichotomous_of [is_trichotomous α r] : ∀ (a b : α), a ≺ b ∨ a = b ∨ b ≺ a := trichotomous @[elab_simple] lemma incomp_trans_of [is_incomp_trans α r] {a b c : α} : (¬ a ≺ b ∧ ¬ b ≺ a) → (¬ b ≺ c ∧ ¬ c ≺ b) → (¬ a ≺ c ∧ ¬ c ≺ a) := incomp_trans end explicit_relation_variants end namespace strict_weak_order section parameters {α : Type u} {r : α → α → Prop} local infix `≺`:50 := r def equiv (a b : α) : Prop := ¬ a ≺ b ∧ ¬ b ≺ a parameter [is_strict_weak_order α r] local infix ` ≈ `:50 := equiv lemma erefl (a : α) : a ≈ a := ⟨irrefl a, irrefl a⟩ lemma esymm {a b : α} : a ≈ b → b ≈ a := λ ⟨h₁, h₂⟩, ⟨h₂, h₁⟩ lemma etrans {a b c : α} : a ≈ b → b ≈ c → a ≈ c := incomp_trans lemma not_lt_of_equiv {a b : α} : a ≈ b → ¬ a ≺ b := λ h, h.1 lemma not_lt_of_equiv' {a b : α} : a ≈ b → ¬ b ≺ a := λ h, h.2 instance : is_equiv α equiv := {refl := erefl, trans := @etrans, symm := @esymm} end /- Notation for the equivalence relation induced by lt -/ notation a ` ≈[`:50 lt `]` b:50 := @equiv _ lt a b end strict_weak_order lemma is_strict_weak_order_of_is_total_preorder {α : Type u} {le : α → α → Prop} {lt : α → α → Prop} [decidable_rel le] [s : is_total_preorder α le] (h : ∀ a b, lt a b ↔ ¬ le b a) : is_strict_weak_order α lt := { trans := λ a b c hab hbc, have nba : ¬ le b a, from iff.mp (h _ _) hab, have ncb : ¬ le c b, from iff.mp (h _ _) hbc, have hab : le a b, from or.resolve_left (total_of le b a) nba, have nca : ¬ le c a, from λ hca : le c a, have hcb : le c b, from trans_of le hca hab, absurd hcb ncb, iff.mpr (h _ _) nca, irrefl := λ a hlt, absurd (refl_of le a) (iff.mp (h _ _) hlt), incomp_trans := λ a b c ⟨nab, nba⟩ ⟨nbc, ncb⟩, have hba : le b a, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nab), have hab : le a b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nba), have hcb : le c b, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) nbc), have hbc : le b c, from decidable.of_not_not (iff.mp (not_iff_not_of_iff (h _ _)) ncb), have hac : le a c, from trans_of le hab hbc, have hca : le c a, from trans_of le hcb hba, and.intro (λ n, absurd hca (iff.mp (h _ _) n)) (λ n, absurd hac (iff.mp (h _ _) n)) } lemma lt_of_lt_of_incomp {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, lt a b → (¬ lt b c ∧ ¬ lt c b) → lt a c := λ a b c hab ⟨nbc, ncb⟩, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hca hab) ncb, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt a b ∧ ¬ lt b a, from incomp_trans_of lt ⟨nac, nca⟩ ⟨ncb, nbc⟩, absurd hab this.1 lemma lt_of_incomp_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_weak_order α lt] [decidable_rel lt] : ∀ {a b c}, (¬ lt a b ∧ ¬ lt b a) → lt b c → lt a c := λ a b c ⟨nab, nba⟩ hbc, have nca : ¬ lt c a, from λ hca, absurd (trans_of lt hbc hca) nba, decidable.by_contradiction $ λ nac : ¬ lt a c, have ¬ lt b c ∧ ¬ lt c b, from incomp_trans_of lt ⟨nba, nab⟩ ⟨nac, nca⟩, absurd hbc this.1 lemma eq_of_incomp {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : (¬ lt a b ∧ ¬ lt b a) → a = b := λ ⟨nab, nba⟩, match trichotomous_of lt a b with | or.inl hab := absurd hab nab | or.inr (or.inl hab) := hab | or.inr (or.inr hba) := absurd hba nba end lemma eq_of_eqv_lt {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] {a b} : a ≈[lt] b → a = b := eq_of_incomp lemma incomp_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : (¬ lt a b ∧ ¬ lt b a) ↔ a = b := iff.intro eq_of_incomp (λ hab, eq.subst hab (and.intro (irrefl_of lt a) (irrefl_of lt a))) lemma eqv_lt_iff_eq {α : Type u} {lt : α → α → Prop} [is_trichotomous α lt] [is_irrefl α lt] (a b) : a ≈[lt] b ↔ a = b := incomp_iff_eq a b lemma not_lt_of_lt {α : Type u} {lt : α → α → Prop} [is_strict_order α lt] {a b} : lt a b → ¬ lt b a := λ h₁ h₂, absurd (trans_of lt h₁ h₂) (irrefl_of lt _)
8d1fc033acca59abb3d67f7c96bce8cf9411d362
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/analysis/inner_product_space/pi_L2.lean
54530dfb50a278fdab068387ec4702ff009fb0b8
[ "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
8,693
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth -/ import analysis.inner_product_space.projection import analysis.normed_space.pi_Lp /-! # `L²` inner product space structure on finite products of inner product spaces The `L²` norm on a finite product of inner product spaces is compatible with an inner product $$ \langle x, y\rangle = \sum \langle x_i, y_i \rangle. $$ This is recorded in this file as an inner product space instance on `pi_Lp 2`. ## Main definitions - `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 (n → 𝕜)` for any `fintype n`, i.e., the space from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably that it is a finite-dimensional inner product space). - `basis.isometry_euclidean_of_orthonormal`: provides the isometry to Euclidean space from a given finite-dimensional inner product space, induced by a basis of the space. - `linear_isometry_equiv.of_inner_product_space`: provides an arbitrary isometry to Euclidean space from a given finite-dimensional inner product space, induced by choosing an arbitrary basis. - `complex.isometry_euclidean`: standard isometry from `ℂ` to `euclidean_space ℝ (fin 2)` -/ open real set filter is_R_or_C open_locale big_operators uniformity topological_space nnreal ennreal complex_conjugate local attribute [instance] fact_one_le_two_real noncomputable theory variables {ι : Type*} variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y /- If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space, then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm, we use instead `pi_Lp 2 f` for the product space, which is endowed with the `L^2` norm. -/ instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*) [Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 f) := { inner := λ x y, ∑ i, inner (x i) (y i), norm_sq_eq_inner := begin intro x, have h₁ : ∑ (i : ι), ∥x i∥ ^ (2 : ℕ) = ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { apply finset.sum_congr rfl, intros j hj, simp [←rpow_nat_cast] }, have h₂ : 0 ≤ ∑ (i : ι), ∥x i∥ ^ (2 : ℝ), { rw [←h₁], exact finset.sum_nonneg (λ j (hj : j ∈ finset.univ), pow_nonneg (norm_nonneg (x j)) 2) }, simp [norm, add_monoid_hom.map_sum, ←norm_sq_eq_inner], rw [←rpow_nat_cast ((∑ (i : ι), ∥x i∥ ^ (2 : ℝ)) ^ (2 : ℝ)⁻¹) 2], rw [←rpow_mul h₂], norm_num [h₁], end, conj_sym := begin intros x y, unfold inner, rw ring_equiv.map_sum, apply finset.sum_congr rfl, rintros z -, apply inner_conj_sym, end, add_left := λ x y z, show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i), by simp only [inner_add_left, finset.sum_add_distrib], smul_left := λ x y r, show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i), by simp only [finset.mul_sum, inner_smul_left] } @[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 f) : ⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ := rfl lemma pi_Lp.norm_eq_of_L2 {ι : Type*} [fintype ι] {f : ι → Type*} [Π i, inner_product_space 𝕜 (f i)] (x : pi_Lp 2 f) : ∥x∥ = sqrt (∑ (i : ι), ∥x i∥ ^ 2) := by { rw [pi_Lp.norm_eq_of_nat 2]; simp [sqrt_eq_rpow] } /-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional space use `euclidean_space 𝕜 (fin n)`. -/ @[reducible, nolint unused_arguments] def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜] (n : Type*) [fintype n] : Type* := pi_Lp 2 (λ (i : n), 𝕜) lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n] (x : euclidean_space 𝕜 n) : ∥x∥ = real.sqrt (∑ (i : n), ∥x i∥ ^ 2) := pi_Lp.norm_eq_of_L2 x section local attribute [reducible] pi_Lp variables [fintype ι] instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance @[simp] lemma finrank_euclidean_space : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp lemma finrank_euclidean_space_fin {n : ℕ} : finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp /-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry from `E` to `pi_Lp 2` of the subspaces equipped with the `L2` inner product. -/ def direct_sum.submodule_is_internal.isometry_L2_of_orthogonal_family [decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.submodule_is_internal V) (hV' : orthogonal_family 𝕜 V) : E ≃ₗᵢ[𝕜] pi_Lp 2 (λ i, V i) := begin let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i), let e₂ := linear_equiv.of_bijective _ hV.injective hV.surjective, refine (e₂.symm.trans e₁).isometry_of_inner _, suffices : ∀ v w, ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫, { intros v₀ w₀, convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀)); simp only [linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] }, intros v w, transitivity ⟪(∑ i, (v i : E)), ∑ i, (w i : E)⟫, { simp [sum_inner, hV'.inner_right_fintype] }, { congr; simp } end /-- An orthonormal basis on a fintype `ι` for an inner product space induces an isometry with `euclidean_space 𝕜 ι`. -/ def basis.isometry_euclidean_of_orthonormal (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι := v.equiv_fun.isometry_of_inner begin intros x y, let p : euclidean_space 𝕜 ι := v.equiv_fun x, let q : euclidean_space 𝕜 ι := v.equiv_fun y, have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫, { simp [sum_inner, inner_smul_left, hv.inner_right_fintype] }, convert key, { rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] }, { rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] } end end /-- `ℂ` is isometric to `ℝ²` with the Euclidean inner product. -/ def complex.isometry_euclidean : ℂ ≃ₗᵢ[ℝ] (euclidean_space ℝ (fin 2)) := complex.basis_one_I.isometry_euclidean_of_orthonormal begin rw orthonormal_iff_ite, intros i, fin_cases i; intros j; fin_cases j; simp [real_inner_eq_re_inner] end @[simp] lemma complex.isometry_euclidean_symm_apply (x : euclidean_space ℝ (fin 2)) : complex.isometry_euclidean.symm x = (x 0) + (x 1) * I := begin convert complex.basis_one_I.equiv_fun_symm_apply x, { simpa }, { simp }, end lemma complex.isometry_euclidean_proj_eq_self (z : ℂ) : ↑(complex.isometry_euclidean z 0) + ↑(complex.isometry_euclidean z 1) * (I : ℂ) = z := by rw [← complex.isometry_euclidean_symm_apply (complex.isometry_euclidean z), complex.isometry_euclidean.symm_apply_apply z] @[simp] lemma complex.isometry_euclidean_apply_zero (z : ℂ) : complex.isometry_euclidean z 0 = z.re := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } @[simp] lemma complex.isometry_euclidean_apply_one (z : ℂ) : complex.isometry_euclidean z 1 = z.im := by { conv_rhs { rw ← complex.isometry_euclidean_proj_eq_self z }, simp } open finite_dimensional /-- Given a natural number `n` equal to the `finrank` of a finite-dimensional inner product space, there exists an isometry from the space to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.of_inner_product_space [finite_dimensional 𝕜 E] {n : ℕ} (hn : finrank 𝕜 E = n) : E ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := (fin_orthonormal_basis hn).isometry_euclidean_of_orthonormal (fin_orthonormal_basis_orthonormal hn) local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ /-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product space, there exists an isometry from the orthogonal complement of a nonzero singleton to `euclidean_space 𝕜 (fin n)`. -/ def linear_isometry_equiv.from_orthogonal_span_singleton (n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) : (𝕜 ∙ v)ᗮ ≃ₗᵢ[𝕜] (euclidean_space 𝕜 (fin n)) := linear_isometry_equiv.of_inner_product_space (finrank_orthogonal_span_singleton hv)
91fcc0920ec6bbf0a14dee19de35909b6fbbeaee
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/group-representation/trivial_representation.lean
6d395edaa398240d8a54028fe3ee87a232f97fa2
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
504
lean
import group_representation universe variables u v w namespace trivial_representation /- Construction of trivial let (R : Ring) M module, ρ : G →ₗ GL R M given by identity -/ def trivial_representation (G :Type u)(R : Type v)(M : Type w)[group G] [ring R] [add_comm_group M] [module R M] : group_representation G R M := { to_fun := λ g, 1, map_one' := rfl, map_mul' := λ _ _, one_mul 1} end trivial_representation
3fd538e7d46b84db5f08ba784d2909f11b10d4e6
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tactic11.lean
5ac6d3655dc6846eb1570568d66225c9debd32b1
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
139
lean
(* import("tactic.lua") *) theorem T (a b : Bool) : ((fun x, x /\ b) a) → ((fun x, x) a) := _ . beta. conj_hyp. exact. done.
6013320754caf03e311c58ab8ca414bc56334e61
29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f
/22_lecture.lean
de6de8c523e73711c89757f0e1a24be64b00a4c3
[]
no_license
KjellZijlemaker/Logical_Verification_VU
ced0ba95316a30e3c94ba8eebd58ea004fa6f53b
4578b93bf1615466996157bb333c84122b201d99
refs/heads/master
1,585,966,086,108
1,549,187,704,000
1,549,187,704,000
155,690,284
0
0
null
null
null
null
UTF-8
Lean
false
false
7,130
lean
/- Lecture 2.2: Functional Programming — Trees -/ /- Binary trees -/ namespace my_bin_tree inductive tree (α : Type) : Type | empty {} : tree | node (a : α) (l : tree) (r : tree) : tree export tree (empty node) def t0 : tree ℕ := node 0 empty empty def t1 : tree ℕ := node 1 empty empty def t2 : tree ℕ := node 2 t0 t1 def mirror {α : Type} : tree α → tree α | empty := empty | (node a l r) := node a (mirror r) (mirror l) lemma mirror_eq_empty_iff {α : Type} : ∀t : tree α, mirror t = empty ↔ t = empty | empty := by refl | (node _ _ _) := by simp [mirror] lemma mirror_mirror {α : Type} : ∀t : tree α, mirror (mirror t) = t | empty := by refl | (node a l r) := begin simp [mirror], apply and.intro, { apply mirror_mirror l }, { apply mirror_mirror r } end inductive is_full {α : Type} : tree α → Prop | empty : is_full empty | node (a : α) (l r : tree α) (hl : is_full l) (hr : is_full r) (empty_iff : l = empty ↔ r = empty) : is_full (node a l r) lemma is_full_singleton {α : Type} (a : α) : is_full (node a empty empty) := begin apply is_full.node, repeat { apply is_full.empty }, refl end lemma is_full_t0 : is_full t0 := is_full_singleton _ lemma is_full_t1 : is_full t1 := is_full_singleton _ lemma is_full_t2 : is_full t2 := begin unfold t2, apply is_full.node, exact is_full_t0, exact is_full_t1, unfold t0 t1, simp end -- proof by structural induction on `t` lemma is_full_mirror {α : Type} : ∀t : tree α, is_full t → is_full (mirror t) | empty := by intro; assumption | (node a l r) := begin intro full_t, cases full_t, unfold mirror, apply is_full.node, repeat { apply is_full_mirror, assumption }, simp [mirror_eq_empty_iff, *] end -- proof by rule induction on `is_full t` example {α : Type} : ∀t : tree α, is_full t → is_full (mirror t) | _ is_full.empty := by unfold mirror; exact is_full.empty | _ (is_full.node a l r hl hr empty_iff) := begin unfold mirror, apply is_full.node, repeat { apply _example, assumption }, simp [mirror_eq_empty_iff, *] end -- inversion rule lemma is_full_node_iff {α : Type} (a : α) (l r : tree α) : is_full (node a l r) ↔ is_full l ∧ is_full r ∧ (l = empty ↔ r = empty) := iff.intro (assume h, match h with | is_full.node a l r h_hl h_hr h_empty_iff := ⟨h_hl, h_hr, h_empty_iff⟩ end) (assume h, match h with | ⟨h_hl, h_hr, h_empty_iff⟩ := is_full.node a l r h_hl h_hr h_empty_iff end) -- proof using rule inversion example {α : Type} : ∀t : tree α, is_full t → is_full (mirror t) | _ is_full.empty := by unfold mirror; exact is_full.empty | _ (is_full.node a l r hl hr empty_iff) := by simp [mirror, is_full_node_iff, _example l hl, _example r hr, mirror_eq_empty_iff, empty_iff] end my_bin_tree /- Red-black trees -/ namespace my_red_black_tree inductive color : Type | red : color | black : color export color (red black) inductive tree (α : Type) : Type | empty {} : tree | node (c : color) (k : ℤ) (v : α) (l : tree) (r : tree) : tree export tree (empty node) def lookup {α : Type} (x : ℤ) : tree α → option α | empty := none | (node _ k v l r) := if x < k then lookup l else if x > k then lookup r else some v inductive is_balanced {α : Type} : tree α → color → ℕ → Prop | leaf (c : color) : is_balanced empty c 0 | red (k : ℤ) (v : α) (l : tree α) (r : tree α) (n : ℕ) (hl : is_balanced l red n) (hr : is_balanced r red n) : is_balanced (node red k v l r) black n | black c k v l r n (hl : is_balanced l black n) (hr : is_balanced r black n) : is_balanced (node black k v l r) c (n + 1) /- We could continue here and define more operations and show that they preserve the `is_balanced` invariant. -/ end my_red_black_tree /- Huffman's algorithm -/ namespace huffman inductive tree (α : Type) | leaf : ℕ → α → tree | inner : ℕ → tree → tree → tree export tree (leaf inner) def stored_weight {α : Type} : tree α → ℕ | (leaf w _) := w | (inner w _ _) := w def unite {α : Type} : tree α → tree α → tree α | l r := inner (stored_weight l + stored_weight r) l r def insort {α : Type} (u : tree α) : list (tree α) → list (tree α) | [] := [u] | (t :: ts) := if stored_weight u ≤ stored_weight t then u :: t :: ts else t :: insort ts lemma insort_ne_nil {α : Type} (t : tree α) (ts : list (tree α)) : insort t ts ≠ [] := begin cases ts; simp [insort], by_cases (stored_weight t ≤ stored_weight ts_hd); simp * end lemma length_insort {α : Type} (t : tree α) : ∀ts : list (tree α), list.length (insort t ts) = list.length ts + 1 | [] := by refl | (t' :: ts) := by by_cases stored_weight t ≤ stored_weight t'; simp [insort, *] def huffman {α : Type} : Πts : list (tree α), ts ≠ [] → tree α | [] h := absurd (refl _) h | [t] _ := t | (t :: u :: ts) _ := have list.length (insort (unite t u) ts) < 1 + (1 + list.length ts) := by simp [length_insort]; exact nat.lt_add_of_pos_left nat.zero_lt_one, huffman (insort (unite t u) ts) (insort_ne_nil _ _) using_well_founded {rel_tac := λ_ _, `[exact ⟨_, measure_wf (list.length ∘ psigma.fst)⟩]} #print has_well_founded /- `measure_wf (list.length ∘ psigma.fst)⟩` tells us that the termination measure is the length of the first argument `ts`. (The second argument is the proof of `ts ≠ []`.) -/ def ts1 : list (tree char) := [leaf 2 'z', leaf 3 'd', leaf 5 'f', leaf 7 's', leaf 11 'e'] #eval huffman ts1 (by simp [ts1]) def tree.repr {α : Type} [has_repr α] : tree α → string | (leaf w a) := "(leaf " ++ repr w ++ " " ++ repr a ++ ")" | (inner w l r) := "(inner " ++ repr w ++ " " ++ tree.repr l ++ " " ++ tree.repr r ++ ")" instance {α : Type} [has_repr α] : has_repr (tree α) := ⟨tree.repr⟩ #eval huffman ts1 (by simp [ts1]) end huffman /- First-order terms -/ namespace fo_terms inductive term (α β : Type) : Type | var {} (x : β) : term | fn (f : α) (ts : list term) : term export term (var fn) inductive well_formed {α β : Type} (ary : α → ℕ) : term α β → Prop | var (x : β) : well_formed (var x) | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, well_formed t) (hlen : list.length ts = ary f) : well_formed (fn f ts) inductive ground {α β : Type} : term α β → Prop | fn (f : α) (ts : list (term α β)) (hargs : ∀t ∈ ts, ground t) : ground (fn f ts) def wf_term (α β : Type) (ary : α → ℕ) : Type := {t : term α β // well_formed ary t} def gr_term (α β : Type) : Type := {t : term α β // ground t} def gr_wf_term (α β : Type) (ary : α → ℕ) : Type := {t : term α β // well_formed ary t ∧ ground t} end fo_terms /- This fails: namespace wf_fo_terms inductive term (α β : Type) (ary : α → ℕ) : Type | var {} (x : β) : term | fn (f : α) (ts : list term) (hlen : list.length ts = ary f) : term export term (var fn) end wf_fo_terms -/
118fcb0ecee86accd293823b4d130d3f608662b5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/test/differentiable.lean
31f29b84a89faececa37e1538cfa27788090d49d
[ "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,418
lean
import analysis.special_functions.trigonometric namespace real example : differentiable ℝ (λ (x : ℝ), exp x) := by simp example : differentiable ℝ (λ (x : ℝ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℝ) : deriv (λ (x : ℝ), (cos x)^2 + 1 + (sin x)^2) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ (x : ℝ), (1+x)^3 - x^3 - 3 * x^2 - 3 * x - 4) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℝ) : differentiable_at ℝ (λ x, (cos x, x)) x := by simp example (x : ℝ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℝ) : differentiable_at ℝ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℝ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] example (x : ℝ) (h : x ≠ 0) : deriv (λ x, x * (log x - 1)) x = log x := by simp [h] end real namespace complex example : differentiable ℂ (λ (x : ℂ), exp x) := by simp example : differentiable ℂ (λ (x : ℂ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℂ) : deriv (λ (x : ℂ), (cos x)^2 + I + (sin x)^2) x = 0 := by { simp, ring } example (x : ℂ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℂ) : differentiable_at ℂ (λ x, (cos x, x)) x := by simp example (x : ℂ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℂ) : differentiable_at ℂ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℂ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] end complex namespace polynomial variables {R : Type*} [comm_semiring R] example : (2 : polynomial R).derivative = 0 := by conv_lhs { simp } example : (3 + X : polynomial R).derivative = 1 := by conv_lhs { simp } example : (2 * X ^ 2 : polynomial R).derivative = 4 * X := by conv_lhs { simp, ring_nf, } example : (X ^ 2 : polynomial R).derivative = 2 * X := by conv_lhs { simp } example : ((C 2 * X ^ 3).derivative : polynomial R) = 6 * X ^ 2 := by conv_lhs { simp, ring_nf, } end polynomial
e59669514a8c57324cf45a60c2e32070e9da1943
7cef822f3b952965621309e88eadf618da0c8ae9
/src/algebraic_geometry/stalks.lean
02f73d7798779a2ace3b16b2f4fe675db1dcc7d4
[ "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
1,980
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 algebraic_geometry.presheafed_space import topology.sheaves.stalks /-! # Stalks for presheaved spaces This file lifts constructions of stalks and pushforwards of stalks to work with the category of presheafed spaces. -/ universes v u v' u' open category_theory open category_theory.limits category_theory.category category_theory.functor open algebraic_geometry open topological_space variables {C : Type u} [𝒞 : category.{v} C] [has_colimits.{v} C] include 𝒞 local attribute [tidy] tactic.op_induction' open Top.presheaf namespace algebraic_geometry.PresheafedSpace def stalk (X : PresheafedSpace.{v} C) (x : X) : C := X.𝒪.stalk x def stalk_map {X Y : PresheafedSpace.{v} C} (α : X ⟶ Y) (x : X) : Y.stalk (α x) ⟶ X.stalk x := (stalk_functor C (α x)).map (α.c) ≫ X.𝒪.stalk_pushforward C α x namespace stalk_map @[simp] lemma id (X : PresheafedSpace.{v} C) (x : X) : stalk_map (𝟙 X) x = 𝟙 (X.stalk x) := begin dsimp [stalk_map], simp only [stalk_pushforward.id], rw [←map_comp], convert (stalk_functor C x).map_id X.𝒪, tidy, end @[simp] lemma comp {X Y Z : PresheafedSpace.{v} C} (α : X ⟶ Y) (β : Y ⟶ Z) (x : X) : stalk_map (α ≫ β) x = (stalk_map β (α x) : Z.stalk (β (α x)) ⟶ Y.stalk (α x)) ≫ (stalk_map α x : Y.stalk (α x) ⟶ X.stalk x) := begin dsimp [stalk_map, stalk_functor, stalk_pushforward], ext U, op_induction U, cases U, simp only [colim.ι_map_assoc, colimit.ι_pre_assoc, colimit.ι_pre, whisker_left_app, whisker_right_app, assoc, id_comp, map_id, map_comp], dsimp, simp only [map_id, assoc], -- FIXME Why doesn't simp do this: erw [category_theory.functor.map_id], erw [category_theory.functor.map_id], erw [id_comp, id_comp], end end stalk_map end algebraic_geometry.PresheafedSpace
a8caae344b3ddc526b6370a650aff76b51ea18f5
206422fb9edabf63def0ed2aa3f489150fb09ccb
/src/linear_algebra/linear_independent.lean
e3070add3d3eceda30c03b90e38f6d97f4bc597a
[ "Apache-2.0" ]
permissive
hamdysalah1/mathlib
b915f86b2503feeae268de369f1b16932321f097
95454452f6b3569bf967d35aab8d852b1ddf8017
refs/heads/master
1,677,154,116,545
1,611,797,994,000
1,611,797,994,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
41,562
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import linear_algebra.finsupp import order.zorn import data.finset.order import data.equiv.fin /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that any family of vectors includes a linear independent subfamily spanning the same submodule. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} 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 {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (finsupp.total ι M R v).to_add_monoid_hom.injective_iff.symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (h ⟨i⟩) end lemma linear_independent.ne_zero [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), {simp}, {simp [h]} end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the sumodule spaned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.set.range f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := (linear_independent_equiv' (equiv.set.of_eq $ by rw [range_comp, subtype.range_coe]) rfl).1 hs.to_subtype_range lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨hl₁, hl₂⟩), simp [this] end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.injective_inl, h.comp _ sum.injective_inr, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.injective_inl.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.injective_inr.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x hx, disjoint_left.1 is_compl_range_inl_range_inr.1) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem _ $ λ i hi, _) _ (neg_mem _ $ sum_mem _ $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (finite.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros i s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros i, exact ⟨i, le_refl _⟩ }, { exact s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero _ h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [comm_ring L] [no_zero_divisors L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section vector_space variables [field K] [add_comm_group V] [add_comm_group V'] [vector_space K V] [vector_space K V'] variables {v : ι → V} {s t : set V} {x y z : V} include K open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent_unique_iff [unique ι] : linear_independent K v ↔ v (default ι) ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single (default ι) 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : V} (hx : x ≠ 0) : linear_independent K (λ x, x : ({x} : set V) → V) := @linear_independent_unique _ _ _ _ _ _ _ (set.unique_singleton _) ‹_› lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], simp [(∘), fin_succ_equiv, option.coe_def, fin.cons_succ, *] end lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists]; refl lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset₀ {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end vector_space
37b10caf1223b16a3308a15ee423beffc599c068
3a7eb58cccd9e625ebf79689f8f0f244a20b6158
/render.lean
1bf11625b093fa4fb7e3ab52a0cebc6e2155cfa7
[]
no_license
hermetique/lean4-raytracer
c1ea6336dbb44296af60ee8e416cc9c87d6827a9
092c9a6c4ee612786082b807491ccefaed961462
refs/heads/master
1,677,468,320,587
1,612,291,379,000
1,612,291,379,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,992
lean
import render.vec3 @[inline] def Float.max (x y : Float) : Float := if x ≤ y then y else x @[inline] def Float.min (x y : Float) : Float := if x ≤ y then x else y @[inline] def Float.abs (x : Float) : Float := if x ≤ 0 then -x else x def Float.pi : Float := 3.1415926535897932385 def Float.infinity : Float := 1e100 -- fix this /-- Uniform at random in [0, 1)-/ def randomFloat {gen} [RandomGen gen] (g : gen) : Float × gen := let (n, g') := RandomGen.next g let (lo, hi) := RandomGen.range g (Float.ofNat (n - lo) / Float.ofNat (hi - lo + 1), g') def IO.randFloat (lo := 0.0) (hi := 1.0) : IO Float := do let gen ← IO.stdGenRef.get let (r, gen) := randomFloat gen IO.stdGenRef.set gen pure $ lo + (hi - lo) * r def IO.randVec3 (lo := 0.0) (hi := 1.0) : IO (Vec3 Float) := return ⟨←IO.randFloat lo hi, ←IO.randFloat lo hi, ←IO.randFloat lo hi⟩ def IO.randVec3InUnitSphere : IO (Vec3 Float) := do for i in [0:100] do -- 7e-33 probability of failure let p ← IO.randVec3 (-1.0) (1.0) if p.lengthSquared < 1.0 then return p return ⟨1, 0, 0⟩ def IO.randVec3InUnitDisk : IO (Vec3 Float) := do for i in [0:100] do -- 2e-67 probability of failure let p := Vec3.mk (← IO.randFloat (-1.0) (1.0)) (← IO.randFloat (-1.0) (1.0)) 0.0 if p.lengthSquared < 1.0 then return p return ⟨0, 0, 0⟩ structure Ray (α : Type _) where origin : Vec3 α dir : Vec3 α def Ray.at [Add α] [Mul α] (r : Ray α) (t : α) : Vec3 α := r.origin + t * r.dir structure Camera where origin : Vec3 Float lowerLeftCorner : Vec3 Float horizontal : Vec3 Float vertical : Vec3 Float (u v w : Vec3 Float) /- right up back -/ lensRadius : Float /-- vfov is the vertical field of view (in degrees) -/ def Camera.default (lookFrom lookAt vup : Vec3 Float) (vfov : Float) (aspectRatio : Float) (aperture : Float) (focusDist : Float) : Camera := let theta := vfov / 180. * Float.pi let h := Float.tan (theta / 2) let viewportHeight := 2.0 * h let viewportWidth := aspectRatio * viewportHeight let w := (lookFrom - lookAt).normalized let u := (vup.cross w).normalized let v := w.cross u let origin := lookFrom let horizontal := focusDist * viewportWidth * u let vertical := focusDist * viewportHeight * v let lowerLeftCorner := origin - horizontal/2.0 - vertical/2.0 - focusDist * w Camera.mk origin lowerLeftCorner horizontal vertical u v w (aperture / 2.0) def Camera.getRay (c : Camera) (s t : Float) : IO (Ray Float) := do let rd := c.lensRadius * (← IO.randVec3InUnitDisk) let offset := rd.x * c.u + rd.y * c.v Ray.mk (c.origin + offset) (c.lowerLeftCorner + s*c.horizontal + t*c.vertical - c.origin - offset) structure HitRecord where p : Vec3 Float t : Float normal : Vec3 Float frontFace : Bool @[inline] def HitRecord.withNormal (p : Vec3 Float) (t : Float) (r : Ray Float) (outwardNormal : Vec3 Float) : HitRecord := let frontFace : Bool := r.dir.dot outwardNormal < 0.0 let normal : Vec3 Float := if frontFace then outwardNormal else -outwardNormal return { p := p t := t normal := normal frontFace := frontFace } inductive MaterialResponse | absorb | scatter (albedo : Color Float) (scattered : Ray Float) structure Material where scatter : Ray Float → HitRecord → IO MaterialResponse def lambertian (albedo : Color Float) : Material where scatter (r : Ray Float) (hitrec : HitRecord) := do let mut scatterDir := hitrec.normal + (←IO.randVec3InUnitSphere).normalized if scatterDir.nearZero then scatterDir := hitrec.normal let scattered := Ray.mk hitrec.p scatterDir return MaterialResponse.scatter albedo scattered def metal (albedo : Color Float) (fuzz : Float := 0.0) : Material where scatter (r : Ray Float) (hitrec : HitRecord) := do let reflected := r.dir.normalized.reflect hitrec.normal let scattered := Ray.mk hitrec.p (reflected + fuzz * (← IO.randVec3InUnitSphere)) if scattered.dir.dot hitrec.normal > 0.0 then return MaterialResponse.scatter albedo scattered else return MaterialResponse.absorb def refract (uv : Vec3 Float) (n : Vec3 Float) (etai_over_etat : Float) : Vec3 Float := let cosTheta := Float.min (- uv.dot n) 1.0 let rOutPerp := etai_over_etat * (uv + cosTheta * n) let rOutParallel := (-Float.sqrt (Float.abs (1.0 - rOutPerp.lengthSquared))) * n rOutPerp + rOutParallel def dielectric (indexOfRefraction : Float) : Material where scatter (r : Ray Float) (hitrec : HitRecord) := do let refractionRatio := if hitrec.frontFace then 1.0/indexOfRefraction else indexOfRefraction let unitDirection := r.dir.normalized let cosTheta := Float.min (-unitDirection.dot hitrec.normal) 1.0 let sinTheta := Float.sqrt (1.0 - cosTheta * cosTheta) let cannotRefract : Bool := refractionRatio * sinTheta > 1.0 -- Schlick's approximation let reflectance (cosine : Float) (refIdx : Float) : Float := let r0' := (1 - refIdx) / (1 + refIdx) let r0 := r0' * r0' r0 + (1 - r0) * Float.pow (1 - cosine) 5 let direction : Vec3 Float := if cannotRefract || reflectance cosTheta refractionRatio > (← IO.randFloat) then Vec3.reflect unitDirection hitrec.normal else refract unitDirection hitrec.normal refractionRatio let scattered := Ray.mk hitrec.p direction return MaterialResponse.scatter Color.white scattered structure Hittable where hit : Ray Float → Float -> Float -> Option (HitRecord × Material) def mkSphere (center : Vec3 Float) (radius : Float) (mat : Material) : Hittable where hit (r : Ray Float) (tmin tmax : Float) := Id.run <| do let oc := r.origin - center let a := r.dir.lengthSquared let halfb := Vec3.dot oc r.dir let c := oc.lengthSquared - radius * radius let discr := halfb*halfb - a*c if discr < 0.0 then return none let sqrtd := discr.sqrt -- Find the nearest root that lies in the acceptable range let mut root := (-halfb - sqrtd) / a if root < tmin || tmax < root then root := (-halfb + sqrtd) / a if root < tmin || tmax < root then return none let t := root let p := r.at t let outwardNormal := (p - center) / radius return some (HitRecord.withNormal p t r outwardNormal, mat) def hitList (hs : Array Hittable) (r : Ray Float) (tmin tmax : Float) : Option (HitRecord × Material) := Id.run <| do let mut hitrec : Option (HitRecord × Material) := none for obj in hs do let closest := (hitrec.map (HitRecord.t ∘ Prod.fst)).getD tmax hitrec := obj.hit r tmin closest <|> hitrec return hitrec def rayColor (hs : Array Hittable) (r : Ray Float) : (depth : Nat) → IO (Color Float) | 0 => return ⟨0, 0, 0⟩ -- exceeded ray bounce limit, no more light gathered | (depth+1) => do match hitList hs r 0.001 Float.infinity with | some (hitrec, mat) => do match ← mat.scatter r hitrec with | MaterialResponse.absorb => return Color.black | MaterialResponse.scatter albedo scattered => return albedo * (← rayColor hs scattered depth) | none => do let unit : Vec3 Float := r.dir.normalized let t := 0.5 * (unit.y + 1.0) return (1.0 - t) * Color.white + t * (Color.mk 0.5 0.7 1.0) def Float.clampToUInt8 (x : Float) : UInt8 := Float.toUInt8 <| Float.min 255 <| Float.max 0 x def IO.FS.Handle.writeColor (handle : IO.FS.Handle) (c : Color Float) : IO Unit := do let r := Float.clampToUInt8 (256 * c.r.sqrt) let g := Float.clampToUInt8 (256 * c.g.sqrt) let b := Float.clampToUInt8 (256 * c.b.sqrt) handle.putStrLn s!"{r} {g} {b}" def randomScene : IO (Array Hittable) := do let mut world : Array Hittable := #[] -- Ground world := world.push <| mkSphere ⟨0, -1000, 0⟩ 1000 (lambertian ⟨0.5, 0.5, 0.5⟩) for a' in [0:22] do let a := Float.ofNat a' - 11 for b' in [0:22] do let b := Float.ofNat b' - 11 let center : Vec3 Float := ⟨a + 0.9 * (← IO.randFloat), 0.2, b + 0.9 * (← IO.randFloat)⟩ if Vec3.length (center - Vec3.mk 4 0.2 0) > 0.9 then let chooseMat ← IO.randFloat if chooseMat < 0.9 then let albedo : Color Float := (← IO.randVec3) * (← IO.randVec3) world := world.push <| mkSphere center 0.2 (lambertian albedo) else if chooseMat < 0.95 then let albedo : Color Float ← IO.randVec3 0.5 1 let fuzz ← IO.randFloat 0 0.5 world := world.push <| mkSphere center 0.2 (metal albedo fuzz) else world := world.push <| mkSphere center 0.2 (dielectric 1.5) world := world.push <| mkSphere ⟨0, 1, 0⟩ 1 (dielectric 1.5) world := world.push <| mkSphere ⟨-4, 1, 0⟩ 1 (lambertian ⟨0.4, 0.2, 0.1⟩) world := world.push <| mkSphere ⟨4, 1, 0⟩ 1 (metal ⟨0.7, 0.6, 0.5⟩) return world def writeTestImage (filename : String) : IO Unit := do let width : Nat := 500 let height : Nat := width * 2 / 3 let aspectRatio : Float := (Float.ofNat width) / (Float.ofNat height) let numThreads := 8 let samplesPerPixel := 10 let maxDepth := 30 let world ← randomScene let lookFrom : Vec3 Float := ⟨13, 2, 3⟩ let lookAt : Vec3 Float := ⟨0, 0, 0⟩ let vup : Vec3 Float := ⟨0, 1, 0⟩ let distToFocus := 10 let aperture := 0.1 let cam := Camera.default lookFrom lookAt vup 20.0 aspectRatio aperture distToFocus let renderTask (showProgress := false) : IO (Array (Color Float)) := do let mut pixels : Array (Color Float) := Array.empty for j' in [0:height] do if showProgress then IO.println s!"line {j'+1} of {height}" let j := height - j' - 1 for i in [0:width] do let mut pixelColor := Color.black for s in [0:samplesPerPixel] do let u := (Float.ofNat i + (← IO.randFloat))/ Float.ofNat width let v := (Float.ofNat j + (← IO.randFloat))/ Float.ofNat height let ray ← cam.getRay u v pixelColor := pixelColor + (← rayColor world ray maxDepth) pixels := pixels.push pixelColor return pixels IO.println s!"Starting {numThreads} threads." let mut tasks := Array.empty for i in [0:numThreads] do tasks := tasks.push (← IO.asTask (renderTask (i = 0))) let mut pixels : Array (Color Float) := Array.mkArray (height * width) Color.black for t in tasks do let pixels' ← (IO.ofExcept (← IO.wait t)) let pixels'' := pixels for i in [0:height*width] do pixels := pixels.set! i (pixels'[i] + pixels''[i]) IO.println s!"Writing to {filename}" IO.FS.withFile filename IO.FS.Mode.write λ handle => do handle.putStrLn "P3" handle.putStrLn s!"{width} {height} 255" for i in [0:height*width] do let pixel := pixels[i] handle.writeColor (pixel / Float.ofNat (samplesPerPixel * numThreads)) def main : List String → IO Unit | [] => writeTestImage "out.ppm" | (x::xs) => writeTestImage x
bf3d3058f839e3d738036872a3319088831275d6
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/finset/prod.lean
5e8f04e86d7cb60a18cd5e68415921f1e243d4a5
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,260
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Oliver Nash -/ import data.finset.card /-! # Finsets in product types This file defines finset constructions on the product type `α × β`. Beware not to confuse with the `finset.prod` operation which computes the multiplicative product. ## Main declarations * `finset.product`: Turns `s : finset α`, `t : finset β` into their product in `finset (α × β)`. * `finset.diag`: For `s : finset α`, `s.diag` is the `finset (α × α)` of pairs `(a, a)` with `a ∈ s`. * `finset.off_diag`: For `s : finset α`, `s.off_diag` is the `finset (α × α)` of pairs `(a, b)` with `a, b ∈ s` and `a ≠ b`. -/ open multiset variables {α β γ : Type*} namespace finset /-! ### prod -/ section prod variables {s s' : finset α} {t t' : finset β} {a : α} {b : β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, s.nodup.product t.nodup⟩ /- This notation binds more strongly than (pre)images, unions and intersections. -/ infixr (name := finset.product) ` ×ˢ `:82 := finset.product @[simp] lemma product_val : (s ×ˢ t).1 = s.1 ×ˢ t.1 := rfl @[simp] lemma mem_product {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product lemma mk_mem_product (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := mem_product.2 ⟨ha, hb⟩ @[simp, norm_cast] lemma coe_product (s : finset α) (t : finset β) : (↑(s ×ˢ t) : set (α × β)) = s ×ˢ t := set.ext $ λ x, finset.mem_product lemma subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ s.image prod.fst ×ˢ s.image prod.snd := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ lemma product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s ×ˢ t ⊆ s' ×ˢ t' := λ ⟨x,y⟩ h, mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩ lemma product_subset_product_left (hs : s ⊆ s') : s ×ˢ t ⊆ s' ×ˢ t := product_subset_product hs (subset.refl _) lemma product_subset_product_right (ht : t ⊆ t') : s ×ˢ t ⊆ s ×ˢ t' := product_subset_product (subset.refl _) ht lemma product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s ×ˢ t = s.bUnion (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] lemma product_eq_bUnion_right [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s ×ˢ t = t.bUnion (λ b, s.image $ λ a, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] /-- See also `finset.sup_product_left`. -/ @[simp] lemma product_bUnion [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) : (s ×ˢ t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) := by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] } @[simp] lemma card_product (s : finset α) (t : finset β) : card (s ×ˢ t) = card s * card t := multiset.card_product _ _ lemma filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s ×ˢ t).filter (λ (x : α × β), p x.1 ∧ q x.2) = s.filter p ×ˢ t.filter q := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], exact and_and_and_comm (a ∈ s) (b ∈ t) (p a) (q b) } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s ×ˢ t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros h; use h.1, simp only [function.comp_app, and_self, h.2, em (q b)], cases h.2; { try { simp at h_1 }, simp [h_1] } }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, simp only [and_imp, mem_filter, not_and, not_not, function.comp_app, iff_false, mem_product, not_mem_empty], intros, assumption } end lemma empty_product (t : finset β) : (∅ : finset α) ×ˢ t = ∅ := rfl lemma product_empty (s : finset α) : s ×ˢ (∅ : finset β) = ∅ := eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2) lemma nonempty.product (hs : s.nonempty) (ht : t.nonempty) : (s ×ˢ t).nonempty := let ⟨x, hx⟩ := hs, ⟨y, hy⟩ := ht in ⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩ lemma nonempty.fst (h : (s ×ˢ t).nonempty) : s.nonempty := let ⟨xy, hxy⟩ := h in ⟨xy.1, (mem_product.1 hxy).1⟩ lemma nonempty.snd (h : (s ×ˢ t).nonempty) : t.nonempty := let ⟨xy, hxy⟩ := h in ⟨xy.2, (mem_product.1 hxy).2⟩ @[simp] lemma nonempty_product : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty := ⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.product h.2⟩ @[simp] lemma product_eq_empty {s : finset α} {t : finset β} : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ := by rw [←not_nonempty_iff_eq_empty, nonempty_product, not_and_distrib, not_nonempty_iff_eq_empty, not_nonempty_iff_eq_empty] @[simp] lemma singleton_product {a : α} : ({a} : finset α) ×ˢ t = t.map ⟨prod.mk a, prod.mk.inj_left _⟩ := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } @[simp] lemma product_singleton {b : β} : s ×ˢ {b} = s.map ⟨λ i, (i, b), prod.mk.inj_right _⟩ := by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] } lemma singleton_product_singleton {a : α} {b : β} : ({a} : finset α) ×ˢ ({b} : finset β) = {(a, b)} := by simp only [product_singleton, function.embedding.coe_fn_mk, map_singleton] @[simp] lemma union_product [decidable_eq α] [decidable_eq β] : (s ∪ s') ×ˢ t = s ×ˢ t ∪ s' ×ˢ t := by { ext ⟨x, y⟩, simp only [or_and_distrib_right, mem_union, mem_product] } @[simp] lemma product_union [decidable_eq α] [decidable_eq β] : s ×ˢ (t ∪ t') = s ×ˢ t ∪ s ×ˢ t' := by { ext ⟨x, y⟩, simp only [and_or_distrib_left, mem_union, mem_product] } end prod section diag variables (s t : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s ×ˢ s).filter (λ a : α × α, a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s ×ˢ s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros h; simp only [h, and_true, eq_self_iff_true, and_self], rw ←h.2, exact h.1 } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros h; simp only [h, ne.def, not_false_iff, and_self] } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, exact λ x1 h1 x2 h2 h3, (prod.mk.inj h3).1 }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros h; rw finset.mem_image at *, { use [a₁, h.1, prod.mk.inj_iff.mpr ⟨rfl, h.2⟩] }, { rcases h with ⟨a, h1, h2⟩, have h := prod.mk.inj h2, rw [←h.1, ←h.2], use h1 }, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, simp only [diag_card] at *, rw tsub_eq_of_eq_add_rev, rw this }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end @[simp] lemma diag_empty : (∅ : finset α).diag = ∅ := rfl @[simp] lemma off_diag_empty : (∅ : finset α).off_diag = ∅ := rfl @[simp] lemma diag_union_off_diag : s.diag ∪ s.off_diag = s ×ˢ s := filter_union_filter_neg_eq _ _ @[simp] lemma disjoint_diag_off_diag : disjoint s.diag s.off_diag := disjoint_filter_filter_neg _ _ lemma product_sdiff_diag : s ×ˢ s \ s.diag = s.off_diag := by rw [←diag_union_off_diag, union_comm, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _).symm] lemma product_sdiff_off_diag : s ×ˢ s \ s.off_diag = s.diag := by rw [←diag_union_off_diag, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _)] lemma diag_union : (s ∪ t).diag = s.diag ∪ t.diag := by { ext ⟨i, j⟩, simp only [mem_diag, mem_union, or_and_distrib_right] } variables {s t} lemma off_diag_union (h : disjoint s t) : (s ∪ t).off_diag = s.off_diag ∪ t.off_diag ∪ s ×ˢ t ∪ t ×ˢ s := begin rw [off_diag, union_product, product_union, product_union, union_comm _ (t ×ˢ t), union_assoc, union_left_comm (s ×ˢ t), ←union_assoc, filter_union, filter_union, ←off_diag, ←off_diag, filter_true_of_mem, ←union_assoc], simp only [mem_union, mem_product, ne.def, prod.forall], rintro i j (⟨hi, hj⟩ | ⟨hi, hj⟩), { exact h.forall_ne_finset hi hj }, { exact h.symm.forall_ne_finset hi hj }, end variables (a : α) @[simp] lemma off_diag_singleton : ({a} : finset α).off_diag = ∅ := by simp [←finset.card_eq_zero] lemma diag_singleton : ({a} : finset α).diag = {(a, a)} := by rw [←product_sdiff_off_diag, off_diag_singleton, sdiff_empty, singleton_product_singleton] lemma diag_insert : (insert a s).diag = insert (a, a) s.diag := by rw [insert_eq, insert_eq, diag_union, diag_singleton] lemma off_diag_insert (has : a ∉ s) : (insert a s).off_diag = s.off_diag ∪ {a} ×ˢ s ∪ s ×ˢ {a} := by rw [insert_eq, union_comm, off_diag_union (disjoint_singleton_right.2 has), off_diag_singleton, union_empty, union_right_comm] end diag end finset
416d837ad4dd7c1aa2179ed9aad89233c4a1c194
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/qpf/multivariate/default_auto.lean
68ab3645febb9a5cee351e9ccc7f9f4f54b4f9c4
[]
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
551
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.qpf.multivariate.basic import Mathlib.data.qpf.multivariate.constructions.fix import Mathlib.data.qpf.multivariate.constructions.cofix import Mathlib.data.qpf.multivariate.constructions.comp import Mathlib.data.qpf.multivariate.constructions.quot import Mathlib.data.qpf.multivariate.constructions.prj import Mathlib.data.qpf.multivariate.constructions.const import Mathlib.data.qpf.multivariate.constructions.sigma import Mathlib.PostPort namespace Mathlib end Mathlib
35f5cfcb5359004041a6034620010d7a453b1ec6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/free.lean
dc7baa005232d6e2deea52c309b5526aab33f822
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
23,839
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.hom.group import algebra.hom.equiv.basic import control.applicative import control.traversable.basic import logic.equiv.defs import data.list.basic /-! # Free constructions ## Main definitions * `free_magma α`: free magma (structure with binary operation without any axioms) over alphabet `α`, defined inductively, with traversable instance and decidable equality. * `magma.assoc_quotient α`: quotient of a magma `α` by the associativity equivalence relation. * `free_semigroup α`: free semigroup over alphabet `α`, defined as a structure with two fields `head : α` and `tail : list α` (i.e. nonempty lists), with traversable instance and decidable equality. * `free_magma_assoc_quotient_equiv α`: isomorphism between `magma.assoc_quotient (free_magma α)` and `free_semigroup α`. * `free_magma.lift`: the universal property of the free magma, expressing its adjointness. -/ universes u v l /-- Free magma over a given alphabet. -/ @[derive decidable_eq] inductive free_magma (α : Type u) : Type u | of : α → free_magma | mul : free_magma → free_magma → free_magma /-- Free nonabelian additive magma over a given alphabet. -/ @[derive decidable_eq] inductive free_add_magma (α : Type u) : Type u | of : α → free_add_magma | add : free_add_magma → free_add_magma → free_add_magma attribute [to_additive] free_magma namespace free_magma variables {α : Type u} @[to_additive] instance [inhabited α] : inhabited (free_magma α) := ⟨of default⟩ @[to_additive] instance : has_mul (free_magma α) := ⟨free_magma.mul⟩ attribute [pattern] has_mul.mul @[simp, to_additive] theorem mul_eq (x y : free_magma α) : mul x y = x * y := rfl /-- Recursor for `free_magma` using `x * y` instead of `free_magma.mul x y`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_magma` using `x + y` instead of `free_add_magma.add x y`."] def rec_on_mul {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on x ih1 ih2 @[ext, to_additive] lemma hom_ext {β : Type v} [has_mul β] {f g : free_magma α →ₙ* β} (h : f ∘ of = g ∘ of) : f = g := fun_like.ext _ _ $ λ x, rec_on_mul x (congr_fun h) $ by { intros, simp only [map_mul, *] } end free_magma /-- Lifts a function `α → β` to a magma homomorphism `free_magma α → β` given a magma `β`. -/ def free_magma.lift_aux {α : Type u} {β : Type v} [has_mul β] (f : α → β) : free_magma α → β | (free_magma.of x) := f x | (x * y) := x.lift_aux * y.lift_aux /-- Lifts a function `α → β` to an additive magma homomorphism `free_add_magma α → β` given an additive magma `β`. -/ def free_add_magma.lift_aux {α : Type u} {β : Type v} [has_add β] (f : α → β) : free_add_magma α → β | (free_add_magma.of x) := f x | (x + y) := x.lift_aux + y.lift_aux attribute [to_additive free_add_magma.lift_aux] free_magma.lift_aux namespace free_magma section lift variables {α : Type u} {β : Type v} [has_mul β] (f : α → β) /-- The universal property of the free magma expressing its adjointness. -/ @[to_additive "The universal property of the free additive magma expressing its adjointness.", simps symm_apply] def lift : (α → β) ≃ (free_magma α →ₙ* β) := { to_fun := λ f, { to_fun := lift_aux f, map_mul' := λ x y, rfl, }, inv_fun := λ F, F ∘ of, left_inv := λ f, by { ext, refl }, right_inv := λ F, by { ext, refl } } @[simp, to_additive] lemma lift_of (x) : lift f (of x) = f x := rfl @[simp, to_additive] lemma lift_comp_of : lift f ∘ of = f := rfl @[simp, to_additive] lemma lift_comp_of' (f : free_magma α →ₙ* β) : lift (f ∘ of) = f := lift.apply_symm_apply f end lift section map variables {α : Type u} {β : Type v} (f : α → β) /-- The unique magma homomorphism `free_magma α →ₙ* free_magma β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive magma homomorphism `free_add_magma α → free_add_magma β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_magma α →ₙ* free_magma β := lift (of ∘ f) @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl end map section category variables {α β : Type u} @[to_additive] instance : monad free_magma := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor on `free_magma` using `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor on `free_add_magma` using `pure` instead of `of`."] protected def rec_on_pure {C : free_magma α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C x → C y → C (x * y)) : C x := free_magma.rec_on_mul x ih1 ih2 @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_magma β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_magma α) : (f <$> (x * y)) = (f <$> x * f <$> y) := rfl @[simp, to_additive] lemma pure_bind (f : α → free_magma β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_magma β) (x y : free_magma α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := rfl @[simp, to_additive] lemma pure_seq {α β : Type u} {f : α → β} {x : free_magma α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {α β : Type u} {f g : free_magma (α → β)} {x : free_magma α} : (f * g) <*> x = (f <*> x) * (g <*> x) := rfl @[to_additive] instance : is_lawful_monad free_magma.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, free_magma.rec_on_pure x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, free_magma.rec_on_pure x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } end category end free_magma /-- `free_magma` is traversable. -/ protected def free_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_magma α → m (free_magma β) | (free_magma.of x) := free_magma.of <$> F x | (x * y) := (*) <$> x.traverse <*> y.traverse /-- `free_add_magma` is traversable. -/ protected def free_add_magma.traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) : free_add_magma α → m (free_add_magma β) | (free_add_magma.of x) := free_add_magma.of <$> F x | (x + y) := (+) <$> x.traverse <*> y.traverse attribute [to_additive free_add_magma.traverse] free_magma.traverse namespace free_magma variables {α : Type u} section category variables {β : Type u} @[to_additive] instance : traversable free_magma := ⟨@free_magma.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) : traverse F (pure x : free_magma α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_magma β)) := rfl @[simp, to_additive] lemma traverse_mul (x y : free_magma α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_magma α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := rfl @[simp, to_additive] lemma traverse_eq (x) : free_magma.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_magma α) : ((*) <$> x <*> y : id (free_magma α)) = (x * y : free_magma α) := rfl @[to_additive] instance : is_lawful_traversable free_magma.{u} := { id_traverse := λ α x, free_magma.rec_on_pure x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, free_magma.rec_on_pure x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, free_magma.rec_on_pure x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_magma.rec_on_pure x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_magma.is_lawful_monad } end category end free_magma /-- Representation of an element of a free magma. -/ protected def free_magma.repr {α : Type u} [has_repr α] : free_magma α → string | (free_magma.of x) := repr x | (x * y) := "( " ++ x.repr ++ " * " ++ y.repr ++ " )" /-- Representation of an element of a free additive magma. -/ protected def free_add_magma.repr {α : Type u} [has_repr α] : free_add_magma α → string | (free_add_magma.of x) := repr x | (x + y) := "( " ++ x.repr ++ " + " ++ y.repr ++ " )" attribute [to_additive free_add_magma.repr] free_magma.repr @[to_additive] instance {α : Type u} [has_repr α] : has_repr (free_magma α) := ⟨free_magma.repr⟩ /-- Length of an element of a free magma. -/ @[simp] def free_magma.length {α : Type u} : free_magma α → ℕ | (free_magma.of x) := 1 | (x * y) := x.length + y.length /-- Length of an element of a free additive magma. -/ @[simp] def free_add_magma.length {α : Type u} : free_add_magma α → ℕ | (free_add_magma.of x) := 1 | (x + y) := x.length + y.length attribute [to_additive free_add_magma.length] free_magma.length /-- Associativity relations for an additive magma. -/ inductive add_magma.assoc_rel (α : Type u) [has_add α] : α → α → Prop | intro : ∀ x y z, add_magma.assoc_rel ((x + y) + z) (x + (y + z)) | left : ∀ w x y z, add_magma.assoc_rel (w + ((x + y) + z)) (w + (x + (y + z))) /-- Associativity relations for a magma. -/ @[to_additive add_magma.assoc_rel "Associativity relations for an additive magma."] inductive magma.assoc_rel (α : Type u) [has_mul α] : α → α → Prop | intro : ∀ x y z, magma.assoc_rel ((x * y) * z) (x * (y * z)) | left : ∀ w x y z, magma.assoc_rel (w * ((x * y) * z)) (w * (x * (y * z))) namespace magma /-- Semigroup quotient of a magma. -/ @[to_additive add_magma.free_add_semigroup "Additive semigroup quotient of an additive magma."] def assoc_quotient (α : Type u) [has_mul α] : Type u := quot $ assoc_rel α namespace assoc_quotient variables {α : Type u} [has_mul α] @[to_additive] lemma quot_mk_assoc (x y z : α) : quot.mk (assoc_rel α) (x * y * z) = quot.mk _ (x * (y * z)) := quot.sound (assoc_rel.intro _ _ _) @[to_additive] lemma quot_mk_assoc_left (x y z w : α) : quot.mk (assoc_rel α) (x * (y * z * w)) = quot.mk _ (x * (y * (z * w))) := quot.sound (assoc_rel.left _ _ _ _) @[to_additive] instance : semigroup (assoc_quotient α) := { mul := λ x y, begin refine quot.lift_on₂ x y (λ x y, quot.mk _ (x * y)) _ _, { rintro a b₁ b₂ (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only, { exact quot_mk_assoc_left _ _ _ _ }, { rw [← quot_mk_assoc, quot_mk_assoc_left, quot_mk_assoc] } }, { rintro a₁ a₂ b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only, { simp only [quot_mk_assoc, quot_mk_assoc_left] }, { rw [quot_mk_assoc, quot_mk_assoc, quot_mk_assoc_left, quot_mk_assoc_left, quot_mk_assoc_left, ← quot_mk_assoc c d, ← quot_mk_assoc c d, quot_mk_assoc_left] } } end, mul_assoc := λ x y z, quot.induction_on₃ x y z $ λ p q r, quot_mk_assoc p q r } /-- Embedding from magma to its free semigroup. -/ @[to_additive "Embedding from additive magma to its free additive semigroup."] def of : α →ₙ* assoc_quotient α := ⟨quot.mk _, λ x y, rfl⟩ @[to_additive] instance [inhabited α] : inhabited (assoc_quotient α) := ⟨of default⟩ @[elab_as_eliminator, to_additive] protected lemma induction_on {C : assoc_quotient α → Prop} (x : assoc_quotient α) (ih : ∀ x, C (of x)) : C x := quot.induction_on x ih section lift variables {β : Type v} [semigroup β] (f : α →ₙ* β) @[ext, to_additive] lemma hom_ext {f g : assoc_quotient α →ₙ* β} (h : f.comp of = g.comp of) : f = g := fun_like.ext _ _ $ λ x, assoc_quotient.induction_on x $ fun_like.congr_fun h /-- Lifts a magma homomorphism `α → β` to a semigroup homomorphism `magma.assoc_quotient α → β` given a semigroup `β`. -/ @[to_additive "Lifts an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.assoc_quotient α → β` given an additive semigroup `β`.", simps symm_apply] def lift : (α →ₙ* β) ≃ (assoc_quotient α →ₙ* β) := { to_fun := λ f, { to_fun := λ x, quot.lift_on x f $ by rintros a b (⟨c, d, e⟩ | ⟨c, d, e, f⟩); simp only [map_mul, mul_assoc], map_mul' := λ x y, quot.induction_on₂ x y (map_mul f) }, inv_fun := λ f, f.comp of, left_inv := λ f, fun_like.ext _ _ $ λ x, rfl, right_inv := λ f, hom_ext $ fun_like.ext _ _ $ λ x, rfl } @[simp, to_additive] lemma lift_of (x : α) : lift f (of x) = f x := rfl @[simp, to_additive] lemma lift_comp_of : (lift f).comp of = f := lift.symm_apply_apply f @[simp, to_additive] lemma lift_comp_of' (f : assoc_quotient α →ₙ* β) : lift (f.comp of) = f := lift.apply_symm_apply f end lift variables {β : Type v} [has_mul β] (f : α →ₙ* β) /-- From a magma homomorphism `α →ₙ* β` to a semigroup homomorphism `magma.assoc_quotient α →ₙ* magma.assoc_quotient β`. -/ @[to_additive "From an additive magma homomorphism `α → β` to an additive semigroup homomorphism `add_magma.assoc_quotient α → add_magma.assoc_quotient β`."] def map : assoc_quotient α →ₙ* assoc_quotient β := lift (of.comp f) @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl end assoc_quotient end magma /-- Free additive semigroup over a given alphabet. -/ @[ext] structure free_add_semigroup (α : Type u) := (head : α) (tail : list α) /-- Free semigroup over a given alphabet. -/ @[ext, to_additive] structure free_semigroup (α : Type u) := (head : α) (tail : list α) namespace free_semigroup variables {α : Type u} @[to_additive] instance : semigroup (free_semigroup α) := { mul := λ L1 L2, ⟨L1.1, L1.2 ++ L2.1 :: L2.2⟩, mul_assoc := λ L1 L2 L3, ext _ _ rfl $ list.append_assoc _ _ _ } @[simp, to_additive] lemma head_mul (x y : free_semigroup α) : (x * y).1 = x.1 := rfl @[simp, to_additive] lemma tail_mul (x y : free_semigroup α) : (x * y).2 = x.2 ++ (y.1 :: y.2) := rfl @[simp, to_additive] lemma mk_mul_mk (x y : α) (L1 L2 : list α) : mk x L1 * mk y L2 = mk x (L1 ++ y :: L2) := rfl /-- The embedding `α → free_semigroup α`. -/ @[to_additive "The embedding `α → free_add_semigroup α`.", simps] def of (x : α) : free_semigroup α := ⟨x, []⟩ /-- Length of an element of free semigroup. -/ @[to_additive "Length of an element of free additive semigroup"] def length (x : free_semigroup α) : ℕ := x.tail.length + 1 @[simp, to_additive] lemma length_mul (x y : free_semigroup α) : (x * y).length = x.length + y.length := by simp [length, ← add_assoc, add_right_comm] @[simp, to_additive] lemma length_of (x : α) : (of x).length = 1 := rfl @[to_additive] instance [inhabited α] : inhabited (free_semigroup α) := ⟨of default⟩ /-- Recursor for free semigroup using `of` and `*`. -/ @[elab_as_eliminator, to_additive "Recursor for free additive semigroup using `of` and `+`."] protected def rec_on_mul {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (of x)) (ih2 : ∀ x y, C (of x) → C y → C (of x * y)) : C x := free_semigroup.rec_on x $ λ f s, list.rec_on s ih1 (λ hd tl ih f, ih2 f ⟨hd, tl⟩ (ih1 f) (ih hd)) f @[ext, to_additive] lemma hom_ext {β : Type v} [has_mul β] {f g : free_semigroup α →ₙ* β} (h : f ∘ of = g ∘ of) : f = g := fun_like.ext _ _ $ λ x, free_semigroup.rec_on_mul x (congr_fun h) $ λ x y hx hy, by simp only [map_mul, *] section lift variables {β : Type v} [semigroup β] (f : α → β) /-- Lifts a function `α → β` to a semigroup homomorphism `free_semigroup α → β` given a semigroup `β`. -/ @[to_additive "Lifts a function `α → β` to an additive semigroup homomorphism `free_add_semigroup α → β` given an additive semigroup `β`.", simps symm_apply] def lift : (α → β) ≃ (free_semigroup α →ₙ* β) := { to_fun := λ f, { to_fun := λ x, x.2.foldl (λ a b, a * f b) (f x.1), map_mul' := λ x y, by simp only [head_mul, tail_mul, ← list.foldl_map f, list.foldl_append, list.foldl_cons, list.foldl_assoc] }, inv_fun := λ f, f ∘ of, left_inv := λ f, rfl, right_inv := λ f, hom_ext rfl } @[simp, to_additive] lemma lift_of (x : α) : lift f (of x) = f x := rfl @[simp, to_additive] lemma lift_comp_of : lift f ∘ of = f := rfl @[simp, to_additive] lemma lift_comp_of' (f : free_semigroup α →ₙ* β) : lift (f ∘ of) = f := hom_ext rfl @[to_additive] lemma lift_of_mul (x y) : lift f (of x * y) = f x * lift f y := by rw [map_mul, lift_of] end lift section map variables {β : Type v} (f : α → β) /-- The unique semigroup homomorphism that sends `of x` to `of (f x)`. -/ @[to_additive "The unique additive semigroup homomorphism that sends `of x` to `of (f x)`."] def map : free_semigroup α →ₙ* free_semigroup β := lift $ of ∘ f @[simp, to_additive] lemma map_of (x) : map f (of x) = of (f x) := rfl @[simp, to_additive] lemma length_map (x) : (map f x).length = x.length := free_semigroup.rec_on_mul x (λ x, rfl) $ λ x y hx hy, by simp only [map_mul, length_mul, *] end map section category variables {β : Type u} @[to_additive] instance : monad free_semigroup := { pure := λ _, of, bind := λ _ _ x f, lift f x } /-- Recursor that uses `pure` instead of `of`. -/ @[elab_as_eliminator, to_additive "Recursor that uses `pure` instead of `of`."] def rec_on_pure {C : free_semigroup α → Sort l} (x) (ih1 : ∀ x, C (pure x)) (ih2 : ∀ x y, C (pure x) → C y → C (pure x * y)) : C x := free_semigroup.rec_on_mul x ih1 ih2 @[simp, to_additive] lemma map_pure (f : α → β) (x) : (f <$> pure x : free_semigroup β) = pure (f x) := rfl @[simp, to_additive] lemma map_mul' (f : α → β) (x y : free_semigroup α) : (f <$> (x * y)) = (f <$> x * f <$> y) := map_mul (map f) _ _ @[simp, to_additive] lemma pure_bind (f : α → free_semigroup β) (x) : (pure x >>= f) = f x := rfl @[simp, to_additive] lemma mul_bind (f : α → free_semigroup β) (x y : free_semigroup α) : (x * y >>= f) = ((x >>= f) * (y >>= f)) := map_mul (lift f) _ _ @[simp, to_additive] lemma pure_seq {f : α → β} {x : free_semigroup α} : pure f <*> x = f <$> x := rfl @[simp, to_additive] lemma mul_seq {f g : free_semigroup (α → β)} {x : free_semigroup α} : (f * g) <*> x = (f <*> x) * (g <*> x) := mul_bind _ _ _ @[to_additive] instance : is_lawful_monad free_semigroup.{u} := { pure_bind := λ _ _ _ _, rfl, bind_assoc := λ α β γ x f g, rec_on_pure x (λ x, rfl) (λ x y ih1 ih2, by rw [mul_bind, mul_bind, mul_bind, ih1, ih2]), id_map := λ α x, rec_on_pure x (λ _, rfl) (λ x y ih1 ih2, by rw [map_mul', ih1, ih2]) } /-- `free_semigroup` is traversable. -/ @[to_additive "`free_add_semigroup` is traversable."] protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u} (F : α → m β) (x : free_semigroup α) : m (free_semigroup β) := rec_on_pure x (λ x, pure <$> F x) (λ x y ihx ihy, (*) <$> ihx <*> ihy) @[to_additive] instance : traversable free_semigroup := ⟨@free_semigroup.traverse⟩ variables {m : Type u → Type u} [applicative m] (F : α → m β) @[simp, to_additive] lemma traverse_pure (x) :traverse F (pure x : free_semigroup α) = pure <$> F x := rfl @[simp, to_additive] lemma traverse_pure' : traverse F ∘ pure = λ x, (pure <$> F x : m (free_semigroup β)) := rfl section variables [is_lawful_applicative m] @[simp, to_additive] lemma traverse_mul (x y : free_semigroup α) : traverse F (x * y) = (*) <$> traverse F x <*> traverse F y := let ⟨x, L1⟩ := x, ⟨y, L2⟩ := y in list.rec_on L1 (λ x, rfl) (λ hd tl ih x, show (*) <$> pure <$> F x <*> traverse F ((mk hd tl) * (mk y L2)) = (*) <$> ((*) <$> pure <$> F x <*> traverse F (mk hd tl)) <*> traverse F (mk y L2), by rw ih; simp only [(∘), (mul_assoc _ _ _).symm] with functor_norm) x @[simp, to_additive] lemma traverse_mul' : function.comp (traverse F) ∘ @has_mul.mul (free_semigroup α) _ = λ x y, (*) <$> traverse F x <*> traverse F y := funext $ λ x, funext $ λ y, traverse_mul F x y end @[simp, to_additive] lemma traverse_eq (x) : free_semigroup.traverse F x = traverse F x := rfl @[simp, to_additive] lemma mul_map_seq (x y : free_semigroup α) : ((*) <$> x <*> y : id (free_semigroup α)) = (x * y : free_semigroup α) := rfl @[to_additive] instance : is_lawful_traversable free_semigroup.{u} := { id_traverse := λ α x, free_semigroup.rec_on_mul x (λ x, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, mul_map_seq]), comp_traverse := λ F G hf1 hg1 hf2 hg2 α β γ f g x, rec_on_pure x (λ x, by resetI; simp only [traverse_pure, traverse_pure'] with functor_norm) (λ x y ih1 ih2, by resetI; rw [traverse_mul, ih1, ih2, traverse_mul]; simp only [traverse_mul'] with functor_norm), naturality := λ F G hf1 hg1 hf2 hg2 η α β f x, rec_on_pure x (λ x, by simp only [traverse_pure] with functor_norm) (λ x y ih1 ih2, by resetI; simp only [traverse_mul] with functor_norm; rw [ih1, ih2]), traverse_eq_map_id := λ α β f x, free_semigroup.rec_on_mul x (λ _, rfl) (λ x y ih1 ih2, by rw [traverse_mul, ih1, ih2, map_mul', mul_map_seq]; refl), .. free_semigroup.is_lawful_monad } end category @[to_additive] instance [decidable_eq α] : decidable_eq (free_semigroup α) := λ x y, decidable_of_iff' _ (ext_iff _ _) end free_semigroup namespace free_magma variables {α : Type u} {β : Type v} /-- The canonical multiplicative morphism from `free_magma α` to `free_semigroup α`. -/ @[to_additive "The canonical additive morphism from `free_add_magma α` to `free_add_semigroup α`."] def to_free_semigroup : free_magma α →ₙ* free_semigroup α := free_magma.lift free_semigroup.of @[simp, to_additive] lemma to_free_semigroup_of (x : α) : to_free_semigroup (of x) = free_semigroup.of x := rfl @[simp, to_additive] lemma to_free_semigroup_comp_of : @to_free_semigroup α ∘ of = free_semigroup.of := rfl @[to_additive] lemma to_free_semigroup_comp_map (f : α → β) : to_free_semigroup.comp (map f) = (free_semigroup.map f).comp to_free_semigroup := by { ext1, refl } @[to_additive] lemma to_free_semigroup_map (f : α → β) (x : free_magma α) : (map f x).to_free_semigroup = free_semigroup.map f x.to_free_semigroup := fun_like.congr_fun (to_free_semigroup_comp_map f) x @[simp, to_additive] lemma length_to_free_semigroup (x : free_magma α) : x.to_free_semigroup.length = x.length := free_magma.rec_on_mul x (λ x, rfl) $ λ x y hx hy, by rw [map_mul, free_semigroup.length_mul, length, hx, hy] end free_magma /-- Isomorphism between `magma.assoc_quotient (free_magma α)` and `free_semigroup α`. -/ @[to_additive "Isomorphism between `add_magma.assoc_quotient (free_add_magma α)` and `free_add_semigroup α`."] def free_magma_assoc_quotient_equiv (α : Type u) : magma.assoc_quotient (free_magma α) ≃* free_semigroup α := (magma.assoc_quotient.lift free_magma.to_free_semigroup).to_mul_equiv (free_semigroup.lift (magma.assoc_quotient.of ∘ free_magma.of)) (by { ext, refl }) (by { ext1, refl })
363862ecf38a1899d1d5b7ae0758e082a645b24c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/category_theory/comma.lean
8b62e341d24bedd9a9f5a55b7c7959e3818043ff
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
12,913
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.isomorphism import category_theory.equivalence import category_theory.punit 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] include 𝒜 ℬ 𝒯 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) variables {L : A ⥤ T} {R : B ⥤ T} @[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) restate_axiom comma_morphism.w' attribute [simp] 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, w' := begin rw [functor.map_comp, category.assoc, g.w, ←category.assoc, f.w, functor.map_comp, category.assoc], end }} namespace comma section variables {X Y Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} @[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) def fst : comma L R ⥤ A := { obj := λ X, X.left, map := λ _ _ f, f.left } def snd : comma L R ⥤ B := { obj := λ X, X.right, map := λ _ _ f, f.right } @[simp] lemma fst_obj {X : comma L R} : (fst L R).obj X = X.left := rfl @[simp] lemma snd_obj {X : comma L R} : (snd L R).obj X = X.right := rfl @[simp] lemma fst_map {X Y : comma L R} {f : X ⟶ Y} : (fst L R).map f = f.left := rfl @[simp] lemma snd_map {X Y : comma L R} {f : X ⟶ Y} : (snd L R).map f = f.right := rfl 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} 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, w' := by tidy; rw [←category.assoc, l.naturality f.left, category.assoc]; tidy } } section variables {X Y : comma L₂ R} {f : X ⟶ Y} {l : L₁ ⟶ L₂} @[simp] lemma map_left_obj_left : ((map_left R l).obj X).left = X.left := rfl @[simp] lemma map_left_obj_right : ((map_left R l).obj X).right = X.right := rfl @[simp] lemma map_left_obj_hom : ((map_left R l).obj X).hom = l.app X.left ≫ X.hom := rfl @[simp] lemma map_left_map_left : ((map_left R l).map f).left = f.left := rfl @[simp] lemma map_left_map_right : ((map_left R l).map f).right = f.right := rfl end def map_left_id : map_left R (𝟙 L) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_left_id_hom_app_left : (((map_left_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_hom_app_right : (((map_left_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_id_inv_app_left : (((map_left_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_id_inv_app_right : (((map_left_id L R).inv).app X).right = 𝟙 (X.right) := rfl end 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 := 𝟙 _ } } } section variables {X : comma L₃ R} {l : L₁ ⟶ L₂} {l' : L₂ ⟶ L₃} @[simp] lemma map_left_comp_hom_app_left : (((map_left_comp R l l').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_hom_app_right : (((map_left_comp R l l').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_left_comp_inv_app_left : (((map_left_comp R l l').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_left_comp_inv_app_right : (((map_left_comp R l l').inv).app X).right = 𝟙 (X.right) := rfl end 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, w' := by tidy; rw [←r.naturality f.right, ←category.assoc]; tidy } } section variables {X Y : comma L R₁} {f : X ⟶ Y} {r : R₁ ⟶ R₂} @[simp] lemma map_right_obj_left : ((map_right L r).obj X).left = X.left := rfl @[simp] lemma map_right_obj_right : ((map_right L r).obj X).right = X.right := rfl @[simp] lemma map_right_obj_hom : ((map_right L r).obj X).hom = X.hom ≫ r.app X.right := rfl @[simp] lemma map_right_map_left : ((map_right L r).map f).left = f.left := rfl @[simp] lemma map_right_map_right : ((map_right L r).map f).right = f.right := rfl end def map_right_id : map_right L (𝟙 R) ≅ 𝟭 _ := { hom := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } }, inv := { app := λ X, { left := 𝟙 _, right := 𝟙 _ } } } section variables {X : comma L R} @[simp] lemma map_right_id_hom_app_left : (((map_right_id L R).hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_hom_app_right : (((map_right_id L R).hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_id_inv_app_left : (((map_right_id L R).inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_id_inv_app_right : (((map_right_id L R).inv).app X).right = 𝟙 (X.right) := rfl end 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 := 𝟙 _ } } } section variables {X : comma L R₁} {r : R₁ ⟶ R₂} {r' : R₂ ⟶ R₃} @[simp] lemma map_right_comp_hom_app_left : (((map_right_comp L r r').hom).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_hom_app_right : (((map_right_comp L r r').hom).app X).right = 𝟙 (X.right) := rfl @[simp] lemma map_right_comp_inv_app_left : (((map_right_comp L r r').inv).app X).left = 𝟙 (X.left) := rfl @[simp] lemma map_right_comp_inv_app_right : (((map_right_comp L r r').inv).app X).right = 𝟙 (X.right) := rfl end end end comma omit 𝒜 ℬ @[derive category] def over (X : T) := comma.{v₃ 0 v₃} (𝟭 T) ((functor.const punit).obj X) 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 = 𝟙 punit.star := by tidy @[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 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 def hom_mk {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom . obviously) : U ⟶ V := { left := f } @[simp] lemma hom_mk_left {U V : over X} (f : U.left ⟶ V.left) (w : f ≫ V.hom = U.hom) : (hom_mk f).left = f := rfl 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 def map {Y : T} (f : X ⟶ Y) : over X ⥤ over Y := comma.map_right _ $ (functor.const punit).map 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 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, over.mk (over.hom_mk g.hom (by simp) : over.mk (g.hom ≫ f.hom) ⟶ f), map := λ g h α, over.hom_mk (over.hom_mk α.left (over.w_assoc α f.hom)) (over.over_morphism.ext (over.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, ⟨over.hom_mk (over.hom_mk (𝟙 g.left.left)) (by apply_auto_param), over.hom_mk (over.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, ⟨over.hom_mk (𝟙 g.left) (by apply_auto_param), over.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] include 𝒟 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 @[derive category] def under (X : T) := comma.{0 v₃ v₃} ((functor.const punit).obj X) (𝟭 T) 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 under_morphism_left {U V : under X} (f : U ⟶ V) : f.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 def mk {X Y : T} (f : X ⟶ Y) : under X := { right := Y, hom := f } @[simp] lemma mk_right {X Y : T} (f : X ⟶ Y) : (mk f).right = Y := rfl @[simp] lemma mk_hom {X Y : T} (f : X ⟶ Y) : (mk f).hom = f := rfl def hom_mk {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom . obviously) : U ⟶ V := { right := f } @[simp] lemma hom_mk_right {U V : under X} (f : U.right ⟶ V.right) (w : U.hom ≫ f = V.hom) : (hom_mk f).right = f := rfl 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 def map {Y : T} (f : X ⟶ Y) : under Y ⥤ under X := comma.map_left _ $ (functor.const punit).map 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] include 𝒟 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 end category_theory
9b2616bfdc6da3404f4c4b9ff9139055516a89ee
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/init/data/ordering.lean
5668e5043e208d85593761d0ced9987053a7449a
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,850
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.to_string init.data.prod init.data.sum.basic inductive ordering | lt | eq | gt open ordering instance : has_to_string ordering := has_to_string.mk (λ s, match s with | ordering.lt := "lt" | ordering.eq := "eq" | ordering.gt := "gt" end) class has_ordering (α : Type) := (cmp : α → α → ordering) def nat.cmp (a b : nat) : ordering := if a < b then ordering.lt else if a = b then ordering.eq else ordering.gt instance : has_ordering nat := ⟨nat.cmp⟩ section open prod variables {α β : Type} [has_ordering α] [has_ordering β] def prod.cmp : α × β → α × β → ordering | (a₁, b₁) (a₂, b₂) := match (has_ordering.cmp a₁ a₂) with | ordering.lt := lt | ordering.eq := has_ordering.cmp b₁ b₂ | ordering.gt := gt end instance {α β : Type} [has_ordering α] [has_ordering β] : has_ordering (α × β) := ⟨prod.cmp⟩ end section open sum variables {α β : Type} [has_ordering α] [has_ordering β] def sum.cmp : α ⊕ β → α ⊕ β → ordering | (inl a₁) (inl a₂) := has_ordering.cmp a₁ a₂ | (inr b₁) (inr b₂) := has_ordering.cmp b₁ b₂ | (inl a₁) (inr b₂) := lt | (inr b₁) (inl a₂) := gt instance {α β : Type} [has_ordering α] [has_ordering β] : has_ordering (α ⊕ β) := ⟨sum.cmp⟩ end section open option variables {α : Type} [has_ordering α] def option.cmp : option α → option α → ordering | (some a₁) (some a₂) := has_ordering.cmp a₁ a₂ | (some a₁) none := gt | none (some a₂) := lt | none none := eq instance {α : Type} [has_ordering α] : has_ordering (option α) := ⟨option.cmp⟩ end
330c5ddc71540b91a0460011073a34fee5dac523
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/multiplicity.lean
64b509ce77a6048f321a78bd0c07877b28fda4f9
[ "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
20,987
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, Chris Hughes -/ import algebra.associated import algebra.big_operators.basic import ring_theory.valuation.basic import data.nat.factorization /-! # Multiplicity of a divisor For a commutative monoid, this file introduces the notion of multiplicity of a divisor and proves several basic results on it. ## Main definitions * `multiplicity a b`: for two elements `a` and `b` of a commutative monoid returns the largest number `n` such that `a ^ n ∣ b` or infinity, written `⊤`, if `a ^ n ∣ b` for all natural numbers `n`. * `multiplicity.finite a b`: a predicate denoting that the multiplicity of `a` in `b` is finite. -/ variables {α : Type*} open nat part open_locale big_operators /-- `multiplicity a b` returns the largest natural number `n` such that `a ^ n ∣ b`, as an `enat` or natural with infinity. If `∀ n, a ^ n ∣ b`, then it returns `⊤`-/ def multiplicity [comm_monoid α] [decidable_rel ((∣) : α → α → Prop)] (a b : α) : enat := enat.find $ λ n, ¬a ^ (n + 1) ∣ b namespace multiplicity section comm_monoid variables [comm_monoid α] /-- `multiplicity.finite a b` indicates that the multiplicity of `a` in `b` is finite. -/ @[reducible] def finite (a b : α) : Prop := ∃ n : ℕ, ¬a ^ (n + 1) ∣ b lemma finite_iff_dom [decidable_rel ((∣) : α → α → Prop)] {a b : α} : finite a b ↔ (multiplicity a b).dom := iff.rfl lemma finite_def {a b : α} : finite a b ↔ ∃ n : ℕ, ¬a ^ (n + 1) ∣ b := iff.rfl @[norm_cast] theorem int.coe_nat_multiplicity (a b : ℕ) : multiplicity (a : ℤ) (b : ℤ) = multiplicity a b := begin apply part.ext', { repeat { rw [← finite_iff_dom, finite_def] }, norm_cast }, { intros h1 h2, apply _root_.le_antisymm; { apply nat.find_mono, norm_cast, simp } } end lemma not_finite_iff_forall {a b : α} : (¬ finite a b) ↔ ∀ n : ℕ, a ^ n ∣ b := ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _ }) (by simpa [finite, not_not] using h), by simp [finite, multiplicity, not_not]; tauto⟩ lemma not_unit_of_finite {a b : α} (h : finite a b) : ¬is_unit a := let ⟨n, hn⟩ := h in mt (is_unit_iff_forall_dvd.1 ∘ is_unit.pow (n + 1)) $ λ h, hn (h b) lemma finite_of_finite_mul_left {a b c : α} : finite a (b * c) → finite a c := λ ⟨n, hn⟩, ⟨n, λ h, hn (h.trans (by simp [mul_pow]))⟩ lemma finite_of_finite_mul_right {a b c : α} : finite a (b * c) → finite a b := by rw mul_comm; exact finite_of_finite_mul_left variable [decidable_rel ((∣) : α → α → Prop)] lemma pow_dvd_of_le_multiplicity {a b : α} {k : ℕ} : (k : enat) ≤ multiplicity a b → a ^ k ∣ b := by { rw ← enat.some_eq_coe, exact nat.cases_on k (λ _, by { rw pow_zero, exact one_dvd _ }) (λ k ⟨h₁, h₂⟩, by_contradiction (λ hk, (nat.find_min _ (lt_of_succ_le (h₂ ⟨k, hk⟩)) hk))) } lemma pow_multiplicity_dvd {a b : α} (h : finite a b) : a ^ get (multiplicity a b) h ∣ b := pow_dvd_of_le_multiplicity (by rw enat.coe_get) lemma is_greatest {a b : α} {m : ℕ} (hm : multiplicity a b < m) : ¬a ^ m ∣ b := λ h, by rw [enat.lt_coe_iff] at hm; exact nat.find_spec hm.fst ((pow_dvd_pow _ hm.snd).trans h) lemma is_greatest' {a b : α} {m : ℕ} (h : finite a b) (hm : get (multiplicity a b) h < m) : ¬a ^ m ∣ b := is_greatest (by rwa [← enat.coe_lt_coe, enat.coe_get] at hm) lemma pos_of_dvd {a b : α} (hfin : finite a b) (hdiv : a ∣ b) : 0 < (multiplicity a b).get hfin := begin refine zero_lt_iff.2 (λ h, _), simpa [hdiv] using (is_greatest' hfin (lt_one_iff.mpr h)), end lemma unique {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬a ^ (k + 1) ∣ b) : (k : enat) = multiplicity a b := le_antisymm (le_of_not_gt (λ hk', is_greatest hk' hk)) $ have finite a b, from ⟨k, hsucc⟩, by { rw [enat.le_coe_iff], exact ⟨this, nat.find_min' _ hsucc⟩ } lemma unique' {a b : α} {k : ℕ} (hk : a ^ k ∣ b) (hsucc : ¬ a ^ (k + 1) ∣ b) : k = get (multiplicity a b) ⟨k, hsucc⟩ := by rw [← enat.coe_inj, enat.coe_get, unique hk hsucc] lemma le_multiplicity_of_pow_dvd {a b : α} {k : ℕ} (hk : a ^ k ∣ b) : (k : enat) ≤ multiplicity a b := le_of_not_gt $ λ hk', is_greatest hk' hk lemma pow_dvd_iff_le_multiplicity {a b : α} {k : ℕ} : a ^ k ∣ b ↔ (k : enat) ≤ multiplicity a b := ⟨le_multiplicity_of_pow_dvd, pow_dvd_of_le_multiplicity⟩ lemma multiplicity_lt_iff_neg_dvd {a b : α} {k : ℕ} : multiplicity a b < (k : enat) ↔ ¬ a ^ k ∣ b := by { rw [pow_dvd_iff_le_multiplicity, not_le] } lemma eq_coe_iff {a b : α} {n : ℕ} : multiplicity a b = (n : enat) ↔ a ^ n ∣ b ∧ ¬a ^ (n + 1) ∣ b := begin rw [← enat.some_eq_coe], exact ⟨λ h, let ⟨h₁, h₂⟩ := eq_some_iff.1 h in h₂ ▸ ⟨pow_multiplicity_dvd _, is_greatest (by { rw [enat.lt_coe_iff], exact ⟨h₁, lt_succ_self _⟩ })⟩, λ h, eq_some_iff.2 ⟨⟨n, h.2⟩, eq.symm $ unique' h.1 h.2⟩⟩ end lemma eq_top_iff {a b : α} : multiplicity a b = ⊤ ↔ ∀ n : ℕ, a ^ n ∣ b := (enat.find_eq_top_iff _).trans $ by { simp only [not_not], exact ⟨λ h n, nat.cases_on n (by { rw pow_zero, exact one_dvd _}) (λ n, h _), λ h n, h _⟩ } @[simp] lemma is_unit_left {a : α} (b : α) (ha : is_unit a) : multiplicity a b = ⊤ := eq_top_iff.2 (λ _, is_unit_iff_forall_dvd.1 (ha.pow _) _) lemma is_unit_right {a b : α} (ha : ¬is_unit a) (hb : is_unit b) : multiplicity a b = 0 := eq_coe_iff.2 ⟨show a ^ 0 ∣ b, by simp only [pow_zero, one_dvd], by { rw pow_one, exact λ h, mt (is_unit_of_dvd_unit h) ha hb }⟩ @[simp] lemma one_left (b : α) : multiplicity 1 b = ⊤ := is_unit_left b is_unit_one lemma one_right {a : α} (ha : ¬is_unit a) : multiplicity a 1 = 0 := is_unit_right ha is_unit_one @[simp] lemma get_one_right {a : α} (ha : finite a 1) : get (multiplicity a 1) ha = 0 := begin rw [enat.get_eq_iff_eq_coe, eq_coe_iff, pow_zero], simpa [is_unit_iff_dvd_one.symm] using not_unit_of_finite ha, end @[simp] lemma unit_left (a : α) (u : αˣ) : multiplicity (u : α) a = ⊤ := is_unit_left a u.is_unit lemma unit_right {a : α} (ha : ¬is_unit a) (u : αˣ) : multiplicity a u = 0 := is_unit_right ha u.is_unit lemma multiplicity_eq_zero_of_not_dvd {a b : α} (ha : ¬a ∣ b) : multiplicity a b = 0 := by { rw [← nat.cast_zero, eq_coe_iff], simpa } lemma eq_top_iff_not_finite {a b : α} : multiplicity a b = ⊤ ↔ ¬ finite a b := part.eq_none_iff' lemma ne_top_iff_finite {a b : α} : multiplicity a b ≠ ⊤ ↔ finite a b := by rw [ne.def, eq_top_iff_not_finite, not_not] lemma lt_top_iff_finite {a b : α} : multiplicity a b < ⊤ ↔ finite a b := by rw [lt_top_iff_ne_top, ne_top_iff_finite] lemma exists_eq_pow_mul_and_not_dvd {a b : α} (hfin : finite a b) : ∃ (c : α), b = a ^ ((multiplicity a b).get hfin) * c ∧ ¬ a ∣ c := begin obtain ⟨c, hc⟩ := multiplicity.pow_multiplicity_dvd hfin, refine ⟨c, hc, _⟩, rintro ⟨k, hk⟩, rw [hk, ← mul_assoc, ← pow_succ'] at hc, have h₁ : a ^ ((multiplicity a b).get hfin + 1) ∣ b := ⟨k, hc⟩, exact (multiplicity.eq_coe_iff.1 (by simp)).2 h₁, end open_locale classical lemma multiplicity_le_multiplicity_iff {a b c d : α} : multiplicity a b ≤ multiplicity c d ↔ (∀ n : ℕ, a ^ n ∣ b → c ^ n ∣ d) := ⟨λ h n hab, (pow_dvd_of_le_multiplicity (le_trans (le_multiplicity_of_pow_dvd hab) h)), λ h, if hab : finite a b then by rw [← enat.coe_get (finite_iff_dom.1 hab)]; exact le_multiplicity_of_pow_dvd (h _ (pow_multiplicity_dvd _)) else have ∀ n : ℕ, c ^ n ∣ d, from λ n, h n (not_finite_iff_forall.1 hab _), by rw [eq_top_iff_not_finite.2 hab, eq_top_iff_not_finite.2 (not_finite_iff_forall.2 this)]⟩ lemma multiplicity_le_multiplicity_of_dvd_left {a b c : α} (hdvd : a ∣ b) : multiplicity b c ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n h, (pow_dvd_pow_of_dvd hdvd n).trans h lemma eq_of_associated_left {a b c : α} (h : associated a b) : multiplicity b c = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_left h.dvd) (multiplicity_le_multiplicity_of_dvd_left h.symm.dvd) lemma multiplicity_le_multiplicity_of_dvd_right {a b c : α} (h : b ∣ c) : multiplicity a b ≤ multiplicity a c := multiplicity_le_multiplicity_iff.2 $ λ n hb, hb.trans h lemma eq_of_associated_right {a b c : α} (h : associated b c) : multiplicity a b = multiplicity a c := le_antisymm (multiplicity_le_multiplicity_of_dvd_right h.dvd) (multiplicity_le_multiplicity_of_dvd_right h.symm.dvd) lemma dvd_of_multiplicity_pos {a b : α} (h : (0 : enat) < multiplicity a b) : a ∣ b := begin rw ← pow_one a, apply pow_dvd_of_le_multiplicity, simpa only [nat.cast_one, enat.pos_iff_one_le] using h end lemma dvd_iff_multiplicity_pos {a b : α} : (0 : enat) < multiplicity a b ↔ a ∣ b := ⟨dvd_of_multiplicity_pos, λ hdvd, lt_of_le_of_ne (zero_le _) (λ heq, is_greatest (show multiplicity a b < ↑1, by simpa only [heq, nat.cast_zero] using enat.coe_lt_coe.mpr zero_lt_one) (by rwa pow_one a))⟩ lemma finite_nat_iff {a b : ℕ} : finite a b ↔ (a ≠ 1 ∧ 0 < b) := begin rw [← not_iff_not, not_finite_iff_forall, not_and_distrib, ne.def, not_not, not_lt, nat.le_zero_iff], exact ⟨λ h, or_iff_not_imp_right.2 (λ hb, have ha : a ≠ 0, from λ ha, by simpa [ha] using h 1, by_contradiction (λ ha1 : a ≠ 1, have ha_gt_one : 1 < a, from lt_of_not_ge (λ ha', by { clear h, revert ha ha1, dec_trivial! }), not_lt_of_ge (le_of_dvd (nat.pos_of_ne_zero hb) (h b)) (lt_pow_self ha_gt_one b))), λ h, by cases h; simp *⟩ end alias dvd_iff_multiplicity_pos ↔ _ has_dvd.dvd.multiplicity_pos end comm_monoid section comm_monoid_with_zero variable [comm_monoid_with_zero α] lemma ne_zero_of_finite {a b : α} (h : finite a b) : b ≠ 0 := let ⟨n, hn⟩ := h in λ hb, by simpa [hb] using hn variable [decidable_rel ((∣) : α → α → Prop)] @[simp] protected lemma zero (a : α) : multiplicity a 0 = ⊤ := part.eq_none_iff.2 (λ n ⟨⟨k, hk⟩, _⟩, hk (dvd_zero _)) @[simp] lemma multiplicity_zero_eq_zero_of_ne_zero (a : α) (ha : a ≠ 0) : multiplicity 0 a = 0 := begin apply multiplicity.multiplicity_eq_zero_of_not_dvd, rwa zero_dvd_iff, end end comm_monoid_with_zero section comm_semiring variables [comm_semiring α] [decidable_rel ((∣) : α → α → Prop)] lemma min_le_multiplicity_add {p a b : α} : min (multiplicity p a) (multiplicity p b) ≤ multiplicity p (a + b) := (le_total (multiplicity p a) (multiplicity p b)).elim (λ h, by rw [min_eq_left h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add hn (multiplicity_le_multiplicity_iff.1 h n hn)) (λ h, by rw [min_eq_right h, multiplicity_le_multiplicity_iff]; exact λ n hn, dvd_add (multiplicity_le_multiplicity_iff.1 h n hn) hn) end comm_semiring section comm_ring variables [comm_ring α] [decidable_rel ((∣) : α → α → Prop)] open_locale classical @[simp] protected lemma neg (a b : α) : multiplicity a (-b) = multiplicity a b := part.ext' (by simp only [multiplicity, enat.find, dvd_neg]) (λ h₁ h₂, enat.coe_inj.1 (by rw [enat.coe_get]; exact eq.symm (unique ((dvd_neg _ _).2 (pow_multiplicity_dvd _)) (mt (dvd_neg _ _).1 (is_greatest' _ (lt_succ_self _)))))) theorem int.nat_abs (a : ℕ) (b : ℤ) : multiplicity a b.nat_abs = multiplicity (a : ℤ) b := begin cases int.nat_abs_eq b with h h; conv_rhs { rw h }, { rw [int.coe_nat_multiplicity], }, { rw [multiplicity.neg, int.coe_nat_multiplicity], }, end lemma multiplicity_add_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a + b) = multiplicity p b := begin apply le_antisymm, { apply enat.le_of_lt_add_one, cases enat.ne_top_iff.mp (enat.ne_top_of_lt h) with k hk, rw [hk], rw_mod_cast [multiplicity_lt_iff_neg_dvd], intro h_dvd, rw [← dvd_add_iff_right] at h_dvd, apply multiplicity.is_greatest _ h_dvd, rw [hk], apply_mod_cast nat.lt_succ_self, rw [pow_dvd_iff_le_multiplicity, nat.cast_add, ← hk, nat.cast_one], exact enat.add_one_le_of_lt h }, { convert min_le_multiplicity_add, rw [min_eq_right (le_of_lt h)] } end lemma multiplicity_sub_of_gt {p a b : α} (h : multiplicity p b < multiplicity p a) : multiplicity p (a - b) = multiplicity p b := by { rw [sub_eq_add_neg, multiplicity_add_of_gt]; rwa [multiplicity.neg] } lemma multiplicity_add_eq_min {p a b : α} (h : multiplicity p a ≠ multiplicity p b) : multiplicity p (a + b) = min (multiplicity p a) (multiplicity p b) := begin rcases lt_trichotomy (multiplicity p a) (multiplicity p b) with hab|hab|hab, { rw [add_comm, multiplicity_add_of_gt hab, min_eq_left], exact le_of_lt hab }, { contradiction }, { rw [multiplicity_add_of_gt hab, min_eq_right], exact le_of_lt hab}, end end comm_ring section cancel_comm_monoid_with_zero variables [cancel_comm_monoid_with_zero α] lemma finite_mul_aux {p : α} (hp : prime p) : ∀ {n m : ℕ} {a b : α}, ¬p ^ (n + 1) ∣ a → ¬p ^ (m + 1) ∣ b → ¬p ^ (n + m + 1) ∣ a * b | n m := λ a b ha hb ⟨s, hs⟩, have p ∣ a * b, from ⟨p ^ (n + m) * s, by simp [hs, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩, (hp.2.2 a b this).elim (λ ⟨x, hx⟩, have hn0 : 0 < n, from nat.pos_of_ne_zero (λ hn0, by clear _fun_match _fun_match; simpa [hx, hn0] using ha), have wf : (n - 1) < n, from tsub_lt_self hn0 dec_trivial, have hpx : ¬ p ^ (n - 1 + 1) ∣ x, from λ ⟨y, hy⟩, ha (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [tsub_add_cancel_of_le (succ_le_of_lt hn0)] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), have 1 ≤ n + m, from le_trans hn0 (nat.le_add_right n m), finite_mul_aux hpx hb ⟨s, mul_right_cancel₀ hp.1 begin rw [tsub_add_eq_add_tsub (succ_le_of_lt hn0), tsub_add_cancel_of_le this], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) (λ ⟨x, hx⟩, have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, by clear _fun_match _fun_match; simpa [hx, hm0] using hb), have wf : (m - 1) < m, from tsub_lt_self hm0 dec_trivial, have hpx : ¬ p ^ (m - 1 + 1) ∣ x, from λ ⟨y, hy⟩, hb (hx.symm ▸ ⟨y, mul_right_cancel₀ hp.1 $ by rw [tsub_add_cancel_of_le (succ_le_of_lt hm0)] at hy; simp [hy, pow_add, mul_comm, mul_assoc, mul_left_comm]⟩), finite_mul_aux ha hpx ⟨s, mul_right_cancel₀ hp.1 begin rw [add_assoc, tsub_add_cancel_of_le (succ_le_of_lt hm0)], clear _fun_match _fun_match finite_mul_aux, simp [*, mul_comm, mul_assoc, mul_left_comm, pow_add] at * end⟩) lemma finite_mul {p a b : α} (hp : prime p) : finite p a → finite p b → finite p (a * b) := λ ⟨n, hn⟩ ⟨m, hm⟩, ⟨n + m, finite_mul_aux hp hn hm⟩ lemma finite_mul_iff {p a b : α} (hp : prime p) : finite p (a * b) ↔ finite p a ∧ finite p b := ⟨λ h, ⟨finite_of_finite_mul_right h, finite_of_finite_mul_left h⟩, λ h, finite_mul hp h.1 h.2⟩ lemma finite_pow {p a : α} (hp : prime p) : Π {k : ℕ} (ha : finite p a), finite p (a ^ k) | 0 ha := ⟨0, by simp [mt is_unit_iff_dvd_one.2 hp.2.1]⟩ | (k+1) ha := by rw [pow_succ]; exact finite_mul hp ha (finite_pow ha) variable [decidable_rel ((∣) : α → α → Prop)] @[simp] lemma multiplicity_self {a : α} (ha : ¬is_unit a) (ha0 : a ≠ 0) : multiplicity a a = 1 := by { rw ← nat.cast_one, exact eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, ha (is_unit_iff_dvd_one.2 ⟨b, mul_left_cancel₀ ha0 $ by { clear _fun_match, simpa [pow_succ, mul_assoc] using hb }⟩)⟩ } @[simp] lemma get_multiplicity_self {a : α} (ha : finite a a) : get (multiplicity a a) ha = 1 := enat.get_eq_iff_eq_coe.2 (eq_coe_iff.2 ⟨by simp, λ ⟨b, hb⟩, by rw [← mul_one a, pow_add, pow_one, mul_assoc, mul_assoc, mul_right_inj' (ne_zero_of_finite ha)] at hb; exact mt is_unit_iff_dvd_one.2 (not_unit_of_finite ha) ⟨b, by clear _fun_match; simp * at *⟩⟩) protected lemma mul' {p a b : α} (hp : prime p) (h : (multiplicity p (a * b)).dom) : get (multiplicity p (a * b)) h = get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2 := have hdiva : p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 ∣ a, from pow_multiplicity_dvd _, have hdivb : p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2 ∣ b, from pow_multiplicity_dvd _, have hpoweq : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) = p ^ get (multiplicity p a) ((finite_mul_iff hp).1 h).1 * p ^ get (multiplicity p b) ((finite_mul_iff hp).1 h).2, by simp [pow_add], have hdiv : p ^ (get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) ∣ a * b, by rw [hpoweq]; apply mul_dvd_mul; assumption, have hsucc : ¬p ^ ((get (multiplicity p a) ((finite_mul_iff hp).1 h).1 + get (multiplicity p b) ((finite_mul_iff hp).1 h).2) + 1) ∣ a * b, from λ h, by exact not_or (is_greatest' _ (lt_succ_self _)) (is_greatest' _ (lt_succ_self _)) (_root_.succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul hp hdiva hdivb h), by rw [← enat.coe_inj, enat.coe_get, eq_coe_iff]; exact ⟨hdiv, hsucc⟩ open_locale classical protected lemma mul {p a b : α} (hp : prime p) : multiplicity p (a * b) = multiplicity p a + multiplicity p b := if h : finite p a ∧ finite p b then by rw [← enat.coe_get (finite_iff_dom.1 h.1), ← enat.coe_get (finite_iff_dom.1 h.2), ← enat.coe_get (finite_iff_dom.1 (finite_mul hp h.1 h.2)), ← nat.cast_add, enat.coe_inj, multiplicity.mul' hp]; refl else begin rw [eq_top_iff_not_finite.2 (mt (finite_mul_iff hp).1 h)], cases not_and_distrib.1 h with h h; simp [eq_top_iff_not_finite.2 h] end lemma finset.prod {β : Type*} {p : α} (hp : prime p) (s : finset β) (f : β → α) : multiplicity p (∏ x in s, f x) = ∑ x in s, multiplicity p (f x) := begin classical, induction s using finset.induction with a s has ih h, { simp only [finset.sum_empty, finset.prod_empty], convert one_right hp.not_unit }, { simp [has, ← ih], convert multiplicity.mul hp } end protected lemma pow' {p a : α} (hp : prime p) (ha : finite p a) : ∀ {k : ℕ}, get (multiplicity p (a ^ k)) (finite_pow hp ha) = k * get (multiplicity p a) ha | 0 := by simp [one_right hp.not_unit] | (k+1) := have multiplicity p (a ^ (k + 1)) = multiplicity p (a * a ^ k), by rw pow_succ, by rw [get_eq_get_of_eq _ _ this, multiplicity.mul' hp, pow', add_mul, one_mul, add_comm] lemma pow {p a : α} (hp : prime p) : ∀ {k : ℕ}, multiplicity p (a ^ k) = k • (multiplicity p a) | 0 := by simp [one_right hp.not_unit] | (succ k) := by simp [pow_succ, succ_nsmul, pow, multiplicity.mul hp] lemma multiplicity_pow_self {p : α} (h0 : p ≠ 0) (hu : ¬ is_unit p) (n : ℕ) : multiplicity p (p ^ n) = n := by { rw [eq_coe_iff], use dvd_rfl, rw [pow_dvd_pow_iff h0 hu], apply nat.not_succ_le_self } lemma multiplicity_pow_self_of_prime {p : α} (hp : prime p) (n : ℕ) : multiplicity p (p ^ n) = n := multiplicity_pow_self hp.ne_zero hp.not_unit n end cancel_comm_monoid_with_zero section valuation variables {R : Type*} [comm_ring R] [is_domain R] {p : R} [decidable_rel (has_dvd.dvd : R → R → Prop)] /-- `multiplicity` of a prime inan integral domain as an additive valuation to `enat`. -/ noncomputable def add_valuation (hp : prime p) : add_valuation R enat := add_valuation.of (multiplicity p) (multiplicity.zero _) (one_right hp.not_unit) (λ _ _, min_le_multiplicity_add) (λ a b, multiplicity.mul hp) @[simp] lemma add_valuation_apply {hp : prime p} {r : R} : add_valuation hp r = multiplicity p r := rfl end valuation end multiplicity section nat open multiplicity lemma multiplicity_eq_zero_of_coprime {p a b : ℕ} (hp : p ≠ 1) (hle : multiplicity p a ≤ multiplicity p b) (hab : nat.coprime a b) : multiplicity p a = 0 := begin rw [multiplicity_le_multiplicity_iff] at hle, rw [← nonpos_iff_eq_zero, ← not_lt, enat.pos_iff_one_le, ← nat.cast_one, ← pow_dvd_iff_le_multiplicity], assume h, have := nat.dvd_gcd h (hle _ h), rw [coprime.gcd_eq_one hab, nat.dvd_one, pow_one] at this, exact hp this end lemma multiplicity_eq_factorization {n p : ℕ} (pp : p.prime) (hn : n ≠ 0) : multiplicity p n = n.factorization p := multiplicity.eq_coe_iff.mpr ⟨pow_factorization_dvd n p, pow_succ_factorization_not_dvd hn pp⟩ end nat
25a4d9624debef2a011d26b0bcc5f6ad6ad630f4
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/algebra/ring.lean
2829810509d717efc87e45149ebcd0ab7678538e
[ "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
19,796
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.ring.prod import ring_theory.ideal.quotient import ring_theory.subring.basic import topology.algebra.group /-! # Topological (semi)rings A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are continuous. Besides this definition, this file proves that the topological closure of a subring (resp. an ideal) is a subring (resp. an ideal) and defines products and quotients of topological (semi)rings. ## Main Results - `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a `subring`/`subsemiring` is itself a `sub(semi)ring`. - `prod.topological_semiring`/`prod.topological_ring`: The product of two topological (semi)rings. - `pi.topological_semiring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings. - `ideal.closure`: The closure of an ideal is an ideal. - `topological_ring_quotient`: The quotient of a topological semiring by an ideal is a topological ring. -/ open classical set filter topological_space function open_locale classical topological_space filter section topological_semiring variables (α : Type*) /-- a topological semiring is a semiring `R` where addition and multiplication are continuous. We allow for non-unital and non-associative semirings as well. The `topological_semiring` class should *only* be instantiated in the presence of a `non_unital_non_assoc_semiring` instance; if there is an instance of `non_unital_non_assoc_ring`, then `topological_ring` should be used. Note: in the presence of `non_assoc_ring`, these classes are mathematically equivalent (see `topological_semiring.has_continuous_neg_of_mul` or `topological_semiring.to_topological_ring`). -/ class topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] extends has_continuous_add α, has_continuous_mul α : Prop /-- A topological ring is a ring `R` where addition, multiplication and negation are continuous. If `R` is a (unital) ring, then continuity of negation can be derived from continuity of multiplication as it is multiplication with `-1`. (See `topological_semiring.has_continuous_neg_of_mul` and `topological_semiring.to_topological_add_group`) -/ class topological_ring [topological_space α] [non_unital_non_assoc_ring α] extends topological_semiring α, has_continuous_neg α : Prop variables {α} /-- If `R` is a ring with a continuous multiplication, then negation is continuous as well since it is just multiplication with `-1`. -/ lemma topological_semiring.has_continuous_neg_of_mul [topological_space α] [non_assoc_ring α] [has_continuous_mul α] : has_continuous_neg α := { continuous_neg := by simpa using (continuous_const.mul continuous_id : continuous (λ x : α, (-1) * x)) } /-- If `R` is a ring which is a topological semiring, then it is automatically a topological ring. This exists so that one can place a topological ring structure on `R` without explicitly proving `continuous_neg`. -/ lemma topological_semiring.to_topological_ring [topological_space α] [non_assoc_ring α] (h : topological_semiring α) : topological_ring α := { ..h, ..(by { haveI := h.to_has_continuous_mul, exact topological_semiring.has_continuous_neg_of_mul } : has_continuous_neg α) } @[priority 100] -- See note [lower instance priority] instance topological_ring.to_topological_add_group [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_add_group α := { ..topological_ring.to_topological_semiring.to_has_continuous_add, ..topological_ring.to_has_continuous_neg } @[priority 50] instance discrete_topology.topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] [discrete_topology α] : topological_semiring α := ⟨⟩ @[priority 50] instance discrete_topology.topological_ring [topological_space α] [non_unital_non_assoc_ring α] [discrete_topology α] : topological_ring α := ⟨⟩ section variables [topological_space α] [semiring α] [topological_semiring α] namespace subsemiring instance (S : subsemiring α) : topological_semiring S := { ..S.to_submonoid.has_continuous_mul, ..S.to_add_submonoid.has_continuous_add } end subsemiring /-- The (topological-space) closure of a subsemiring of a topological semiring is itself a subsemiring. -/ def subsemiring.topological_closure (s : subsemiring α) : subsemiring α := { carrier := closure (s : set α), ..(s.to_submonoid.topological_closure), ..(s.to_add_submonoid.topological_closure ) } @[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) : (s.topological_closure : set α) = closure (s : set α) := rfl instance subsemiring.topological_closure_topological_semiring (s : subsemiring α) : topological_semiring (s.topological_closure) := { ..s.to_add_submonoid.topological_closure_has_continuous_add, ..s.to_submonoid.topological_closure_has_continuous_mul } lemma subsemiring.subring_topological_closure (s : subsemiring α) : s ≤ s.topological_closure := subset_closure lemma subsemiring.is_closed_topological_closure (s : subsemiring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subsemiring.topological_closure_minimal (s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subsemiring of a topological semiring is commutative, then so is its topological closure. -/ def subsemiring.comm_semiring_topological_closure [t2_space α] (s : subsemiring α) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := { ..s.topological_closure.to_semiring, ..s.to_submonoid.comm_monoid_topological_closure hs } end section variables {β : Type*} [topological_space α] [topological_space β] /-- The product topology on the cartesian product of two topological semirings makes the product into a topological semiring. -/ instance [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [topological_semiring α] [topological_semiring β] : topological_semiring (α × β) := {} /-- The product topology on the cartesian product of two topological rings makes the product into a topological ring. -/ instance [non_unital_non_assoc_ring α] [non_unital_non_assoc_ring β] [topological_ring α] [topological_ring β] : topological_ring (α × β) := {} end instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_semiring (C b)] [Π b, topological_semiring (C b)] : topological_semiring (Π b, C b) := {} instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_ring (C b)] [Π b, topological_ring (C b)] : topological_ring (Π b, C b) := {} section mul_opposite open mul_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_add α] : has_continuous_add αᵐᵒᵖ := { continuous_add := continuous_induced_rng $ (@continuous_add α _ _ _).comp (continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵐᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [has_continuous_neg α] : has_continuous_neg αᵐᵒᵖ := { continuous_neg := continuous_induced_rng $ (@continuous_neg α _ _ _).comp continuous_unop } instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵐᵒᵖ := {} end mul_opposite section add_opposite open add_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_mul α] : has_continuous_mul αᵃᵒᵖ := { continuous_mul := by convert (continuous_op.comp $ (@continuous_mul α _ _ _).comp $ continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵃᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵃᵒᵖ := {} end add_opposite section variables {R : Type*} [non_unital_non_assoc_ring R] [topological_space R] lemma topological_ring.of_add_group_of_nhds_zero [topological_add_group R] (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) : topological_ring R := begin refine {..‹topological_add_group R›, ..}, have hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0), by simp, have hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) (𝓝 0), { rw ← nhds_prod_eq, convert continuous_add.tendsto ((0 : R), (0 : R)), rw zero_add }, rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, rw [continuous_at, nhds_prod_eq, hleft x₀, hleft y₀, hleft (x₀*y₀), filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λ (x : R), x + x₀ * y₀) ∘ (λ (p : R × R), p.1 + p.2) ∘ (λ (p : R × R), (p.1*y₀ + x₀*p.2, p.1*p.2))) ((𝓝 0) ×ᶠ (𝓝 0)) (map (λ (x : R), x + x₀ * y₀) $ 𝓝 0), { convert this using 1, { ext, simp only [comp_app, mul_add, add_mul], abel }, { simp only [add_comm] } }, refine tendsto_map.comp (hadd.comp (tendsto.prod_mk _ hmul)), exact hadd.comp (((hmul_right y₀).comp tendsto_fst).prod_mk ((hmul_left x₀).comp tendsto_snd)) end lemma topological_ring.of_nhds_zero (hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hneg : tendsto (λ x, -x : R → R) (𝓝 0) (𝓝 0)) (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) (hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0)) : topological_ring R := begin haveI := topological_add_group.of_comm_of_nhds_zero hadd hneg hleft, exact topological_ring.of_add_group_of_nhds_zero hmul hmul_left hmul_right end end variables {α} [topological_space α] section variables [non_unital_non_assoc_ring α] [topological_ring α] /-- In a topological semiring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological semiring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const end variables [ring α] [topological_ring α] namespace subring instance (S : subring α) : topological_ring S := topological_semiring.to_topological_ring S.to_subsemiring.topological_semiring end subring /-- The (topological-space) closure of a subring of a topological ring is itself a subring. -/ def subring.topological_closure (S : subring α) : subring α := { carrier := closure (S : set α), ..S.to_submonoid.topological_closure, ..S.to_add_subgroup.topological_closure } instance subring.topological_closure_topological_ring (s : subring α) : topological_ring (s.topological_closure) := { ..s.to_add_subgroup.topological_closure_topological_add_group, ..s.to_submonoid.topological_closure_has_continuous_mul } lemma subring.subring_topological_closure (s : subring α) : s ≤ s.topological_closure := subset_closure lemma subring.is_closed_topological_closure (s : subring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subring.topological_closure_minimal (s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subring of a topological ring is commutative, then so is its topological closure. -/ def subring.comm_ring_topological_closure [t2_space α] (s : subring α) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := { ..s.topological_closure.to_ring, ..s.to_submonoid.comm_monoid_topological_closure hs } end topological_semiring section topological_comm_ring variables {α : Type*} [topological_space α] [comm_ring α] [topological_ring α] /-- The closure of an ideal in a topological ring as an ideal. -/ def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, smul_mem' := λ c x hx, map_mem_closure (mul_left_continuous _) hx $ λ a, S.mul_mem_left c, ..(add_submonoid.topological_closure S.to_add_submonoid) } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_comm_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space (α ⧸ N) := show topological_space (quotient _), by apply_instance -- note for the reader: in the following, `mk` is `ideal.quotient.mk`, the canonical map `R → R/I`. variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin intros s s_op, change is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate, exact is_open_Union (λ ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := is_open_map.to_quotient_map ((quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N)) ((continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd)) (by rintro ⟨⟨x⟩, ⟨y⟩⟩; exact ⟨(x, y), rfl⟩) instance topological_ring_quotient : topological_ring (α ⧸ N) := topological_semiring.to_topological_ring { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont, continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont } end topological_ring /-! ### Lattice of ring topologies We define a type class `ring_topology α` which endows a ring `α` with a topology such that all ring operations are continuous. Ring topologies on a fixed ring `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → ring_topology β`. -/ universes u v /-- A ring topology on a ring `α` is a topology for which addition, negation and multiplication are continuous. -/ @[ext] structure ring_topology (α : Type u) [ring α] extends topological_space α, topological_ring α : Type u namespace ring_topology variables {α : Type*} [ring α] instance inhabited {α : Type u} [ring α] : inhabited (ring_topology α) := ⟨{to_topological_space := ⊤, continuous_add := continuous_top, continuous_mul := continuous_top, continuous_neg := continuous_top}⟩ @[ext] lemma ext' {f g : ring_topology α} (h : f.is_open = g.is_open) : f = g := by { ext, rw h } /-- The ordering on ring topologies on the ring `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (ring_topology α) := partial_order.lift ring_topology.to_topological_space $ ext local notation `cont` := @continuous _ _ private def def_Inf (S : set (ring_topology α)) : ring_topology α := let Inf_S' := Inf (to_topological_space '' S) in { to_topological_space := Inf_S', continuous_add := begin apply continuous_Inf_rng, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_add h_continuous_id, end, continuous_mul := begin apply continuous_Inf_rng, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_mul h_continuous_id, end, continuous_neg := begin apply continuous_Inf_rng, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_neg h, end } /-- Ring topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of ring topologies is the topology generated by all their open sets (which is a ring topology). The supremum of two ring topologies `s` and `t` is the infimum of the family of all ring topologies contained in the intersection of `s` and `t`. -/ instance : complete_semilattice_Inf (ring_topology α) := { Inf := def_Inf, Inf_le := λ S a haS, by { apply topological_space.complete_lattice.Inf_le, use [a, ⟨ haS, rfl⟩] }, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..ring_topology.partial_order } instance : complete_lattice (ring_topology α) := complete_lattice_of_complete_semilattice_Inf _ /-- Given `f : α → β` and a topology on `α`, the coinduced ring topology on `β` is the finest topology such that `f` is continuous and `β` is a topological ring. -/ def coinduced {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : ring_topology β := Inf {b : ring_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} lemma coinduced_continuous {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw continuous_iff_coinduced_le, refine le_Inf _, rintros _ ⟨t', ht', rfl⟩, exact ht', end /-- The forgetful functor from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology (t : ring_topology α) : add_group_topology α := { to_topological_space := t.to_topological_space, to_topological_add_group := @topological_ring.to_topological_add_group _ _ t.to_topological_space t.to_topological_ring } /-- The order embedding from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology.order_embedding : order_embedding (ring_topology α) (add_group_topology α) := { to_fun := λ t, t.to_add_group_topology, inj' := begin intros t₁ t₂ h_eq, dsimp only at h_eq, ext, have h_t₁ : t₁.to_topological_space = t₁.to_add_group_topology.to_topological_space := rfl, rw [h_t₁, h_eq], refl, end, map_rel_iff' := begin intros t₁ t₂, rw [embedding.coe_fn_mk], have h_le : t₁ ≤ t₂ ↔ t₁.to_topological_space ≤ t₂.to_topological_space := by refl, rw h_le, refl, end } end ring_topology
c1c8c2f0a956417060e42f854f7bd3d136ca669b
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Data/FuzzyMatching.lean
22bcdb2cba784a46ccd543092bc0229e3655896b
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
10,863
lean
/- Copyright (c) 2022 Lars König. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Lars König The string fuzzy matching algorithm in this file is based on the algorithm used in LLVM with some modifications. The LLVM algorithm itself is based on VS code's client side filtering algorithm. For the LLVM implementation see https://clang.llvm.org/extra//doxygen/FuzzyMatch_8cpp_source.html -/ namespace Lean namespace FuzzyMatching section Utils @[specialize] private def iterateLookaround (f : (Option Char × Char × Option Char) → α) (string : String) : Array α := if string.isEmpty then #[] else if string.length == 1 then #[f (none, string.get 0, none)] else Id.run do let mut result := Array.mkEmpty string.length result := result.push <| f (none, string.get 0, string.get ⟨1⟩) -- TODO: the following code is assuming all characters are ASCII for i in [2:string.length] do result := result.push <| f (string.get ⟨i - 2⟩, string.get ⟨i - 1⟩, string.get ⟨i⟩) result.push <| f (string.get ⟨string.length - 2⟩, string.get ⟨string.length - 1⟩, none) private def containsInOrderLower (a b : String) : Bool := Id.run do if a.isEmpty then return true let mut aIt := a.mkIterator -- TODO: the following code is assuming all characters are ASCII for i in [:b.endPos.byteIdx] do if aIt.curr.toLower == (b.get ⟨i⟩).toLower then aIt := aIt.next if !aIt.hasNext then return true return false end Utils /-- Represents the type of a single character. -/ inductive CharType where | lower | upper | separator def charType (c : Char) : CharType := if c.isAlphanum then if c.isUpper then CharType.upper else CharType.lower else CharType.separator /-- Represents the role of a character inside a word. -/ inductive CharRole where | head | tail | separator deriving Inhabited @[inline] def charRole (prev? : Option CharType) (curr : CharType) (next?: Option CharType) : CharRole := if curr matches CharType.separator then CharRole.separator else if prev?.isNone || prev? matches some CharType.separator then CharRole.head else if curr matches CharType.lower then CharRole.tail else if prev? matches some CharType.upper && !(next? matches some CharType.lower) then CharRole.tail else CharRole.head /-- Add additional information to each character in a string. -/ private def stringInfo (s : String) : Array CharRole := iterateLookaround (string := s) fun (prev?, curr, next?) => charRole (prev?.map charType) (charType curr) (next?.map charType) private def selectBest (missScore? matchScore? : Option Int) : Option Int := match (missScore?, matchScore?) with | (missScore, none) => missScore | (none, matchScore) => matchScore | (some missScore, some matchScore) => some <| max missScore matchScore /-- Match the given pattern with the given word. The algorithm uses dynamic programming to find the best scores. In addition to the current characters in the pattern and the word, the algorithm uses different scores for the last operation (miss/match). This is necessary to give consecutive character matches a bonus. -/ private def fuzzyMatchCore (pattern word : String) (patternRoles wordRoles : Array CharRole) : Option Int := Id.run do /- Flattened array where the value at index (i, j, k) represents the best possible score of a fuzzy match between the substrings pattern[:i+1] and word[:j+1] assuming that pattern[i] misses at word[j] (k = 0, i.e. it was matched earlier), or matches at word[j] (k = 1). A value of `none` corresponds to a score of -∞, and is used where no such match/miss is possible or for unneeded parts of the table. -/ let mut result : Array (Option Int) := Array.mkArray (pattern.length * word.length * 2) none let mut runLengths : Array Int := Array.mkArray (pattern.length * word.length) 0 -- penalty for starting a consecutive run at each index let mut startPenalties : Array Int := Array.mkArray word.length 0 let mut lastSepIdx := 0 let mut penaltyNs : Int := 0 let mut penaltySkip : Int := 0 for wordIdx in [:word.length] do if (wordIdx != 0) && (wordRoles.get! wordIdx) matches .separator then -- reset skip penalty at namespace separator penaltySkip := 0 -- add constant penalty for each namespace to prefer shorter namespace nestings penaltyNs := penaltyNs + 1 lastSepIdx := wordIdx penaltySkip := penaltySkip + skipPenalty (wordRoles.get! wordIdx) (wordIdx == 0) startPenalties := startPenalties.set! wordIdx $ penaltySkip + penaltyNs -- TODO: the following code is assuming all characters are ASCII for patternIdx in [:pattern.length] do /- For this dynamic program to be correct, it's only necessary to populate a range of length `word.length - pattern.length` at each index (because at the very end, we can only consider fuzzy matches of `pattern` with a longer substring of `word`). -/ for wordIdx in [patternIdx:word.length-(pattern.length - patternIdx - 1)] do let missScore? := if wordIdx >= 1 then selectBest (getMiss result patternIdx (wordIdx - 1)) (getMatch result patternIdx (wordIdx - 1)) else none let mut matchScore? := none if allowMatch (pattern.get ⟨patternIdx⟩) (word.get ⟨wordIdx⟩) (patternRoles.get! patternIdx) (wordRoles.get! wordIdx) then if patternIdx >= 1 then let runLength := runLengths.get! (getIdx (patternIdx - 1) (wordIdx - 1)) + 1 runLengths := runLengths.set! (getIdx patternIdx wordIdx) runLength matchScore? := selectBest (getMiss result (patternIdx - 1) (wordIdx - 1) |>.map (· + matchResult (pattern.get ⟨patternIdx⟩) (word.get ⟨wordIdx⟩) (patternRoles.get! patternIdx) (wordRoles.get! wordIdx) none (wordIdx == 0) - startPenalties.get! wordIdx)) (getMatch result (patternIdx - 1) (wordIdx - 1) |>.map (· + matchResult (pattern.get ⟨patternIdx⟩) (word.get ⟨wordIdx⟩) (patternRoles.get! patternIdx) (wordRoles.get! wordIdx) (.some runLength) (wordIdx == 0) )) |>.map fun score => if wordIdx >= lastSepIdx then score + 1 else score -- main identifier bonus else runLengths := runLengths.set! (getIdx patternIdx wordIdx) 1 matchScore? := .some $ matchResult (pattern.get ⟨patternIdx⟩) (word.get ⟨wordIdx⟩) (patternRoles.get! patternIdx) (wordRoles.get! wordIdx) none (wordIdx == 0) - startPenalties.get! wordIdx result := set result patternIdx wordIdx missScore? matchScore? return selectBest (getMiss result (pattern.length - 1) (word.length - 1)) (getMatch result (pattern.length - 1) (word.length - 1)) where getDoubleIdx (patternIdx wordIdx : Nat) := patternIdx * word.length * 2 + wordIdx * 2 getIdx (patternIdx wordIdx : Nat) := patternIdx * word.length + wordIdx getMiss (result : Array (Option Int)) (patternIdx wordIdx : Nat) : Option Int := result.get! $ getDoubleIdx patternIdx wordIdx getMatch (result : Array (Option Int)) (patternIdx wordIdx : Nat) : Option Int := result.get! $ getDoubleIdx patternIdx wordIdx + 1 set (result : Array (Option Int)) (patternIdx wordIdx : Nat) (missValue matchValue : Option Int) : Array (Option Int) := let idx := getDoubleIdx patternIdx wordIdx result |>.set! idx missValue |>.set! (idx + 1) matchValue /-- Heuristic to penalize skipping characters in the word. -/ skipPenalty (wordRole : CharRole) (wordStart : Bool) : Int := Id.run do /- Skipping the beginning of the word. -/ if wordStart then return 3 /- Skipping the beginning of a segment. -/ if wordRole matches CharRole.head then return 1 return 0 /-- Whether characters from the pattern and the word match. -/ allowMatch (patternChar wordChar : Char) (patternRole wordRole : CharRole) : Bool := Id.run do /- Different characters do not match. -/ if patternChar.toLower != wordChar.toLower then return false /- The beginning of a segment in the pattern must align with the beginning of a segment in the word. -/ if patternRole matches CharRole.head && !(wordRole matches CharRole.head) then return false return true /-- Heuristic to rate a match. -/ matchResult (patternChar wordChar : Char) (patternRole wordRole : CharRole) (consecutive : Option Int) (wordStart : Bool) : Int := Id.run do let mut score : Int := 1 /- Case-sensitive equality or beginning of a segment in pattern and word. -/ if patternChar == wordChar || (patternRole matches CharRole.head && wordRole matches CharRole.head) then score := score + 1 /- Beginning of the word. -/ if wordStart then score := score + 2 /- Consecutive character match. -/ if let some bonus := consecutive then /- consecutive run bonus -/ score := score + bonus return score /-- Match the given pattern with the given word using a fuzzy matching algorithm. The resulting scores are in the interval `[0, 1]` or `none` if no match was found. -/ def fuzzyMatchScore? (pattern word : String) : Option Float := Id.run do /- Some fast and simple checks. -/ if pattern.isEmpty then return some 1 if pattern.length > word.length then return none if !(containsInOrderLower pattern word) then return none let some score := fuzzyMatchCore pattern word (stringInfo pattern) (stringInfo word) | none let mut score := score /- Bonus if every character is matched. -/ if pattern.length == word.length then score := score * 2 /- Perfect score per character. -/ let perfect := 4 /- Perfect score for full match given the heuristic in `matchResult`; the latter term represents the bonus of a perfect consecutive run. -/ let perfectMatch := (perfect * pattern.length + ((pattern.length * (pattern.length + 1) / 2) - 1)) let normScore := Float.ofInt score / Float.ofInt perfectMatch return some <| min 1 (max 0 normScore) def fuzzyMatchScoreWithThreshold? (pattern word : String) (threshold := 0.1) : Option Float := fuzzyMatchScore? pattern word |>.filter (· > threshold) /-- Match the given pattern with the given word using a fuzzy matching algorithm. Return `false` if no match was found or the found match received a score below the given threshold. -/ def fuzzyMatch (pattern word : String) (threshold := 0.2) : Bool := fuzzyMatchScoreWithThreshold? pattern word threshold |>.isSome end FuzzyMatching end Lean
51d590e4e658f7981b1b29146e6ec5438241e13c
649957717d58c43b5d8d200da34bf374293fe739
/src/data/matrix.lean
e7e41829ebeecbf39b8f721ac2b444c45e068131
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
10,939
lean
/- Copyright (c) 2018 Ellen Arlt. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin Matrices -/ import algebra.module algebra.pi_instances import data.fintype universes u v def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) := m → n → α namespace matrix variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] variables {α : Type v} section ext variables {M N : matrix m n α} theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N := ⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩ @[extensionality] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp def transpose (M : matrix m n α) : matrix n m α | x y := M y x def col (w : m → α) : matrix m punit α | x y := w x def row (v : n → α) : matrix punit n α | x y := v y end ext instance [has_add α] : has_add (matrix m n α) := pi.has_add instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg instance [add_group α] : add_group (matrix m n α) := pi.add_group instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group @[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl @[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl @[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl section diagonal variables [decidable_eq n] def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0 @[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i := by simp [diagonal] @[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) : (diagonal d) i j = 0 := by simp [diagonal, h] theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) : (diagonal d) i j = 0 := diagonal_val_ne h.symm @[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 := by simp [diagonal]; refl section one variables [has_zero α] [has_one α] instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩ @[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl @[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i @[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 := diagonal_val_ne theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 := diagonal_val_ne' end one end diagonal @[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) : diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) := by ext i j; by_cases i = j; simp [h] protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, finset.univ.sum (λ j, M i j * N j k) local notation M `⬝` N := M.mul N theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M ⬝ N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl local attribute [simp] mul_val instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩ @[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) : M * N = M ⬝ N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl section semigroup variables [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) := by classical; funext i k; simp [finset.mul_sum, finset.sum_mul, mul_assoc]; rw finset.sum_comm instance : semigroup (matrix n n α) := { mul_assoc := matrix.mul_assoc, ..matrix.has_mul } end semigroup @[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) : -diagonal d = diagonal (λ i, -d i) := by ext i j; by_cases i = j; simp [h] section semiring variables [semiring α] @[simp] theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 := by ext i j; simp @[simp] theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 := by ext i j; simp theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N := by ext i j; simp [finset.sum_add_distrib, mul_add] theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N := by ext i j; simp [finset.sum_add_distrib, add_mul] @[simp] theorem diagonal_mul [decidable_eq m] (d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j := by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt} @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j := by simp; rw finset.sum_eq_single j; simp {contextual := tt} @[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] @[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M := by ext i j; rw [← diagonal_one, mul_diagonal, mul_one] instance [decidable_eq n] : monoid (matrix n n α) := { one_mul := matrix.one_mul, mul_one := matrix.mul_one, ..matrix.has_one, ..matrix.semigroup } instance [decidable_eq n] : semiring (matrix n n α) := { mul_zero := mul_zero, zero_mul := zero_mul, left_distrib := mul_add, right_distrib := add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) := by ext i j; by_cases i = j; simp [h] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) : diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) := diagonal_mul_diagonal' _ _ end semiring section ring variables [ring α] @[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) : (-M) ⬝ N = -(M ⬝ N) := by ext; simp [matrix.mul] @[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) : M ⬝ (-N) = -(M ⬝ N) := by ext; simp [matrix.mul] end ring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.add_comm_group, ..matrix.semiring } instance [has_mul α] : has_scalar α (matrix m n α) := ⟨λ a M i j, a * M i j⟩ instance [ring α] : module α (matrix m n α) := module.of_core { smul_add := λ a M N, ext $ λ i j, _root_.mul_add a (M i j) (N i j), add_smul := λ a b M, ext $ λ i j, _root_.add_mul a b (M i j), mul_smul := λ a b M, ext $ λ i j, mul_assoc a b (M i j), one_smul := λ M, ext $ λ i j, one_mul (M i j), .. (infer_instance : has_scalar α (matrix m n α)) } section comm_ring variables [comm_ring α] @[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end @[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N := begin ext i j, unfold matrix.mul has_scalar.smul, rw finset.mul_sum, congr, ext, ac_refl end end comm_ring section semiring variables [semiring α] def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α | x y := w x * v y def mul_vec (M : matrix m n α) (v : n → α) : m → α | x := finset.univ.sum (λy:n, M x y * v y) def vec_mul (v : m → α) (M : matrix m n α) : n → α | y := finset.univ.sum (λx:m, v x * M x y) instance mul_vec.is_add_monoid_hom_left (v : n → α) : is_add_monoid_hom (λM:matrix m n α, mul_vec M v) := { map_zero := by ext; simp [mul_vec]; refl, map_add := begin intros x y, ext m, rw pi.add_apply (mul_vec x v) (mul_vec y v) m, simp [mul_vec, finset.sum_add_distrib, right_distrib] end } lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) : mul_vec (diagonal v) w x = v x * w x := begin transitivity, refine finset.sum_eq_single x _ _, { assume b _ ne, simp [diagonal, ne.symm] }, { simp }, { rw [diagonal_val_eq] } end lemma vec_mul_vec_eq (w : m → α) (v : n → α) : vec_mul_vec w v = (col w) ⬝ (row v) := by simp [matrix.mul]; refl end semiring section transpose local postfix `ᵀ` : 1500 := transpose lemma transpose_transpose (M : matrix m n α) : Mᵀᵀ = M := by ext; refl @[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 := by ext i j; refl @[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) : (M + N)ᵀ = Mᵀ + Nᵀ := begin ext i j, dsimp [transpose], refl end @[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) : (M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ := begin ext i j, unfold matrix.mul transpose, congr, ext, ac_refl end @[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) : (- M)ᵀ = - Mᵀ := by ext i j; refl end transpose def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α := λ i j, A (row i) (col j) @[reducible] def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α := minor A id (fin.cast_add r) @[reducible] def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α := minor A id (fin.nat_add l) @[reducible] def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α := minor A (fin.cast_add d) id @[reducible] def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α := minor A (fin.nat_add u) id @[reducible] def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin r) α := sub_up (sub_right A) @[reducible] def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin r) α := sub_down (sub_right A) @[reducible] def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin u) (fin (l)) α := sub_up (sub_left A) @[reducible] def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) : matrix (fin d) (fin (l)) α := sub_down (sub_left A) end matrix
d0f096e114ed18b6980faa6655c6c7b24369a0df
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/linear_algebra/affine_space/barycentric_coords.lean
39bb4ce50128c829374491fbd4dc6cf58c6e2481
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,192
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.affine_space.independent /-! # Barycentric coordinates Suppose `P` is an affine space modelled on the module `V` over the ring `k`, and `p : ι → P` is an affine-independent family of points spanning `P`. Given this data, each point `q : P` may be written uniquely as an affine combination: `q = w₀ p₀ + w₁ p₁ + ⋯` for some (finitely-supported) weights `wᵢ`. For each `i : ι`, we thus have an affine map `P →ᵃ[k] k`, namely `q ↦ wᵢ`. This family of maps is known as the family of barycentric coordinates. It is defined in this file. ## The construction Fixing `i : ι`, and allowing `j : ι` to range over the values `j ≠ i`, we obtain a basis `bᵢ` of `V` defined by `bᵢ j = p j -ᵥ p i`. Let `fᵢ j : V →ₗ[k] k` be the corresponding dual basis and let `fᵢ = ∑ j, fᵢ j : V →ₗ[k] k` be the corresponding "sum of all coordinates" form. Then the `i`th barycentric coordinate of `q : P` is `1 - fᵢ (q -ᵥ p i)`. ## Main definitions * `barycentric_coord`: the map `P →ᵃ[k] k` corresponding to `i : ι`. * `barycentric_coord_apply_eq`: the behaviour of `barycentric_coord i` on `p i`. * `barycentric_coord_apply_neq`: the behaviour of `barycentric_coord i` on `p j` when `j ≠ i`. * `barycentric_coord_apply`: the behaviour of `barycentric_coord i` on `p j` for general `j`. * `barycentric_coord_apply_combination`: the characterisation of `barycentric_coord i` in terms of affine combinations, i.e., `barycentric_coord i (w₀ p₀ + w₁ p₁ + ⋯) = wᵢ`. ## TODO * Construct the affine equivalence between `P` and `{ f : ι →₀ k | f.sum = 1 }`. -/ open_locale affine big_operators open set universes u₁ u₂ u₃ u₄ variables {ι : Type u₁} {k : Type u₂} {V : Type u₃} {P : Type u₄} variables [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {p : ι → P} (h_ind : affine_independent k p) (h_tot : affine_span k (range p) = ⊤) include V h_ind h_tot /-- Given an affine-independent family of points spanning the point space `P`, if we single out one member of the family, we obtain a basis for the model space `V`. The basis correpsonding to the singled-out member `i : ι` is indexed by `{j : ι // j ≠ i}` and its `j`th element is `p j -ᵥ p i`. (See `basis_of_aff_ind_span_eq_top_apply`.) -/ noncomputable def basis_of_aff_ind_span_eq_top (i : ι) : basis {j : ι // j ≠ i} k V := basis.mk ((affine_independent_iff_linear_independent_vsub k p i).mp h_ind) begin suffices : submodule.span k (range (λ (j : {x // x ≠ i}), p ↑j -ᵥ p i)) = vector_span k (range p), { rw [this, ← direction_affine_span, h_tot, affine_subspace.direction_top], }, conv_rhs { rw ← image_univ, }, rw vector_span_image_eq_span_vsub_set_right_ne k p (mem_univ i), congr, ext v, simp, end local notation `basis_of` := basis_of_aff_ind_span_eq_top h_ind h_tot @[simp] lemma basis_of_aff_ind_span_eq_top_apply (i : ι) (j : {j : ι // j ≠ i}) : basis_of i j = p ↑j -ᵥ p i := by simp [basis_of_aff_ind_span_eq_top] /-- The `i`th barycentric coordinate of a point. -/ noncomputable def barycentric_coord (i : ι) : P →ᵃ[k] k := { to_fun := λ q, 1 - (basis_of i).sum_coords (q -ᵥ p i), linear := -(basis_of i).sum_coords, map_vadd' := λ q v, by rw [vadd_vsub_assoc, linear_map.map_add, vadd_eq_add, linear_map.neg_apply, sub_add_eq_sub_sub_swap, add_comm, sub_eq_add_neg], } @[simp] lemma barycentric_coord_apply_eq (i : ι) : barycentric_coord h_ind h_tot i (p i) = 1 := by simp only [barycentric_coord, basis.coe_sum_coords, linear_equiv.map_zero, linear_equiv.coe_coe, sub_zero, affine_map.coe_mk, finsupp.sum_zero_index, vsub_self] @[simp] lemma barycentric_coord_apply_neq (i j : ι) (h : j ≠ i) : barycentric_coord h_ind h_tot i (p j) = 0 := by rw [barycentric_coord, affine_map.coe_mk, ← subtype.coe_mk j h, ← basis_of_aff_ind_span_eq_top_apply h_ind h_tot i ⟨j, h⟩, basis.sum_coords_self_apply, sub_self] lemma barycentric_coord_apply [decidable_eq ι] (i j : ι) : barycentric_coord h_ind h_tot i (p j) = if i = j then 1 else 0 := by { cases eq_or_ne i j; simp [h.symm], simp [h], } @[simp] lemma barycentric_coord_apply_combination_of_mem {s : finset ι} {i : ι} (hi : i ∈ s) {w : ι → k} (hw : s.sum w = 1) : barycentric_coord h_ind h_tot i (s.affine_combination p w) = w i := begin classical, simp only [barycentric_coord_apply, hi, finset.affine_combination_eq_linear_combination, if_true, hw, mul_boole, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination p w hw], end @[simp] lemma barycentric_coord_apply_combination_of_not_mem {s : finset ι} {i : ι} (hi : i ∉ s) {w : ι → k} (hw : s.sum w = 1) : barycentric_coord h_ind h_tot i (s.affine_combination p w) = 0 := begin classical, simp only [barycentric_coord_apply, hi, finset.affine_combination_eq_linear_combination, if_false, hw, mul_boole, function.comp_app, smul_eq_mul, s.sum_ite_eq, s.map_affine_combination p w hw], end
f2536de1625b3838b5a527485ef047be95989a8e
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/t6.lean
53a5e5bc81a0369b1a457bb0170fa358283bb6fc
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
332
lean
definition Prop : Type.{1} := Type.{0} section parameter {A : Type} -- Mark A as implicit parameter parameter R : A → A → Prop definition id (a : A) : A := a definition refl : Prop := forall (a : A), R a a definition symm : Prop := forall (a b : A), R a b -> R b a end check id.{2} check refl.{1} check symm.{1}
185bd29b453dfe73761ae89e5c246cf90a9dd376
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/polynomial/field_division.lean
d7337da3eab394bad03c5b90813b98a5816fdc24
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
18,384
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.ring_division import data.polynomial.derivative import algebra.gcd_monoid /-! # Theory of univariate polynomials This file starts looking like the ring theory of $ R[X] $ -/ noncomputable theory open_locale classical big_operators namespace polynomial universes u v w y z variables {R : Type u} {S : Type v} {k : Type y} {A : Type z} {a b : R} {n : ℕ} section integral_domain variables [integral_domain R] [normalization_monoid R] instance : normalization_monoid (polynomial R) := { norm_unit := λ p, ⟨C ↑(norm_unit (p.leading_coeff)), C ↑(norm_unit (p.leading_coeff))⁻¹, by rw [← ring_hom.map_mul, units.mul_inv, C_1], by rw [← ring_hom.map_mul, units.inv_mul, C_1]⟩, norm_unit_zero := units.ext (by simp), norm_unit_mul := λ p q hp0 hq0, units.ext (begin dsimp, rw [ne.def, ← leading_coeff_eq_zero] at *, rw [leading_coeff_mul, norm_unit_mul hp0 hq0, units.coe_mul, C_mul], end), norm_unit_coe_units := λ u, units.ext begin rw [← mul_one u⁻¹, units.coe_mul, units.eq_inv_mul_iff_mul_eq], dsimp, rcases polynomial.is_unit_iff.1 ⟨u, rfl⟩ with ⟨_, ⟨w, rfl⟩, h2⟩, rw [← h2, leading_coeff_C, norm_unit_coe_units, ← C_mul, units.mul_inv, C_1], end } @[simp] lemma coe_norm_unit {p : polynomial R} : (norm_unit p : polynomial R) = C ↑(norm_unit p.leading_coeff) := by simp [norm_unit] lemma leading_coeff_normalize (p : polynomial R) : leading_coeff (normalize p) = normalize (leading_coeff p) := by simp end integral_domain section field variables [field R] {p q : polynomial R} lemma is_unit_iff_degree_eq_zero : is_unit p ↔ degree p = 0 := ⟨degree_eq_zero_of_is_unit, λ h, have degree p ≤ 0, by simp [*, le_refl], have hc : coeff p 0 ≠ 0, from λ hc, by rw [eq_C_of_degree_le_zero this, hc] at h; simpa using h, is_unit_iff_dvd_one.2 ⟨C (coeff p 0)⁻¹, begin conv in p { rw eq_C_of_degree_le_zero this }, rw [← C_mul, _root_.mul_inv_cancel hc, C_1] end⟩⟩ lemma degree_pos_of_ne_zero_of_nonunit (hp0 : p ≠ 0) (hp : ¬is_unit p) : 0 < degree p := lt_of_not_ge (λ h, by rw [eq_C_of_degree_le_zero h] at hp0 hp; exact (hp $ is_unit.map' C $ is_unit.mk0 (coeff p 0) (mt C_inj.2 (by simpa using hp0)))) lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (p : polynomial R) (h : q ≠ 0) : degree (p * C (leading_coeff q)⁻¹) = degree p := have h₁ : (leading_coeff q)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul, degree_C h₁, add_zero] theorem irreducible_of_monic {p : polynomial R} (hp1 : p.monic) (hp2 : p ≠ 1) : irreducible p ↔ (∀ f g : polynomial R, f.monic → g.monic → f * g = p → f = 1 ∨ g = 1) := ⟨λ hp3 f g hf hg hfg, or.cases_on (hp3.2 f g hfg.symm) (assume huf : is_unit f, or.inl $ eq_one_of_is_unit_of_monic hf huf) (assume hug : is_unit g, or.inr $ eq_one_of_is_unit_of_monic hg hug), λ hp3, ⟨mt (eq_one_of_is_unit_of_monic hp1) hp2, λ f g hp, have hf : f ≠ 0, from λ hf, by { rw [hp, hf, zero_mul] at hp1, exact not_monic_zero hp1 }, have hg : g ≠ 0, from λ hg, by { rw [hp, hg, mul_zero] at hp1, exact not_monic_zero hp1 }, or.imp (λ hf, is_unit_of_mul_eq_one _ _ hf) (λ hg, is_unit_of_mul_eq_one _ _ hg) $ hp3 (f * C f.leading_coeff⁻¹) (g * C g.leading_coeff⁻¹) (monic_mul_leading_coeff_inv hf) (monic_mul_leading_coeff_inv hg) $ by rw [mul_assoc, mul_left_comm _ g, ← mul_assoc, ← C_mul, ← mul_inv', ← leading_coeff_mul, ← hp, monic.def.1 hp1, inv_one, C_1, mul_one]⟩⟩ /-- Division of polynomials. See polynomial.div_by_monic for more details.-/ def div (p q : polynomial R) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) /-- Remainder of polynomial division, see the lemma `quotient_mul_add_remainder_eq_aux`. See polynomial.mod_by_monic for more details. -/ def mod (p q : polynomial R) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial R) : q * div p q + mod p q = p := if h : q = 0 then by simp only [h, zero_mul, mod, mod_by_monic_zero, zero_add] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial R) (hq : q ≠ 0) : degree (mod p q) < degree q := by rw ← degree_mul_leading_coeff_inv q hq; exact degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial R) := ⟨div⟩ instance : has_mod (polynomial R) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial R) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp only [monic.def.1 hq, inv_one, mul_one, C_1] lemma div_by_monic_eq_div (p : polynomial R) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp only [monic.def.1 hq, inv_one, C_1, one_mul, mul_one] lemma mod_X_sub_C_eq_C_eval (p : polynomial R) (a : R) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial R) := { quotient := (/), quotient_zero := by simp [div_def], remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq), .. polynomial.comm_ring, .. polynomial.nontrivial } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv q hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp only [this, false_and, if_false] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv q hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul]} lemma degree_div_le (p q : polynomial R) : degree (p / q) ≤ degree p := if hq : q = 0 then by simp [hq] else by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq]; exact degree_div_by_monic_le _ _ lemma degree_div_lt (hp : p ≠ 0) (hq : 0 < degree q) : degree (p / q) < degree p := have hq0 : q ≠ 0, from λ hq0, by simpa [hq0] using hq, by rw [div_def, mul_comm, degree_mul_leading_coeff_inv _ hq0]; exact degree_div_by_monic_lt _ (monic_mul_leading_coeff_inv hq0) hp (by rw degree_mul_leading_coeff_inv _ hq0; exact hq) @[simp] lemma degree_map [field k] (p : polynomial R) (f : R →+* k) : degree (p.map f) = degree p := p.degree_map_eq_of_injective f.injective @[simp] lemma nat_degree_map [field k] (f : R →+* k) : nat_degree (p.map f) = nat_degree p := nat_degree_eq_of_degree_eq (degree_map _ f) @[simp] lemma leading_coeff_map [field k] (f : R →+* k) : leading_coeff (p.map f) = f (leading_coeff p) := by simp only [← coeff_nat_degree, coeff_map f, nat_degree_map] theorem monic_map_iff [field k] {f : R →+* k} {p : polynomial R} : (p.map f).monic ↔ p.monic := by rw [monic, leading_coeff_map, ← f.map_one, function.injective.eq_iff f.injective, monic] theorem is_unit_map [field k] (f : R →+* k) : is_unit (p.map f) ↔ is_unit p := by simp_rw [is_unit_iff_degree_eq_zero, degree_map] lemma map_div [field k] (f : R →+* k) : (p / q).map f = p.map f / q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [div_def, div_def, map_mul, map_div_by_monic f (monic_mul_leading_coeff_inv hq0)]; simp [f.map_inv, coeff_map f] lemma map_mod [field k] (f : R →+* k) : (p % q).map f = p.map f % q.map f := if hq0 : q = 0 then by simp [hq0] else by rw [mod_def, mod_def, leading_coeff_map f, ← f.map_inv, ← map_C f, ← map_mul f, map_mod_by_monic f (monic_mul_leading_coeff_inv hq0)] section open euclidean_domain local attribute [-instance] finsupp.finsupp.decidable_eq theorem gcd_map [field k] (f : R →+* k) : gcd (p.map f) (q.map f) = (gcd p q).map f := gcd.induction p q (λ x, by simp_rw [map_zero, euclidean_domain.gcd_zero_left]) $ λ x y hx ih, by rw [gcd_val, ← map_mod, ih, ← gcd_val] end lemma eval₂_gcd_eq_zero [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hf : f.eval₂ ϕ α = 0) (hg : g.eval₂ ϕ α = 0) : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 := by rw [euclidean_domain.gcd_eq_gcd_ab f g, polynomial.eval₂_add, polynomial.eval₂_mul, polynomial.eval₂_mul, hf, hg, zero_mul, zero_mul, zero_add] lemma eval_gcd_eq_zero {f g : polynomial R} {α : R} (hf : f.eval α = 0) (hg : g.eval α = 0) : (euclidean_domain.gcd f g).eval α = 0 := eval₂_gcd_eq_zero hf hg lemma root_left_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : f.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_left f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_right_of_root_gcd [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} (hα : (euclidean_domain.gcd f g).eval₂ ϕ α = 0) : g.eval₂ ϕ α = 0 := by { cases euclidean_domain.gcd_dvd_right f g with p hp, rw [hp, polynomial.eval₂_mul, hα, zero_mul] } lemma root_gcd_iff_root_left_right [comm_semiring k] {ϕ : R →+* k} {f g : polynomial R} {α : k} : (euclidean_domain.gcd f g).eval₂ ϕ α = 0 ↔ (f.eval₂ ϕ α = 0) ∧ (g.eval₂ ϕ α = 0) := ⟨λ h, ⟨root_left_of_root_gcd h, root_right_of_root_gcd h⟩, λ h, eval₂_gcd_eq_zero h.1 h.2⟩ lemma is_root_gcd_iff_is_root_left_right {f g : polynomial R} {α : R} : (euclidean_domain.gcd f g).is_root α ↔ f.is_root α ∧ g.is_root α := root_gcd_iff_root_left_right theorem is_coprime_map [field k] (f : R →+* k) : is_coprime (p.map f) (q.map f) ↔ is_coprime p q := by rw [← gcd_is_unit_iff, ← gcd_is_unit_iff, gcd_map, is_unit_map] @[simp] lemma map_eq_zero [semiring S] [nontrivial S] (f : R →+* S) : p.map f = 0 ↔ p = 0 := by simp only [polynomial.ext_iff, f.map_eq_zero, coeff_map, coeff_zero] lemma map_ne_zero [semiring S] [nontrivial S] {f : R →+* S} (hp : p ≠ 0) : p.map f ≠ 0 := mt (map_eq_zero f).1 hp lemma mem_roots_map [field k] {f : R →+* k} {x : k} (hp : p ≠ 0) : x ∈ (p.map f).roots ↔ p.eval₂ f x = 0 := begin rw mem_roots (show p.map f ≠ 0, by exact map_ne_zero hp), dsimp only [is_root], rw polynomial.eval_map, end lemma exists_root_of_degree_eq_one (h : degree p = 1) : ∃ x, is_root p x := ⟨-(p.coeff 0 / p.coeff 1), have p.coeff 1 ≠ 0, by rw ← nat_degree_eq_of_degree_eq_some h; exact mt leading_coeff_eq_zero.1 (λ h0, by simpa [h0] using h), by conv in p { rw [eq_X_add_C_of_degree_le_one (show degree p ≤ 1, by rw h; exact le_refl _)] }; simp [is_root, mul_div_cancel' _ this]⟩ lemma coeff_inv_units (u : units (polynomial R)) (n : ℕ) : ((↑u : polynomial R).coeff n)⁻¹ = ((↑u⁻¹ : polynomial R).coeff n) := begin rw [eq_C_of_degree_eq_zero (degree_coe_units u), eq_C_of_degree_eq_zero (degree_coe_units u⁻¹), coeff_C, coeff_C, inv_eq_one_div], split_ifs, { rw [div_eq_iff_mul_eq (coeff_coe_units_zero_ne_zero u), coeff_zero_eq_eval_zero, coeff_zero_eq_eval_zero, ← eval_mul, ← units.coe_mul, inv_mul_self]; simp }, { simp } end lemma monic_normalize (hp0 : p ≠ 0) : monic (normalize p) := begin rw [ne.def, ← leading_coeff_eq_zero, ← ne.def, ← is_unit_iff_ne_zero] at hp0, rw [monic, leading_coeff_normalize, normalize_eq_one], apply hp0, end lemma coe_norm_unit_of_ne_zero (hp : p ≠ 0) : (norm_unit p : polynomial R) = C p.leading_coeff⁻¹ := by simp [hp] lemma normalize_monic (h : monic p) : normalize p = p := by simp [h] theorem map_dvd_map' [field k] (f : R →+* k) {x y : polynomial R} : x.map f ∣ y.map f ↔ x ∣ y := if H : x = 0 then by rw [H, map_zero, zero_dvd_iff, zero_dvd_iff, map_eq_zero] else by rw [← normalize_dvd_iff, ← @normalize_dvd_iff (polynomial R), normalize_apply, normalize_apply, coe_norm_unit_of_ne_zero H, coe_norm_unit_of_ne_zero (mt (map_eq_zero f).1 H), leading_coeff_map, ← f.map_inv, ← map_C, ← map_mul, map_dvd_map _ f.injective (monic_mul_leading_coeff_inv H)] lemma degree_normalize : degree (normalize p) = degree p := by simp lemma prime_of_degree_eq_one (hp1 : degree p = 1) : prime p := have prime (normalize p), from prime_of_degree_eq_one_of_monic (hp1 ▸ degree_normalize) (monic_normalize (λ hp0, absurd hp1 (hp0.symm ▸ by simp; exact dec_trivial))), prime_of_associated normalize_associated this lemma irreducible_of_degree_eq_one (hp1 : degree p = 1) : irreducible p := irreducible_of_prime (prime_of_degree_eq_one hp1) theorem not_irreducible_C (x : R) : ¬irreducible (C x) := if H : x = 0 then by { rw [H, C_0], exact not_irreducible_zero } else λ hx, irreducible.not_unit hx $ is_unit_C.2 $ is_unit_iff_ne_zero.2 H theorem degree_pos_of_irreducible (hp : irreducible p) : 0 < p.degree := lt_of_not_ge $ λ hp0, have _ := eq_C_of_degree_le_zero hp0, not_irreducible_C (p.coeff 0) $ this ▸ hp theorem pairwise_coprime_X_sub {α : Type u} [field α] {I : Type v} {s : I → α} (H : function.injective s) : pairwise (is_coprime on (λ i : I, polynomial.X - polynomial.C (s i))) := λ i j hij, have h : s j - s i ≠ 0, from sub_ne_zero_of_ne $ function.injective.ne H hij.symm, ⟨polynomial.C (s j - s i)⁻¹, -polynomial.C (s j - s i)⁻¹, by rw [neg_mul_eq_neg_mul_symm, ← sub_eq_add_neg, ← mul_sub, sub_sub_sub_cancel_left, ← polynomial.C_sub, ← polynomial.C_mul, inv_mul_cancel h, polynomial.C_1]⟩ /-- If `f` is a polynomial over a field, and `a : K` satisfies `f' a ≠ 0`, then `f / (X - a)` is coprime with `X - a`. Note that we do not assume `f a = 0`, because `f / (X - a) = (f - f a) / (X - a)`. -/ lemma is_coprime_of_is_root_of_eval_derivative_ne_zero {K : Type*} [field K] (f : polynomial K) (a : K) (hf' : f.derivative.eval a ≠ 0) : is_coprime (X - C a : polynomial K) (f /ₘ (X - C a)) := begin refine or.resolve_left (dvd_or_coprime (X - C a) (f /ₘ (X - C a)) (irreducible_of_degree_eq_one (polynomial.degree_X_sub_C a))) _, contrapose! hf' with h, have key : (X - C a) * (f /ₘ (X - C a)) = f - (f %ₘ (X - C a)), { rw [eq_sub_iff_add_eq, ← eq_sub_iff_add_eq', mod_by_monic_eq_sub_mul_div], exact monic_X_sub_C a }, replace key := congr_arg derivative key, simp only [derivative_X, derivative_mul, one_mul, sub_zero, derivative_sub, mod_by_monic_X_sub_C_eq_C_eval, derivative_C] at key, have : (X - C a) ∣ derivative f := key ▸ (dvd_add h (dvd_mul_right _ _)), rw [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval] at this, rw [← C_inj, this, C_0], end lemma prod_multiset_root_eq_finset_root {p : polynomial R} (hzero : p ≠ 0) : (multiset.map (λ (a : R), X - C a) p.roots).prod = ∏ a in (multiset.to_finset p.roots), (λ (a : R), (X - C a) ^ (root_multiplicity a p)) a := by simp only [count_roots hzero, finset.prod_multiset_map_count] /-- The product `∏ (X - a)` for `a` inside the multiset `p.roots` divides `p`. -/ lemma prod_multiset_X_sub_C_dvd (p : polynomial R) : (multiset.map (λ (a : R), X - C a) p.roots).prod ∣ p := begin by_cases hp0 : p = 0, { simp only [hp0, roots_zero, is_unit_one, multiset.prod_zero, multiset.map_zero, is_unit.dvd] }, rw prod_multiset_root_eq_finset_root hp0, have hcoprime : pairwise (is_coprime on λ (a : R), polynomial.X - C (id a)) := pairwise_coprime_X_sub function.injective_id, have H : pairwise (is_coprime on λ (a : R), (polynomial.X - C (id a)) ^ (root_multiplicity a p)), { intros a b hdiff, exact (hcoprime a b hdiff).pow }, apply finset.prod_dvd_of_coprime (pairwise.pairwise_on H (↑(multiset.to_finset p.roots) : set R)), intros a h, rw multiset.mem_to_finset at h, exact pow_root_multiplicity_dvd p a end lemma roots_C_mul (p : polynomial R) {a : R} (hzero : a ≠ 0) : (C a * p).roots = p.roots := begin by_cases hpzero : p = 0, { simp only [hpzero, mul_zero] }, rw multiset.ext, intro b, have prodzero : C a * p ≠ 0, { simp only [hpzero, or_false, ne.def, mul_eq_zero, C_eq_zero, hzero, not_false_iff] }, rw [count_roots hpzero, count_roots prodzero, root_multiplicity_mul prodzero], have mulzero : root_multiplicity b (C a) = 0, { simp only [hzero, root_multiplicity_eq_zero, eval_C, is_root.def, not_false_iff] }, simp only [mulzero, zero_add] end end field end polynomial
f19820888fe0204429f27a1d7bb233f241282bb1
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/stuckMVarBug.lean
d75c0f9b42911b04a0d10a449714567275c7ef69
[ "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
479
lean
class HasMulComm (α : Type u) [Mul α] : Prop where mulComm : {a b : α} → a * b = b * a class A (α : Type u) where [Mul : Mul α] attribute [instance] A.mk A.Mul class B (α : Type u) where [Mul : Mul α] [HasMulComm : HasMulComm α] attribute [instance] B.mk B.Mul B.HasMulComm example [A α] [HasMulComm α] : B α := inferInstance section variable [A α] [HasMulComm α] example : B α := by exact inferInstance example : B α := inferInstance end
89b7fe6ab77ccec09b895e436c729452de8f707f
6065973b1fa7bbacba932011c9e2f32bf7bdd6c1
/src/algebra/big_operators/order.lean
0d25a9c23b88f4f8fe98b5caabc963cb03219937
[ "Apache-2.0" ]
permissive
khmacdonald/mathlib
90a0fa2222369fa69ed2fbfb841b74d2bdfd66cb
3669cb35c578441812ad30fd967d21a94b6f387e
refs/heads/master
1,675,863,801,090
1,609,761,876,000
1,609,761,876,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,478
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 algebra.big_operators.basic /-! # Results about big operators with values in an ordered algebraic structure. Mostly monotonicity results for the `∑` operation. -/ universes u v w open_locale big_operators variables {α : Type u} {β : Type v} {γ : Type w} namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_add_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (∑ x in s, g x) ≤ ∑ x in s, f (g x) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [linear_ordered_field α] {f : β → α} {s : finset β} : abs (∑ x in s, f x) ≤ ∑ x in s, abs (f x) := le_sum_of_subadditive _ abs_zero abs_add s f lemma abs_prod [linear_ordered_comm_ring α] {f : β → α} {s : finset β} : abs (∏ x in s, f x) = ∏ x in s, abs (f x) := (abs_hom.to_monoid_hom : α →* α).map_prod _ _ section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → (∑ x in s, f x) ≤ (∑ x in s, g x) := begin classical, apply finset.induction_on s, exact (λ _, le_refl _), assume a s ha ih h, have : f a + (∑ x in s, f x) ≤ g a + (∑ x in s, g x), from add_le_add (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] end theorem card_le_mul_card_image_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * t.card := calc s.card = (∑ a in t, (s.filter (λ x, f x = a)).card) : card_eq_sum_card_fiberwise Hf ... ≤ (∑ _ in t, n) : sum_le_sum hn ... = _ : by simp [mul_comm] theorem card_le_mul_card_image [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) : s.card ≤ n * (s.image f).card := card_le_mul_card_image_of_maps_to (λ x, mem_image_of_mem _) n hn theorem mul_card_image_le_card_of_maps_to [decidable_eq γ] {f : α → γ} {s : finset α} {t : finset γ} (Hf : ∀ a ∈ s, f a ∈ t) (n : ℕ) (hn : ∀ a ∈ t, n ≤ (s.filter (λ x, f x = a)).card) : n * t.card ≤ s.card := calc n * t.card = (∑ _ in t, n) : by simp [mul_comm] ... ≤ (∑ a in t, (s.filter (λ x, f x = a)).card) : sum_le_sum hn ... = s.card : by rw ← card_eq_sum_card_fiberwise Hf theorem mul_card_image_le_card [decidable_eq γ] {f : α → γ} (s : finset α) (n : ℕ) (hn : ∀ a ∈ s.image f, n ≤ (s.filter (λ x, f x = a)).card) : n * (s.image f).card ≤ s.card := mul_card_image_le_card_of_maps_to (λ x, mem_image_of_mem _) n hn lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ (∑ x in s, f x) := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : (∑ x in s, f x) ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) ≤ (∑ x in s₂ \ s₁, f x) + (∑ x in s₁, f x) : le_add_of_nonneg_left $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = ∑ x in s₂ \ s₁ ∪ s₁, f x : (sum_union sdiff_disjoint).symm ... = (∑ x in s₂, f x) : by rw [sdiff_union_of_subset h] lemma sum_mono_set_of_nonneg (hf : ∀ x, 0 ≤ f x) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset_of_nonneg hs $ λ x _ _, hf x lemma sum_fiberwise_le_sum_of_sum_fiber_nonneg [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (0 : β) ≤ ∑ x in s.filter (λ x, g x = y), f x) : (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ ∑ x in s, f x := calc (∑ y in t, ∑ x in s.filter (λ x, g x = y), f x) ≤ (∑ y in t ∪ s.image g, ∑ x in s.filter (λ x, g x = y), f x) : sum_le_sum_of_subset_of_nonneg (subset_union_left _ _) $ λ y hyts, h y ... = ∑ x in s, f x : sum_fiberwise_of_maps_to (λ x hx, mem_union.2 $ or.inr $ mem_image_of_mem _ hx) _ lemma sum_le_sum_fiberwise_of_sum_fiber_nonpos [decidable_eq γ] {s : finset α} {t : finset γ} {g : α → γ} {f : α → β} (h : ∀ y ∉ t, (∑ x in s.filter (λ x, g x = y), f x) ≤ 0) : (∑ x in s, f x) ≤ ∑ y in t, ∑ x in s.filter (λ x, g x = y), f x := @sum_fiberwise_le_sum_of_sum_fiber_nonneg α (order_dual β) _ _ _ _ _ _ _ h lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := begin classical, apply finset.induction_on s, exact λ _, ⟨λ _ _, false.elim, λ _, rfl⟩, assume a s ha ih H, have : ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] end lemma sum_eq_zero_iff_of_nonpos : (∀x∈s, f x ≤ 0) → ((∑ x in s, f x) = 0 ↔ ∀x∈s, f x = 0) := @sum_eq_zero_iff_of_nonneg _ (order_dual β) _ _ _ lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ (∑ x in s, f x) := have ∑ x in {a}, f x ≤ (∑ x in s, f x), from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_add_comm_monoid section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid β] @[simp] lemma sum_eq_zero_iff : ∑ x in s, f x = 0 ↔ ∀ x ∈ s, f x = 0 := sum_eq_zero_iff_of_nonneg $ λ x hx, zero_le (f x) lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_mono_set (f : α → β) : monotone (λ s, ∑ x in s, f x) := λ s₁ s₂ hs, sum_le_sum_of_subset hs lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : (∑ x in s₁, f x) ≤ (∑ x in s₂, f x) := by classical; calc (∑ x in s₁, f x) = ∑ x in s₁.filter (λx, f x = 0), f x + ∑ x in s₁.filter (λx, f x ≠ 0), f x : by rw [←sum_union, filter_union_filter_neg_eq]; exact disjoint_filter.2 (assume _ _ h n_h, n_h h) ... ≤ (∑ x in s₂, f x) : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_add_monoid section ordered_cancel_comm_monoid variables [ordered_cancel_add_comm_monoid β] theorem sum_lt_sum (Hle : ∀ i ∈ s, f i ≤ g i) (Hlt : ∃ i ∈ s, f i < g i) : (∑ x in s, f x) < (∑ x in s, g x) := begin classical, rcases Hlt with ⟨i, hi, hlt⟩, rw [← insert_erase hi, sum_insert (not_mem_erase _ _), sum_insert (not_mem_erase _ _)], exact add_lt_add_of_lt_of_le hlt (sum_le_sum $ λ j hj, Hle j $ mem_of_mem_erase hj) end lemma sum_lt_sum_of_nonempty (hs : s.nonempty) (Hlt : ∀ x ∈ s, f x < g x) : (∑ x in s, f x) < (∑ x in s, g x) := begin apply sum_lt_sum, { intros i hi, apply le_of_lt (Hlt i hi) }, cases hs with i hi, exact ⟨i, hi, Hlt i hi⟩, end lemma sum_lt_sum_of_subset [decidable_eq α] (h : s₁ ⊆ s₂) {i : α} (hi : i ∈ s₂ \ s₁) (hpos : 0 < f i) (hnonneg : ∀ j ∈ s₂ \ s₁, 0 ≤ f j) : (∑ x in s₁, f x) < (∑ x in s₂, f x) := calc (∑ x in s₁, f x) < (∑ x in insert i s₁, f x) : begin simp only [mem_sdiff] at hi, rw sum_insert hi.2, exact lt_add_of_pos_left (∑ x in s₁, f x) hpos, end ... ≤ (∑ x in s₂, f x) : begin simp only [mem_sdiff] at hi, apply sum_le_sum_of_subset_of_nonneg, { simp [finset.insert_subset, h, hi.1] }, { assume x hx h'x, apply hnonneg x, simp [mem_insert, not_or_distrib] at h'x, rw mem_sdiff, simp [hx, h'x] } end end ordered_cancel_comm_monoid section linear_ordered_cancel_comm_monoid variables [linear_ordered_cancel_add_comm_monoid β] theorem exists_lt_of_sum_lt (Hlt : (∑ x in s, f x) < ∑ x in s, g x) : ∃ i ∈ s, f i < g i := begin contrapose! Hlt with Hle, exact sum_le_sum Hle end theorem exists_le_of_sum_le (hs : s.nonempty) (Hle : (∑ x in s, f x) ≤ ∑ x in s, g x) : ∃ i ∈ s, f i ≤ g i := begin contrapose! Hle with Hlt, rcases hs with ⟨i, hi⟩, exact sum_lt_sum (λ i hi, le_of_lt (Hlt i hi)) ⟨i, hi, Hlt i hi⟩ end lemma exists_pos_of_sum_zero_of_exists_nonzero (f : α → β) (h₁ : ∑ e in s, f e = 0) (h₂ : ∃ x ∈ s, f x ≠ 0) : ∃ x ∈ s, 0 < f x := begin contrapose! h₁, obtain ⟨x, m, x_nz⟩ : ∃ x ∈ s, f x ≠ 0 := h₂, apply ne_of_lt, calc ∑ e in s, f e < ∑ e in s, 0 : sum_lt_sum h₁ ⟨x, m, lt_of_le_of_ne (h₁ x m) x_nz⟩ ... = 0 : by rw [finset.sum_const, nsmul_zero], end end linear_ordered_cancel_comm_monoid section linear_ordered_comm_ring variables [linear_ordered_comm_ring β] open_locale classical /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_nonneg {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) : 0 ≤ (∏ x in s, f x) := prod_induction f (λ x, 0 ≤ x) (λ _ _ ha hb, mul_nonneg ha hb) zero_le_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_pos {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 < f x) : 0 < (∏ x in s, f x) := prod_induction f (λ x, 0 < x) (λ _ _ ha hb, mul_pos ha hb) zero_lt_one h0 /- this is also true for a ordered commutative multiplicative monoid -/ lemma prod_le_prod {s : finset α} {f g : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ g x) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin induction s using finset.induction with a s has ih h, { simp }, { simp [has], apply mul_le_mul, exact h1 a (mem_insert_self a s), apply ih (λ x H, h0 _ _) (λ x H, h1 _ _); exact (mem_insert_of_mem H), apply prod_nonneg (λ x H, h0 x (mem_insert_of_mem H)), apply le_trans (h0 a (mem_insert_self a s)) (h1 a (mem_insert_self a s)) } end lemma prod_le_one {s : finset α} {f : α → β} (h0 : ∀(x ∈ s), 0 ≤ f x) (h1 : ∀(x ∈ s), f x ≤ 1) : (∏ x in s, f x) ≤ 1 := begin convert ← prod_le_prod h0 h1, exact finset.prod_const_one end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `linear_ordered_comm_ring`. -/ lemma prod_add_prod_le {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) (hg : ∀ i ∈ s, 0 ≤ g i) (hh : ∀ i ∈ s, 0 ≤ h i) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (mul_le_mul_of_nonneg_right h2i _), { rw [right_distrib], apply add_le_add; apply mul_le_mul_of_nonneg_left; try { apply prod_le_prod }; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption }, { apply prod_nonneg, simp only [and_imp, mem_sdiff, mem_singleton], intros j h1j h2j, refine le_trans (hg j h1j) (hgf j h1j h2j) } end end linear_ordered_comm_ring section canonically_ordered_comm_semiring variables [canonically_ordered_comm_semiring β] lemma prod_le_prod' {s : finset α} {f g : α → β} (h : ∀ i ∈ s, f i ≤ g i) : (∏ x in s, f x) ≤ (∏ x in s, g x) := begin classical, induction s using finset.induction with a s has ih h, { simp }, { rw [finset.prod_insert has, finset.prod_insert has], apply canonically_ordered_semiring.mul_le_mul, { exact h _ (finset.mem_insert_self a s) }, { exact ih (λ i hi, h _ (finset.mem_insert_of_mem hi)) } } end /-- If `g, h ≤ f` and `g i + h i ≤ f i`, then the product of `f` over `s` is at least the sum of the products of `g` and `h`. This is the version for `canonically_ordered_comm_semiring`. -/ lemma prod_add_prod_le' {s : finset α} {i : α} {f g h : α → β} (hi : i ∈ s) (h2i : g i + h i ≤ f i) (hgf : ∀ j ∈ s, j ≠ i → g j ≤ f j) (hhf : ∀ j ∈ s, j ≠ i → h j ≤ f j) : ∏ i in s, g i + ∏ i in s, h i ≤ ∏ i in s, f i := begin classical, simp_rw [← mul_prod_diff_singleton hi], refine le_trans _ (canonically_ordered_semiring.mul_le_mul_right' h2i _), rw [right_distrib], apply add_le_add; apply canonically_ordered_semiring.mul_le_mul_left'; apply prod_le_prod'; simp only [and_imp, mem_sdiff, mem_singleton]; intros; apply_assumption; assumption end end canonically_ordered_comm_semiring end finset namespace with_top open finset /-- A product of finite numbers is still finite -/ lemma prod_lt_top [canonically_ordered_comm_semiring β] [nontrivial β] [decidable_eq β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → (∏ x in s, f x) < ⊤ := λ h, prod_induction f (λ a, a < ⊤) (λ a b, mul_lt_top) (coe_lt_top 1) h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top [ordered_add_comm_monoid β] {s : finset α} {f : α → with_top β} : (∀a∈s, f a < ⊤) → (∑ x in s, f x) < ⊤ := λ h, sum_induction f (λ a, a < ⊤) (by { simp_rw add_lt_top, tauto }) zero_lt_top h /-- A sum of finite numbers is still finite -/ lemma sum_lt_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) < ⊤ ↔ (∀a∈s, f a < ⊤) := iff.intro (λh a ha, lt_of_le_of_lt (single_le_sum (λa ha, zero_le _) ha) h) sum_lt_top /-- A sum of numbers is infinite iff one of them is infinite -/ lemma sum_eq_top_iff [canonically_ordered_add_monoid β] {s : finset α} {f : α → with_top β} : (∑ x in s, f x) = ⊤ ↔ (∃a∈s, f a = ⊤) := begin rw ← not_iff_not, push_neg, simp only [← lt_top_iff_ne_top], exact sum_lt_top_iff end end with_top
1f7bb719067cfe495d161fee0410be36d04d7209
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/tests/lean/run/1728.lean
6efb439e3d977809e0e36781a3250b9af4cc98e8
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
709
lean
structure Bijection ( U V : Type ) := ( morphism : U → V ) ( inverse : V → U ) ( witness_1 : ∀ u : U, inverse (morphism u) = u ) ( witness_2 : ∀ v : V, morphism (inverse v) = v ) class Finite ( α : Type ) := ( cardinality : nat ) ( bijection : Bijection α (fin cardinality) ) lemma empty_exfalso (x : false) : empty := begin exfalso, trivial end instance empty_is_Finite : Finite empty := { cardinality := 0, bijection := begin split, intros, induction u, intros, induction v, trace_state, cases v_property, repeat {admit} end }
34eeda77531fdc3580ba615ab5889ed302ae6a74
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/id.lean
1b621eb9a2215bdebb8bd100d77b194fc737512f
[ "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
148
lean
check id id set_option pp.universes true check id id check id Prop check id num check @id.{0} check @id.{1} check id num.zero check @eq check eq eq
47face2b66eae93892fe5992f0c5eaf9441d667b
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/test/zify.lean
d5aa75556d9f33570966070c2bff1fc35a4878c6
[ "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
697
lean
import tactic.zify example (a b c x y z : ℕ) (h : ¬ x*y*z < 0) : a + 3*b > c := begin zify at h ⊢, guard_hyp h := ¬↑x * ↑y * ↑z < (0 : ℤ), guard_target ↑c < (↑a : ℤ) + 3 * ↑b, admit end example (a b : ℕ) : a ≤ b := begin zify, guard_target (a : ℤ) ≤ b, admit end example (a b : ℕ) (h : a = b ∧ b < a) : false := begin zify at h, cases h with ha hb, apply ne_of_lt hb, rw ha end example (a b c : ℕ) (h : a - b < c) (hab : b ≤ a) : false := begin zify [hab] at h, guard_hyp h := (a : ℤ) - b < c, admit end example (a b c : ℕ) (h : a + b ≠ c) : false := begin zify at h, guard_hyp h := (a : ℤ) + b ≠ c, admit end
0cf79c03d073a6a0c250781accec9565d9a11e20
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/thm95.lean
a8c20547b10f6ae9f977e060b091e2a91bcfd438
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,209
lean
import pseudo_normed_group.system_of_complexes import polyhedral_lattice.pseudo_normed_group import Mbar.pseudo_normed_group open_locale nnreal -- enable the notation `ℝ≥0` for the nonnegative real numbers. variables (BD : breen_deligne.package) variables (c' : ℕ → ℝ≥0) -- implicit constants, chosen once and for all -- see the sentence after that statement of Thm 9.5 namespace ProFiltPseuNormGrpWithTinv universe variables u def Hom {r' : ℝ≥0} (Λ : Type) (M : Type u) [normed_group Λ] [polyhedral_lattice Λ] [profinitely_filtered_pseudo_normed_group_with_Tinv r' M] : ProFiltPseuNormGrpWithTinv.{u} r' := of r' (Λ →+ M) end ProFiltPseuNormGrpWithTinv open ProFiltPseuNormGrpWithTinv /-- Theorem 9.5 in [Analytic] -/ theorem thm95 [BD.suitable c'] (r r' : ℝ≥0) [fact (0 < r)] [fact (0 < r')] [fact (r < r')] [fact (r' ≤ 1)] : ∀ m : ℕ, ∃ (k K : ℝ≥0) [fact (1 ≤ k)], ∀ (Λ : Type) [normed_group Λ],​ ∀ [polyhedral_lattice Λ], ∃ c₀ : ℝ≥0, ∀ (S : Type) [fintype S], ∀ (V : NormedGroup) [normed_with_aut r V], ​(BD.system c' r V r' (Hom Λ (Mbar r' S))).is_bounded_exact k K m c₀ := sorry
529ef0b8a4d2224742334eab72a6dc6ca0e76a1a
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/nat/order.lean
848ebc2e9843c3e8bdaf75108015ec762e73e82c
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,900
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.nat.order Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad The order relation on the natural numbers. -/ import data.nat.basic algebra.ordered_ring open eq.ops namespace nat /- lt and le -/ definition le_of_lt_or_eq {m n : ℕ} (H : m < n ∨ m = n) : m ≤ n := or.elim H (take H1, le_of_lt H1) (take H1, H1 ▸ !le.refl) definition lt.by_cases {a b : ℕ} {P : Prop} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := or.elim !lt.trichotomy (assume H, H1 H) (assume H, or.elim H (assume H', H2 H') (assume H', H3 H')) definition lt_or_eq_of_le {m n : ℕ} (H : m ≤ n) : m < n ∨ m = n := lt.by_cases (assume H1 : m < n, or.inl H1) (assume H1 : m = n, or.inr H1) (assume H1 : m > n, absurd (lt_of_le_of_lt H H1) !lt.irrefl) theorem le_iff_lt_or_eq (m n : ℕ) : m ≤ n ↔ m < n ∨ m = n := iff.intro lt_or_eq_of_le le_of_lt_or_eq definition lt_of_le_and_ne {m n : ℕ} (H1 : m ≤ n) (H2 : m ≠ n) : m < n := or.elim (lt_or_eq_of_le H1) (take H3 : m < n, H3) (take H3 : m = n, absurd H3 H2) theorem lt_iff_le_and_ne (m n : ℕ) : m < n ↔ m ≤ n ∧ m ≠ n := iff.intro (take H, and.intro (le_of_lt H) (take H1, lt.irrefl _ (H1 ▸ H))) (take H, lt_of_le_and_ne (and.elim_left H) (and.elim_right H)) theorem le_add_right (n k : ℕ) : n ≤ n + k := nat.induction_on k (calc n ≤ n : le.refl n ... = n + zero : add_zero) (λ k (ih : n ≤ n + k), calc n ≤ succ (n + k) : le_succ_of_le ih ... = n + succ k : add_succ) theorem le_add_left (n m : ℕ): n ≤ m + n := !add.comm ▸ !le_add_right theorem le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m := h ▸ le_add_right n k theorem le.elim {n m : ℕ} (h : n ≤ m) : ∃k, n + k = m := le.rec_on h (exists.intro 0 rfl) (λ m (h : n < m), lt.rec_on h (exists.intro 1 rfl) (λ b hlt (ih : ∃ (k : ℕ), n + k = b), obtain (k : ℕ) (h : n + k = b), from ih, exists.intro (succ k) (calc n + succ k = succ (n + k) : add_succ ... = succ b : h))) theorem le.total {m n : ℕ} : m ≤ n ∨ n ≤ m := lt.by_cases (assume H : m < n, or.inl (le_of_lt H)) (assume H : m = n, or.inl (H ▸ !le.refl)) (assume H : m > n, or.inr (le_of_lt H)) /- addition -/ theorem add_le_add_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, le.intro (calc k + n + l = k + (n + l) : !add.assoc ... = k + m : {Hl}) theorem add_le_add_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k := !add.comm ▸ !add.comm ▸ add_le_add_left H k theorem le_of_add_le_add_left {k n m : ℕ} (H : k + n ≤ k + m) : n ≤ m := obtain (l : ℕ) (Hl : k + n + l = k + m), from (le.elim H), le.intro (add.cancel_left (calc k + (n + l) = k + n + l : (!add.assoc)⁻¹ ... = k + m : Hl)) theorem add_lt_add_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m := lt_of_succ_le (!add_succ ▸ add_le_add_left (succ_le_of_lt H) k) theorem add_lt_add_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k := !add.comm ▸ !add.comm ▸ add_lt_add_left H k theorem lt_add_of_pos_right {n k : ℕ} (H : k > 0) : n < n + k := !add_zero ▸ add_lt_add_left H n /- multiplication -/ theorem mul_le_mul_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m := obtain (l : ℕ) (Hl : n + l = m), from le.elim H, have H2 : k * n + k * l = k * m, by rewrite [-mul.left_distrib, Hl], le.intro H2 theorem mul_le_mul_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k := !mul.comm ▸ !mul.comm ▸ (mul_le_mul_left H k) theorem mul_le_mul {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l := le.trans (mul_le_mul_right H1 m) (mul_le_mul_left H2 k) theorem mul_lt_mul_of_pos_left {n m k : ℕ} (H : n < m) (Hk : k > 0) : k * n < k * m := have H2 : k * n < k * n + k, from lt_add_of_pos_right Hk, have H3 : k * n + k ≤ k * m, from !mul_succ ▸ mul_le_mul_left (succ_le_of_lt H) k, lt_of_lt_of_le H2 H3 theorem mul_lt_mul_of_pos_right {n m k : ℕ} (H : n < m) (Hk : k > 0) : n * k < m * k := !mul.comm ▸ !mul.comm ▸ mul_lt_mul_of_pos_left H Hk theorem le.antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m := obtain (k : ℕ) (Hk : n + k = m), from (le.elim H1), obtain (l : ℕ) (Hl : m + l = n), from (le.elim H2), have L1 : k + l = 0, from add.cancel_left (calc n + (k + l) = n + k + l : (!add.assoc)⁻¹ ... = m + l : {Hk} ... = n : Hl ... = n + 0 : (!add_zero)⁻¹), have L2 : k = 0, from eq_zero_of_add_eq_zero_right L1, calc n = n + 0 : (!add_zero)⁻¹ ... = n + k : {L2⁻¹} ... = m : Hk theorem zero_le (n : ℕ) : 0 ≤ n := le.intro !zero_add /- nat is an instance of a linearly ordered semiring -/ section open [classes] algebra protected definition linear_ordered_semiring [instance] [reducible] : algebra.linear_ordered_semiring nat := ⦃ algebra.linear_ordered_semiring, nat.comm_semiring, add_left_cancel := @add.cancel_left, add_right_cancel := @add.cancel_right, lt := lt, le := le, le_refl := le.refl, le_trans := @le.trans, le_antisymm := @le.antisymm, le_total := @le.total, le_iff_lt_or_eq := @le_iff_lt_or_eq, lt_iff_le_and_ne := lt_iff_le_and_ne, add_le_add_left := @add_le_add_left, le_of_add_le_add_left := @le_of_add_le_add_left, zero_ne_one := ne.symm (succ_ne_zero zero), mul_le_mul_of_nonneg_left := (take a b c H1 H2, mul_le_mul_left H1 c), mul_le_mul_of_nonneg_right := (take a b c H1 H2, mul_le_mul_right H1 c), mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right ⦄ migrate from algebra with nat replacing has_le.ge → ge, has_lt.gt → gt hiding pos_of_mul_pos_left, pos_of_mul_pos_right, lt_of_mul_lt_mul_left, lt_of_mul_lt_mul_right end section port_algebra open [classes] algebra theorem add_pos_left : ∀{a : ℕ}, 0 < a → ∀b : ℕ, 0 < a + b := take a H b, @algebra.add_pos_of_pos_of_nonneg _ _ a b H !zero_le theorem add_pos_right : ∀{a : ℕ}, 0 < a → ∀b : ℕ, 0 < b + a := take a H b, !add.comm ▸ add_pos_left H b theorem add_eq_zero_iff_eq_zero_and_eq_zero : ∀{a b : ℕ}, a + b = 0 ↔ a = 0 ∧ b = 0 := take a b : ℕ, @algebra.add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg _ _ a b !zero_le !zero_le theorem le_add_of_le_left : ∀{a b c : ℕ}, b ≤ c → b ≤ a + c := take a b c H, @algebra.le_add_of_nonneg_of_le _ _ a b c !zero_le H theorem le_add_of_le_right : ∀{a b c : ℕ}, b ≤ c → b ≤ c + a := take a b c H, @algebra.le_add_of_le_of_nonneg _ _ a b c H !zero_le theorem lt_add_of_lt_left : ∀{b c : ℕ}, b < c → ∀a, b < a + c := take b c H a, @algebra.lt_add_of_nonneg_of_lt _ _ a b c !zero_le H theorem lt_add_of_lt_right : ∀{b c : ℕ}, b < c → ∀a, b < c + a := take b c H a, @algebra.lt_add_of_lt_of_nonneg _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_left : ∀{a b c : ℕ}, c * a < c * b → a < b := take a b c H, @algebra.lt_of_mul_lt_mul_left _ _ a b c H !zero_le theorem lt_of_mul_lt_mul_right : ∀{a b c : ℕ}, a * c < b * c → a < b := take a b c H, @algebra.lt_of_mul_lt_mul_right _ _ a b c H !zero_le theorem pos_of_mul_pos_left : ∀{a b : ℕ}, 0 < a * b → 0 < b := take a b H, @algebra.pos_of_mul_pos_left _ _ a b H !zero_le theorem pos_of_mul_pos_right : ∀{a b : ℕ}, 0 < a * b → 0 < a := take a b H, @algebra.pos_of_mul_pos_right _ _ a b H !zero_le end port_algebra theorem zero_le_one : 0 ≤ 1 := dec_trivial theorem zero_lt_one : 0 < 1 := dec_trivial /- properties specific to nat -/ theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m := lt_of_succ_le (le.intro H) theorem lt_elim {n m : ℕ} (H : n < m) : ∃k, succ n + k = m := le.elim (succ_le_of_lt H) theorem lt_add_succ (n m : ℕ) : n < n + succ m := lt_intro !succ_add_eq_succ_add theorem eq_zero_of_le_zero {n : ℕ} (H : n ≤ 0) : n = 0 := obtain (k : ℕ) (Hk : n + k = 0), from le.elim H, eq_zero_of_add_eq_zero_right Hk /- succ and pred -/ theorem lt_iff_succ_le (m n : nat) : m < n ↔ succ m ≤ n := iff.intro succ_le_of_lt lt_of_succ_le theorem not_succ_le_zero (n : ℕ) : ¬ succ n ≤ 0 := (assume H : succ n ≤ 0, have H2 : succ n = 0, from eq_zero_of_le_zero H, absurd H2 !succ_ne_zero) theorem succ_le_succ {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m := !add_one ▸ !add_one ▸ add_le_add_right H 1 theorem le_of_succ_le_succ {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m := le_of_add_le_add_right ((!add_one)⁻¹ ▸ (!add_one)⁻¹ ▸ H) theorem self_le_succ (n : ℕ) : n ≤ succ n := le.intro !add_one theorem succ_le_or_eq_of_le {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m := or.elim (lt_or_eq_of_le H) (assume H1 : n < m, or.inl (succ_le_of_lt H1)) (assume H1 : n = m, or.inr H1) theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m := nat.cases_on n (assume H : pred 0 ≤ m, !zero_le) (take n', assume H : pred (succ n') ≤ m, have H1 : n' ≤ m, from pred_succ n' ▸ H, succ_le_succ H1) theorem pred_le_of_le_succ {n m : ℕ} : n ≤ succ m → pred n ≤ m := nat.cases_on n (assume H, !pred_zero⁻¹ ▸ zero_le m) (take n', assume H : succ n' ≤ succ m, have H1 : n' ≤ m, from le_of_succ_le_succ H, !pred_succ⁻¹ ▸ H1) theorem succ_le_of_le_pred {n m : ℕ} : succ n ≤ m → n ≤ pred m := nat.cases_on m (assume H, absurd H !not_succ_le_zero) (take m', assume H : succ n ≤ succ m', have H1 : n ≤ m', from le_of_succ_le_succ H, !pred_succ⁻¹ ▸ H1) theorem pred_le_pred_of_le {n m : ℕ} : n ≤ m → pred n ≤ pred m := nat.cases_on n (assume H, pred_zero⁻¹ ▸ zero_le (pred m)) (take n', assume H : succ n' ≤ m, !pred_succ⁻¹ ▸ succ_le_of_le_pred H) theorem lt_of_pred_lt_pred {n m : ℕ} (H : pred n < pred m) : n < m := lt_of_not_le (take H1 : m ≤ n, not_lt_of_le (pred_le_pred_of_le H1) H) theorem le_or_eq_succ_of_le_succ {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m := or_of_or_of_imp_left (succ_le_or_eq_of_le H) (take H2 : succ n ≤ succ m, show n ≤ m, from le_of_succ_le_succ H2) theorem le_pred_self (n : ℕ) : pred n ≤ n := nat.cases_on n (pred_zero⁻¹ ▸ !le.refl) (take k : ℕ, (!pred_succ)⁻¹ ▸ !self_le_succ) theorem succ_pos (n : ℕ) : 0 < succ n := !zero_lt_succ theorem succ_pred_of_pos {n : ℕ} (H : n > 0) : succ (pred n) = n := (or_resolve_right (eq_zero_or_eq_succ_pred n) (ne.symm (ne_of_lt H)))⁻¹ theorem exists_eq_succ_of_lt {n m : ℕ} (H : n < m) : exists k, m = succ k := discriminate (take (Hm : m = 0), absurd (Hm ▸ H) !not_lt_zero) (take (l : ℕ) (Hm : m = succ l), exists.intro l Hm) theorem lt_succ_self (n : ℕ) : n < succ n := lt.base n theorem le_of_lt_succ {n m : ℕ} (H : n < succ m) : n ≤ m := le_of_succ_le_succ (succ_le_of_lt H) /- other forms of induction -/ protected theorem strong_induction_on {P : nat → Prop} (n : ℕ) (H : ∀n, (∀m, m < n → P m) → P n) : P n := have H1 : ∀ {n m : nat}, m < n → P m, from take n, nat.induction_on n (show ∀m, m < 0 → P m, from take m H, absurd H !not_lt_zero) (take n', assume IH : ∀ {m : nat}, m < n' → P m, have H2: P n', from H n' @IH, show ∀m, m < succ n' → P m, from take m, assume H3 : m < succ n', or.elim (lt_or_eq_of_le (le_of_lt_succ H3)) (assume H4: m < n', IH H4) (assume H4: m = n', H4⁻¹ ▸ H2)), H1 !lt_succ_self protected theorem case_strong_induction_on {P : nat → Prop} (a : nat) (H0 : P 0) (Hind : ∀(n : nat), (∀m, m ≤ n → P m) → P (succ n)) : P a := strong_induction_on a ( take n, show (∀m, m < n → P m) → P n, from nat.cases_on n (assume H : (∀m, m < 0 → P m), show P 0, from H0) (take n, assume H : (∀m, m < succ n → P m), show P (succ n), from Hind n (take m, assume H1 : m ≤ n, H _ (lt_succ_of_le H1)))) /- pos -/ theorem by_cases_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀ {y : nat}, y > 0 → P y) : P y := nat.cases_on y H0 (take y, H1 !succ_pos) theorem eq_zero_or_pos (n : ℕ) : n = 0 ∨ n > 0 := or_of_or_of_imp_left (or.swap (lt_or_eq_of_le !zero_le)) (take H : 0 = n, H⁻¹) theorem pos_of_ne_zero {n : ℕ} (H : n ≠ 0) : n > 0 := or.elim !eq_zero_or_pos (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2) theorem ne_zero_of_pos {n : ℕ} (H : n > 0) : n ≠ 0 := ne.symm (ne_of_lt H) theorem exists_eq_succ_of_pos {n : ℕ} (H : n > 0) : exists l, n = succ l := exists_eq_succ_of_lt H theorem pos_of_dvd_of_pos {m n : ℕ} (H1 : m ∣ n) (H2 : n > 0) : m > 0 := pos_of_ne_zero (assume H3 : m = 0, have H4 : n = 0, from eq_zero_of_zero_dvd (H3 ▸ H1), ne_of_lt H2 H4⁻¹) /- multiplication -/ theorem mul_lt_mul_of_le_of_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_right H1 m) (mul_lt_mul_of_pos_left H2 Hk) theorem mul_lt_mul_of_lt_of_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l := lt_of_le_of_lt (mul_le_mul_left H2 n) (mul_lt_mul_of_pos_right H1 Hl) theorem mul_lt_mul_of_le_of_le {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l := have H3 : n * m ≤ k * m, from mul_le_mul_right (le_of_lt H1) m, have H4 : k * m < k * l, from mul_lt_mul_of_pos_left H2 (lt_of_le_of_lt !zero_le H1), lt_of_le_of_lt H3 H4 theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k := have H2 : n * m ≤ n * k, from H ▸ !le.refl, have H3 : n * k ≤ n * m, from H ▸ !le.refl, have H4 : m ≤ k, from le_of_mul_le_mul_left H2 Hn, have H5 : k ≤ m, from le_of_mul_le_mul_left H3 Hn, le.antisymm H4 H5 theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := eq_of_mul_eq_mul_left Hm (!mul.comm ▸ !mul.comm ▸ H) theorem eq_zero_or_eq_of_mul_eq_mul_left {n m k : ℕ} (H : n * m = n * k) : n = 0 ∨ m = k := or_of_or_of_imp_right !eq_zero_or_pos (assume Hn : n > 0, eq_of_mul_eq_mul_left Hn H) theorem eq_zero_or_eq_of_mul_eq_mul_right {n m k : ℕ} (H : n * m = k * m) : m = 0 ∨ n = k := eq_zero_or_eq_of_mul_eq_mul_left (!mul.comm ▸ !mul.comm ▸ H) theorem eq_one_of_mul_eq_one_right {n m : ℕ} (H : n * m = 1) : n = 1 := have H2 : n * m > 0, from H⁻¹ ▸ !succ_pos, have H3 : n > 0, from pos_of_mul_pos_right H2, have H4 : m > 0, from pos_of_mul_pos_left H2, or.elim (le_or_gt n 1) (assume H5 : n ≤ 1, show n = 1, from le.antisymm H5 (succ_le_of_lt H3)) (assume H5 : n > 1, have H6 : n * m ≥ 2 * 1, from mul_le_mul (succ_le_of_lt H5) (succ_le_of_lt H4), have H7 : 1 ≥ 2, from !mul_one ▸ H ▸ H6, absurd !lt_succ_self (not_lt_of_le H7)) theorem eq_one_of_mul_eq_one_left {n m : ℕ} (H : n * m = 1) : m = 1 := eq_one_of_mul_eq_one_right (!mul.comm ▸ H) theorem eq_one_of_mul_eq_self_left {n m : ℕ} (Hpos : n > 0) (H : m * n = n) : m = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ !one_mul⁻¹) theorem eq_one_of_mul_eq_self_right {n m : ℕ} (Hpos : m > 0) (H : m * n = m) : n = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {n : ℕ} (H : n ∣ 1) : n = 1 := dvd.elim H (take m, assume H1 : 1 = n * m, eq_one_of_mul_eq_one_right H1⁻¹) end nat
46da6cb65bb20e8d6557ffd85f4dd84da9ad810e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/mllist_auto.lean
5a5fb1142c1b5c878b0a94527a6bb08f1c10b1d4
[]
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
621
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro, Keeley Hoek, Simon Hudon, Scott Morrison Monadic lazy lists. The inductive construction is not allowed outside of meta (indeed, we can build infinite objects). This isn't so bad, as the typical use is with the tactic monad, in any case. As we're in meta anyway, we don't bother with proofs about these constructions. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.option.defs import Mathlib.PostPort namespace Mathlib end Mathlib
1f094a59376e2a099e159f02015a151803bba844
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/adjunctions/initial.lean
b9e81713ac5f9f8ff655a7c3ed42c6b66ffe8e7b
[]
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
843
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import ..adjunctions import ..universal.comma_categories open categories open categories.functor open categories.natural_transformation open categories.comma open categories.initial namespace categories.adjunctions -- PROJECT -- definition unit_component_in_slice_category -- { C D : Category } { L : Functor C D } { R : Functor D C } ( A : Adjunction L R ) ( X : C.Obj ) -- : (SliceCategory X).Obj := sorry -- definition unit_components_initial_in_slice_category -- { C D : Category } { L : Functor C D } { R : Functor D C } ( A : Adjunction L R ) ( X : C.Obj ) -- : is_initial (unit_component_in_slice_category A X) := sorry -- and so on end categories.adjunctions
9a5f4a84f6907434592e67ef265c9e65371b5b02
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/limits/concrete_category.lean
01d3a7451738ac71c777120efa14a86f3360f0af
[ "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
12,327
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Adam Topaz -/ import category_theory.limits.preserves.basic import category_theory.limits.types import category_theory.limits.shapes.wide_pullbacks import category_theory.limits.shapes.multiequalizer import category_theory.concrete_category.basic import category_theory.limits.shapes.kernels import tactic.apply_fun /-! # Facts about (co)limits of functors into concrete categories -/ universes w v u open category_theory namespace category_theory.limits local attribute [instance] concrete_category.has_coe_to_fun concrete_category.has_coe_to_sort section limits variables {C : Type u} [category.{v} C] [concrete_category.{(max w v)} C] {J : Type w} [small_category J] (F : J ⥤ C) [preserves_limit F (forget C)] lemma concrete.to_product_injective_of_is_limit {D : cone F} (hD : is_limit D) : function.injective (λ (x : D.X) (j : J), D.π.app j x) := begin let E := (forget C).map_cone D, let hE : is_limit E := is_limit_of_preserves _ hD, let G := types.limit_cone.{w v} (F ⋙ forget C), let hG := types.limit_cone_is_limit.{w v} (F ⋙ forget C), let T : E.X ≅ G.X := hE.cone_point_unique_up_to_iso hG, change function.injective (T.hom ≫ (λ x j, G.π.app j x)), have h : function.injective T.hom, { intros a b h, suffices : T.inv (T.hom a) = T.inv (T.hom b), by simpa, rw h }, suffices : function.injective (λ (x : G.X) j, G.π.app j x), by exact this.comp h, apply subtype.ext, end lemma concrete.is_limit_ext {D : cone F} (hD : is_limit D) (x y : D.X) : (∀ j, D.π.app j x = D.π.app j y) → x = y := λ h, concrete.to_product_injective_of_is_limit _ hD (funext h) lemma concrete.limit_ext [has_limit F] (x y : limit F) : (∀ j, limit.π F j x = limit.π F j y) → x = y := concrete.is_limit_ext F (limit.is_limit _) _ _ section wide_pullback open wide_pullback open wide_pullback_shape lemma concrete.wide_pullback_ext {B : C} {ι : Type w} {X : ι → C} (f : Π j : ι, X j ⟶ B) [has_wide_pullback B X f] [preserves_limit (wide_cospan B X f) (forget C)] (x y : wide_pullback B X f) (h₀ : base f x = base f y) (h : ∀ j, π f j x = π f j y) : x = y := begin apply concrete.limit_ext, rintro (_|j), { exact h₀ }, { apply h } end lemma concrete.wide_pullback_ext' {B : C} {ι : Type w} [nonempty ι] {X : ι → C} (f : Π j : ι, X j ⟶ B) [has_wide_pullback.{w} B X f] [preserves_limit (wide_cospan B X f) (forget C)] (x y : wide_pullback B X f) (h : ∀ j, π f j x = π f j y) : x = y := begin apply concrete.wide_pullback_ext _ _ _ _ h, inhabit ι, simp only [← π_arrow f (arbitrary _), comp_apply, h], end end wide_pullback section multiequalizer lemma concrete.multiequalizer_ext {I : multicospan_index.{w} C} [has_multiequalizer I] [preserves_limit I.multicospan (forget C)] (x y : multiequalizer I) (h : ∀ (t : I.L), multiequalizer.ι I t x = multiequalizer.ι I t y) : x = y := begin apply concrete.limit_ext, rintros (a|b), { apply h }, { rw [← limit.w I.multicospan (walking_multicospan.hom.fst b), comp_apply, comp_apply, h] } end /-- An auxiliary equivalence to be used in `multiequalizer_equiv` below.-/ def concrete.multiequalizer_equiv_aux (I : multicospan_index C) : (I.multicospan ⋙ (forget C)).sections ≃ { x : Π (i : I.L), I.left i // ∀ (i : I.R), I.fst i (x _) = I.snd i (x _) } := { to_fun := λ x, ⟨λ i, x.1 (walking_multicospan.left _), λ i, begin have a := x.2 (walking_multicospan.hom.fst i), have b := x.2 (walking_multicospan.hom.snd i), rw ← b at a, exact a, end⟩, inv_fun := λ x, { val := λ j, match j with | walking_multicospan.left a := x.1 _ | walking_multicospan.right b := I.fst b (x.1 _) end, property := begin rintros (a|b) (a'|b') (f|f|f), { change (I.multicospan.map (𝟙 _)) _ = _, simp }, { refl }, { dsimp, erw ← x.2 b', refl }, { change (I.multicospan.map (𝟙 _)) _ = _, simp }, end }, left_inv := begin intros x, ext (a|b), { refl }, { change _ = x.val _, rw ← x.2 (walking_multicospan.hom.fst b), refl } end, right_inv := by { intros x, ext i, refl } } /-- The equivalence between the noncomputable multiequalizer and and the concrete multiequalizer. -/ noncomputable def concrete.multiequalizer_equiv (I : multicospan_index.{w} C) [has_multiequalizer I] [preserves_limit I.multicospan (forget C)] : (multiequalizer I : C) ≃ { x : Π (i : I.L), I.left i // ∀ (i : I.R), I.fst i (x _) = I.snd i (x _) } := let h1 := (limit.is_limit I.multicospan), h2 := (is_limit_of_preserves (forget C) h1), E := h2.cone_point_unique_up_to_iso (types.limit_cone_is_limit _) in equiv.trans E.to_equiv (concrete.multiequalizer_equiv_aux I) @[simp] lemma concrete.multiequalizer_equiv_apply (I : multicospan_index.{w} C) [has_multiequalizer I] [preserves_limit I.multicospan (forget C)] (x : multiequalizer I) (i : I.L) : ((concrete.multiequalizer_equiv I) x : Π (i : I.L), I.left i) i = multiequalizer.ι I i x := rfl end multiequalizer -- TODO: Add analogous lemmas about products and equalizers. end limits section colimits -- We don't mark this as an `@[ext]` lemma as we don't always want to work elementwise. lemma cokernel_funext {C : Type*} [category C] [has_zero_morphisms C] [concrete_category C] {M N K : C} {f : M ⟶ N} [has_cokernel f] {g h : cokernel f ⟶ K} (w : ∀ (n : N), g (cokernel.π f n) = h (cokernel.π f n)) : g = h := begin apply coequalizer.hom_ext, apply concrete_category.hom_ext _ _, simpa using w, end variables {C : Type u} [category.{v} C] [concrete_category.{v} C] {J : Type v} [small_category J] (F : J ⥤ C) [preserves_colimit F (forget C)] lemma concrete.from_union_surjective_of_is_colimit {D : cocone F} (hD : is_colimit D) : let ff : (Σ (j : J), F.obj j) → D.X := λ a, D.ι.app a.1 a.2 in function.surjective ff := begin intro ff, let E := (forget C).map_cocone D, let hE : is_colimit E := is_colimit_of_preserves _ hD, let G := types.colimit_cocone.{v v} (F ⋙ forget C), let hG := types.colimit_cocone_is_colimit.{v v} (F ⋙ forget C), let T : E ≅ G := hE.unique_up_to_iso hG, let TX : E.X ≅ G.X := (cocones.forget _).map_iso T, suffices : function.surjective (TX.hom ∘ ff), { intro a, obtain ⟨b, hb⟩ := this (TX.hom a), refine ⟨b, _⟩, apply_fun TX.inv at hb, change (TX.hom ≫ TX.inv) (ff b) = (TX.hom ≫ TX.inv) _ at hb, simpa only [TX.hom_inv_id] using hb }, have : TX.hom ∘ ff = λ a, G.ι.app a.1 a.2, { ext a, change (E.ι.app a.1 ≫ hE.desc G) a.2 = _, rw hE.fac }, rw this, rintro ⟨⟨j,a⟩⟩, exact ⟨⟨j,a⟩,rfl⟩, end lemma concrete.is_colimit_exists_rep {D : cocone F} (hD : is_colimit D) (x : D.X) : ∃ (j : J) (y : F.obj j), D.ι.app j y = x := begin obtain ⟨a, rfl⟩ := concrete.from_union_surjective_of_is_colimit F hD x, exact ⟨a.1, a.2, rfl⟩, end lemma concrete.colimit_exists_rep [has_colimit F] (x : colimit F) : ∃ (j : J) (y : F.obj j), colimit.ι F j y = x := concrete.is_colimit_exists_rep F (colimit.is_colimit _) x lemma concrete.is_colimit_rep_eq_of_exists {D : cocone F} {i j : J} (hD : is_colimit D) (x : F.obj i) (y : F.obj j) (h : ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y) : D.ι.app i x = D.ι.app j y := begin let E := (forget C).map_cocone D, let hE : is_colimit E := is_colimit_of_preserves _ hD, let G := types.colimit_cocone.{v v} (F ⋙ forget C), let hG := types.colimit_cocone_is_colimit.{v v} (F ⋙ forget C), let T : E ≅ G := hE.unique_up_to_iso hG, let TX : E.X ≅ G.X := (cocones.forget _).map_iso T, apply_fun TX.hom, swap, { suffices : function.bijective TX.hom, by exact this.1, rw ← is_iso_iff_bijective, apply is_iso.of_iso }, change (E.ι.app i ≫ TX.hom) x = (E.ι.app j ≫ TX.hom) y, erw [T.hom.w, T.hom.w], obtain ⟨k, f, g, h⟩ := h, have : G.ι.app i x = (G.ι.app k (F.map f x) : G.X) := quot.sound ⟨f,rfl⟩, rw [this, h], symmetry, exact quot.sound ⟨g,rfl⟩, end lemma concrete.colimit_rep_eq_of_exists [has_colimit F] {i j : J} (x : F.obj i) (y : F.obj j) (h : ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y) : colimit.ι F i x = colimit.ι F j y := concrete.is_colimit_rep_eq_of_exists F (colimit.is_colimit _) x y h section filtered_colimits variable [is_filtered J] lemma concrete.is_colimit_exists_of_rep_eq {D : cocone F} {i j : J} (hD : is_colimit D) (x : F.obj i) (y : F.obj j) (h : D.ι.app _ x = D.ι.app _ y) : ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y := begin let E := (forget C).map_cocone D, let hE : is_colimit E := is_colimit_of_preserves _ hD, let G := types.colimit_cocone.{v v} (F ⋙ forget C), let hG := types.colimit_cocone_is_colimit.{v v} (F ⋙ forget C), let T : E ≅ G := hE.unique_up_to_iso hG, let TX : E.X ≅ G.X := (cocones.forget _).map_iso T, apply_fun TX.hom at h, change (E.ι.app i ≫ TX.hom) x = (E.ι.app j ≫ TX.hom) y at h, erw [T.hom.w, T.hom.w] at h, replace h := quot.exact _ h, suffices : ∀ (a b : Σ j, F.obj j) (h : eqv_gen (limits.types.quot.rel.{v v} (F ⋙ forget C)) a b), ∃ k (f : a.1 ⟶ k) (g : b.1 ⟶ k), F.map f a.2 = F.map g b.2, { exact this ⟨i,x⟩ ⟨j,y⟩ h }, intros a b h, induction h, case eqv_gen.rel : x y hh { obtain ⟨e,he⟩ := hh, use [y.1, e, 𝟙 _], simpa using he.symm }, case eqv_gen.refl : x { use [x.1, 𝟙 _, 𝟙 _, rfl] }, case eqv_gen.symm : x y _ hh { obtain ⟨k, f, g, hh⟩ := hh, use [k, g, f, hh.symm] }, case eqv_gen.trans : x y z _ _ hh1 hh2 { obtain ⟨k1, f1, g1, h1⟩ := hh1, obtain ⟨k2, f2, g2, h2⟩ := hh2, let k0 : J := is_filtered.max k1 k2, let e1 : k1 ⟶ k0 := is_filtered.left_to_max _ _, let e2 : k2 ⟶ k0 := is_filtered.right_to_max _ _, let k : J := is_filtered.coeq (g1 ≫ e1) (f2 ≫ e2), let e : k0 ⟶ k := is_filtered.coeq_hom _ _, use [k, f1 ≫ e1 ≫ e, g2 ≫ e2 ≫ e], simp only [F.map_comp, comp_apply, h1, ← h2], simp only [← comp_apply, ← F.map_comp], rw is_filtered.coeq_condition }, end theorem concrete.is_colimit_rep_eq_iff_exists {D : cocone F} {i j : J} (hD : is_colimit D) (x : F.obj i) (y : F.obj j) : D.ι.app i x = D.ι.app j y ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y := ⟨concrete.is_colimit_exists_of_rep_eq _ hD _ _, concrete.is_colimit_rep_eq_of_exists _ hD _ _⟩ lemma concrete.colimit_exists_of_rep_eq [has_colimit F] {i j : J} (x : F.obj i) (y : F.obj j) (h : colimit.ι F _ x = colimit.ι F _ y) : ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y := concrete.is_colimit_exists_of_rep_eq F (colimit.is_colimit _) x y h theorem concrete.colimit_rep_eq_iff_exists [has_colimit F] {i j : J} (x : F.obj i) (y : F.obj j) : colimit.ι F i x = colimit.ι F j y ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f x = F.map g y := ⟨concrete.colimit_exists_of_rep_eq _ _ _, concrete.colimit_rep_eq_of_exists _ _ _⟩ end filtered_colimits section wide_pushout open wide_pushout open wide_pushout_shape lemma concrete.wide_pushout_exists_rep {B : C} {α : Type*} {X : α → C} (f : Π j : α, B ⟶ X j) [has_wide_pushout.{v} B X f] [preserves_colimit (wide_span B X f) (forget C)] (x : wide_pushout B X f) : (∃ y : B, head f y = x) ∨ (∃ (i : α) (y : X i), ι f i y = x) := begin obtain ⟨_ | j, y, rfl⟩ := concrete.colimit_exists_rep _ x, { use y }, { right, use [j,y] } end lemma concrete.wide_pushout_exists_rep' {B : C} {α : Type*} [nonempty α] {X : α → C} (f : Π j : α, B ⟶ X j) [has_wide_pushout.{v} B X f] [preserves_colimit (wide_span B X f) (forget C)] (x : wide_pushout B X f) : ∃ (i : α) (y : X i), ι f i y = x := begin rcases concrete.wide_pushout_exists_rep f x with ⟨y, rfl⟩ | ⟨i, y, rfl⟩, { inhabit α, use [arbitrary _, f _ y], simp only [← arrow_ι _ (arbitrary α), comp_apply] }, { use [i,y] } end end wide_pushout -- TODO: Add analogous lemmas about coproducts and coequalizers. end colimits end category_theory.limits
5a57fb1869aae84a93f5f440e5fcb0bb78f5d00e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/group/min_max.lean
b0bfc080a6f0a265267b17043747117a76e92fd1
[ "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,302
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.group.abs import algebra.order.monoid.min_max /-! # `min` and `max` in linearly ordered groups. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ section variables {α : Type*} [group α] [linear_order α] [covariant_class α α (*) (≤)] @[simp, to_additive] lemma max_one_div_max_inv_one_eq_self (a : α) : max a 1 / max a⁻¹ 1 = a := by { rcases le_total a 1 with h|h; simp [h] } alias max_zero_sub_max_neg_zero_eq_self ← max_zero_sub_eq_self end section linear_ordered_comm_group variables {α : Type*} [linear_ordered_comm_group α] {a b c : α} @[to_additive min_neg_neg] lemma min_inv_inv' (a b : α) : min (a⁻¹) (b⁻¹) = (max a b)⁻¹ := eq.symm $ @monotone.map_max α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive max_neg_neg] lemma max_inv_inv' (a b : α) : max (a⁻¹) (b⁻¹) = (min a b)⁻¹ := eq.symm $ @monotone.map_min α αᵒᵈ _ _ has_inv.inv a b $ λ a b, inv_le_inv_iff.mpr @[to_additive min_sub_sub_right] lemma min_div_div_right' (a b c : α) : min (a / c) (b / c) = min a b / c := by simpa only [div_eq_mul_inv] using min_mul_mul_right a b (c⁻¹) @[to_additive max_sub_sub_right] lemma max_div_div_right' (a b c : α) : max (a / c) (b / c) = max a b / c := by simpa only [div_eq_mul_inv] using max_mul_mul_right a b (c⁻¹) @[to_additive min_sub_sub_left] lemma min_div_div_left' (a b c : α) : min (a / b) (a / c) = a / max b c := by simp only [div_eq_mul_inv, min_mul_mul_left, min_inv_inv'] @[to_additive max_sub_sub_left] lemma max_div_div_left' (a b c : α) : max (a / b) (a / c) = a / min b c := by simp only [div_eq_mul_inv, max_mul_mul_left, max_inv_inv'] end linear_ordered_comm_group section linear_ordered_add_comm_group variables {α : Type*} [linear_ordered_add_comm_group α] {a b c : α} lemma max_sub_max_le_max (a b c d : α) : max a b - max c d ≤ max (a - c) (b - d) := begin simp only [sub_le_iff_le_add, max_le_iff], split, calc a = a - c + c : (sub_add_cancel a c).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_left _ _) (le_max_left _ _), calc b = b - d + d : (sub_add_cancel b d).symm ... ≤ max (a - c) (b - d) + max c d : add_le_add (le_max_right _ _) (le_max_right _ _) end lemma abs_max_sub_max_le_max (a b c d : α) : |max a b - max c d| ≤ max (|a - c|) (|b - d|) := begin refine abs_sub_le_iff.2 ⟨_, _⟩, { exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) }, { rw [abs_sub_comm a c, abs_sub_comm b d], exact (max_sub_max_le_max _ _ _ _).trans (max_le_max (le_abs_self _) (le_abs_self _)) } end lemma abs_min_sub_min_le_max (a b c d : α) : |min a b - min c d| ≤ max (|a - c|) (|b - d|) := by simpa only [max_neg_neg, neg_sub_neg, abs_sub_comm] using abs_max_sub_max_le_max (-a) (-b) (-c) (-d) lemma abs_max_sub_max_le_abs (a b c : α) : |max a c - max b c| ≤ |a - b| := by simpa only [sub_self, abs_zero, max_eq_left (abs_nonneg _)] using abs_max_sub_max_le_max a c b c end linear_ordered_add_comm_group
23402412f55a5f38d29616c262119b6d58748926
274748215b6d042f0d9c9a505f9551fa8e0c5f38
/src/for_mathlib/calle_set.lean
7de82cfacc4089318e90dc3fd5efa304c1cb232a
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/M4P33
878ecb515c77d20cc799ff1ebd78f1bf4fd65c12
1a179372db71ad6802d11eacbc1f02f327d55f8f
refs/heads/master
1,607,519,867,193
1,583,344,297,000
1,583,344,297,000
233,316,107
59
4
Apache-2.0
1,579,285,778,000
1,578,788,367,000
Lean
UTF-8
Lean
false
false
183
lean
import data.set.lattice open set theorem compl_lt_compl {α : Type*} (U V : set α) : -U < -V → V < U := λ H, ⟨compl_subset_compl.1 H.1, λ H1, H.2 (compl_subset_compl.2 H1)⟩
8b624966fb6d548bba2dc060be082a56382e0cc9
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/unify_fo_approx_bug1.lean
18ed17544501b8a80c0dae9bfb307f3e1887d799
[ "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
343
lean
#check ( return (1, 1) : list (nat × nat) ) constant A : Type constant B : Type set_option pp.binder_types true set_option pp.universes true #check λ (A : Type) (B : Type) (a : A) (b : B), (return (a, b) : list (A × B)) #check λ (A : Type) (B : Type) (C : Type) (a : A) (b : B) (c : C), (return (a, b, a, c) : list (A × B × A × C))
03b9054ec589dcd5143642848f51180a81902d46
59a4b050600ed7b3d5826a8478db0a9bdc190252
/src/category_theory/full_subcategory.lean
5138ffffc8cd74c19a1385d0f5c793c9330a0767
[]
no_license
rwbarton/lean-category-theory
f720268d800b62a25d69842ca7b5d27822f00652
00df814d463406b7a13a56f5dcda67758ba1b419
refs/heads/master
1,585,366,296,767
1,536,151,349,000
1,536,151,349,000
147,652,096
0
0
null
1,536,226,960,000
1,536,226,960,000
null
UTF-8
Lean
false
false
1,992
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.functor import category_theory.embedding import category_theory.tactics.obviously namespace category_theory universes u₁ v₁ u₂ v₂ w₁ variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] include 𝒞 instance full_subcategory (Z : C → Prop) : category.{u₁ v₁} {X : C // Z X} := { hom := λ X Y, X.1 ⟶ Y.1, id := λ X, 𝟙 X.1, comp := λ _ _ _ f g, f ≫ g } def full_subcategory_embedding (Z : C → Prop) : {X : C // Z X} ⥤ C := { obj := λ X, X.1, map' := λ _ _ f, f } instance full_subcategory_full (Z : C → Prop) : full (full_subcategory_embedding Z) := by obviously instance full_subcategory_faithful (Z : C → Prop) : faithful (full_subcategory_embedding Z) := by obviously instance sigma_category (Z : C → Type w₁) : category.{(max u₁ w₁) v₁} (Σ X : C, Z X) := { hom := λ X Y, X.1 ⟶ Y.1, id := λ X, 𝟙 X.1, comp := λ _ _ _ f g, f ≫ g } def sigma_category_embedding (Z : C → Type u₁) : (Σ X : C, Z X) ⥤ C := { obj := λ X, X.1, map' := λ _ _ f, f } instance full_σ (Z : C → Type u₁) : full (sigma_category_embedding Z) := by obviously instance faithful_σ (Z : C → Type u₁) : faithful (sigma_category_embedding Z) := by obviously variables {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒟 def restrict_functor_σ (F : C ⥤ D) (ZC : C → Type u₁) (ZD : D → Type u₂) (w : ∀ {X : C} (z : ZC X), ZD (F X)) : (Σ X : C, ZC X) ⥤ (Σ Y : D, ZD Y) := { obj := λ X, ⟨ F X.1, w X.2 ⟩, map' := λ _ _ f, F.map f } def restrict_functor (F : C ⥤ D) (ZC : C → Prop) (ZD : D → Prop) (w : ∀ {X : C} (z : ZC X), ZD (F X)) : {X : C // ZC X} ⥤ {Y : D // ZD Y} := { obj := λ X, ⟨ F X.1, w X.2 ⟩, map' := λ _ _ f, F.map f } end category_theory
cac02efb7736dcb19c38a0942e92b89ec48a157b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/normed/group/SemiNormedGroup.lean
db67750524950377be46acc1043545a31f3b1415
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,002
lean
/- Copyright (c) 2021 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Riccardo Brasca -/ import analysis.normed.group.hom import category_theory.limits.shapes.zero_morphisms import category_theory.concrete_category.bundled_hom import category_theory.elementwise /-! # The category of seminormed groups > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define `SemiNormedGroup`, the category of seminormed groups and normed group homs between them, as well as `SemiNormedGroup₁`, the subcategory of norm non-increasing morphisms. -/ noncomputable theory universes u open category_theory /-- The category of seminormed abelian groups and bounded group homomorphisms. -/ def SemiNormedGroup : Type (u+1) := bundled seminormed_add_comm_group namespace SemiNormedGroup instance bundled_hom : bundled_hom @normed_add_group_hom := ⟨@normed_add_group_hom.to_fun, @normed_add_group_hom.id, @normed_add_group_hom.comp, @normed_add_group_hom.coe_inj⟩ attribute [derive [large_category, concrete_category]] SemiNormedGroup instance : has_coe_to_sort SemiNormedGroup (Type u) := bundled.has_coe_to_sort /-- Construct a bundled `SemiNormedGroup` from the underlying type and typeclass. -/ def of (M : Type u) [seminormed_add_comm_group M] : SemiNormedGroup := bundled.of M instance (M : SemiNormedGroup) : seminormed_add_comm_group M := M.str @[simp] lemma coe_of (V : Type u) [seminormed_add_comm_group V] : (SemiNormedGroup.of V : Type u) = V := rfl @[simp] lemma coe_id (V : SemiNormedGroup) : ⇑(𝟙 V) = id := rfl @[simp] lemma coe_comp {M N K : SemiNormedGroup} (f : M ⟶ N) (g : N ⟶ K) : ((f ≫ g) : M → K) = g ∘ f := rfl instance : inhabited SemiNormedGroup := ⟨of punit⟩ instance of_unique (V : Type u) [seminormed_add_comm_group V] [i : unique V] : unique (SemiNormedGroup.of V) := i instance : limits.has_zero_morphisms.{u (u+1)} SemiNormedGroup := {} @[simp] lemma zero_apply {V W : SemiNormedGroup} (x : V) : (0 : V ⟶ W) x = 0 := rfl lemma is_zero_of_subsingleton (V : SemiNormedGroup) [subsingleton V] : limits.is_zero V := begin refine ⟨λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩, { ext, have : x = 0 := subsingleton.elim _ _, simp only [this, map_zero], }, { ext, apply subsingleton.elim } end instance has_zero_object : limits.has_zero_object SemiNormedGroup.{u} := ⟨⟨of punit, is_zero_of_subsingleton _⟩⟩ lemma iso_isometry_of_norm_noninc {V W : SemiNormedGroup} (i : V ≅ W) (h1 : i.hom.norm_noninc) (h2 : i.inv.norm_noninc) : isometry i.hom := begin apply add_monoid_hom_class.isometry_of_norm, intro v, apply le_antisymm (h1 v), calc ‖v‖ = ‖i.inv (i.hom v)‖ : by rw [iso.hom_inv_id_apply] ... ≤ ‖i.hom v‖ : h2 _, end end SemiNormedGroup /-- `SemiNormedGroup₁` is a type synonym for `SemiNormedGroup`, which we shall equip with the category structure consisting only of the norm non-increasing maps. -/ def SemiNormedGroup₁ : Type (u+1) := bundled seminormed_add_comm_group namespace SemiNormedGroup₁ instance : has_coe_to_sort SemiNormedGroup₁ (Type u) := bundled.has_coe_to_sort instance : large_category.{u} SemiNormedGroup₁ := { hom := λ X Y, { f : normed_add_group_hom X Y // f.norm_noninc }, id := λ X, ⟨normed_add_group_hom.id X, normed_add_group_hom.norm_noninc.id⟩, comp := λ X Y Z f g, ⟨(g : normed_add_group_hom Y Z).comp (f : normed_add_group_hom X Y), g.2.comp f.2⟩ } @[ext] lemma hom_ext {M N : SemiNormedGroup₁} (f g : M ⟶ N) (w : (f : M → N) = (g : M → N)) : f = g := subtype.eq (normed_add_group_hom.ext (congr_fun w)) instance : concrete_category.{u} SemiNormedGroup₁ := { forget := { obj := λ X, X, map := λ X Y f, f, }, forget_faithful := {} } /-- Construct a bundled `SemiNormedGroup₁` from the underlying type and typeclass. -/ def of (M : Type u) [seminormed_add_comm_group M] : SemiNormedGroup₁ := bundled.of M instance (M : SemiNormedGroup₁) : seminormed_add_comm_group M := M.str /-- Promote a morphism in `SemiNormedGroup` to a morphism in `SemiNormedGroup₁`. -/ def mk_hom {M N : SemiNormedGroup} (f : M ⟶ N) (i : f.norm_noninc) : SemiNormedGroup₁.of M ⟶ SemiNormedGroup₁.of N := ⟨f, i⟩ @[simp] lemma mk_hom_apply {M N : SemiNormedGroup} (f : M ⟶ N) (i : f.norm_noninc) (x) : mk_hom f i x = f x := rfl /-- Promote an isomorphism in `SemiNormedGroup` to an isomorphism in `SemiNormedGroup₁`. -/ @[simps] def mk_iso {M N : SemiNormedGroup} (f : M ≅ N) (i : f.hom.norm_noninc) (i' : f.inv.norm_noninc) : SemiNormedGroup₁.of M ≅ SemiNormedGroup₁.of N := { hom := mk_hom f.hom i, inv := mk_hom f.inv i', hom_inv_id' := by { apply subtype.eq, exact f.hom_inv_id, }, inv_hom_id' := by { apply subtype.eq, exact f.inv_hom_id, }, } instance : has_forget₂ SemiNormedGroup₁ SemiNormedGroup := { forget₂ := { obj := λ X, X, map := λ X Y f, f.1, }, } @[simp] lemma coe_of (V : Type u) [seminormed_add_comm_group V] : (SemiNormedGroup₁.of V : Type u) = V := rfl @[simp] lemma coe_id (V : SemiNormedGroup₁) : ⇑(𝟙 V) = id := rfl @[simp] lemma coe_comp {M N K : SemiNormedGroup₁} (f : M ⟶ N) (g : N ⟶ K) : ((f ≫ g) : M → K) = g ∘ f := rfl -- If `coe_fn_coe_base` fires before `coe_comp`, `coe_comp'` puts us back in normal form. @[simp] lemma coe_comp' {M N K : SemiNormedGroup₁} (f : M ⟶ N) (g : N ⟶ K) : ((f ≫ g) : normed_add_group_hom M K) = (↑g : normed_add_group_hom N K).comp ↑f := rfl instance : inhabited SemiNormedGroup₁ := ⟨of punit⟩ instance of_unique (V : Type u) [seminormed_add_comm_group V] [i : unique V] : unique (SemiNormedGroup₁.of V) := i instance : limits.has_zero_morphisms.{u (u+1)} SemiNormedGroup₁ := { has_zero := λ X Y, { zero := ⟨0, normed_add_group_hom.norm_noninc.zero⟩, }, comp_zero' := λ X Y f Z, by { ext, refl, }, zero_comp' := λ X Y Z f, by { ext, simp [coe_fn_coe_base'] } } @[simp] lemma zero_apply {V W : SemiNormedGroup₁} (x : V) : (0 : V ⟶ W) x = 0 := rfl lemma is_zero_of_subsingleton (V : SemiNormedGroup₁) [subsingleton V] : limits.is_zero V := begin refine ⟨λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩, λ X, ⟨⟨⟨0⟩, λ f, _⟩⟩⟩, { ext, have : x = 0 := subsingleton.elim _ _, simp only [this, map_zero], exact map_zero f.1 }, { ext, apply subsingleton.elim } end instance has_zero_object : limits.has_zero_object SemiNormedGroup₁.{u} := ⟨⟨of punit, is_zero_of_subsingleton _⟩⟩ lemma iso_isometry {V W : SemiNormedGroup₁} (i : V ≅ W) : isometry i.hom := begin change isometry (i.hom : V →+ W), refine add_monoid_hom_class.isometry_of_norm i.hom _, intro v, apply le_antisymm (i.hom.2 v), calc ‖v‖ = ‖i.inv (i.hom v)‖ : by rw [iso.hom_inv_id_apply] ... ≤ ‖i.hom v‖ : i.inv.2 _, end end SemiNormedGroup₁
890173c7c951b9a2d201aa1fff1400605bdd1666
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/match_fun.lean
a31313099bc166a68759f51793c4764e79381b99
[ "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
418
lean
open bool nat definition foo (b : bool) : nat → nat := match b with | tt := λ x : nat, 0 | ff := λ y : nat, (succ 0) end example : foo tt 1 = 0 := rfl example : foo ff 1 = 1 := rfl definition zero_fn := λ x : nat, 0 definition foo2 : bool → nat → nat | tt := succ | ff := zero_fn example : foo2 tt 1 = 2 := rfl example : foo2 tt 2 = 3 := rfl example : foo2 ff 1 = 0 := rfl example : foo2 ff 2 = 0 := rfl
7d7c9b9dec67ddc90294781baea89bd789dc6dd2
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/ring_theory/polynomial/vieta.lean
93ec3fb2d4213060b5b0586994dd55ea5b2a91e1
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
5,386
lean
/- Copyright (c) 2020 Hanting Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hanting Zhang -/ import ring_theory.polynomial.basic import ring_theory.polynomial.symmetric /-! # Vieta's Formula The main result is `multiset.prod_X_add_C_eq_sum_esymm`, which shows that the product of linear terms ` X + λ` with `λ` in a `multiset s` is equal to a linear combination of the symmetric functions `esymm s`. From this, we deduce `mv_polynomial.prod_X_add_C_eq_sum_esymm` which is the equivalent formula for the product of linear terms `X + X i` with `i` in a `fintype σ` as a linear combination of the symmetric polynomials `esymm σ R j`. -/ open_locale big_operators polynomial namespace multiset section semiring variables {R : Type*} [comm_semiring R] /-- A sum version of Vieta's formula for `multiset`: the product of the linear terms `X + λ` where `λ` runs through a multiset `s` is equal to a linear combination of the symmetric functions `esymm s` of the `λ`'s .-/ lemma prod_X_add_C_eq_sum_esymm (s : multiset R) : (s.map (λ r, polynomial.X + polynomial.C r)).prod = ∑ j in finset.range (s.card + 1), (polynomial.C (s.esymm j) * polynomial.X^(s.card - j)) := begin classical, rw [prod_map_add, antidiagonal_eq_map_powerset, map_map, ←bind_powerset_len, function.comp, map_bind, sum_bind, finset.sum_eq_multiset_sum, finset.range_coe, map_congr (eq.refl _)], intros _ _, rw [esymm, ←sum_hom', ←sum_map_mul_right, map_congr (eq.refl _)], intros _ ht, rw mem_powerset_len at ht, simp [ht, map_const, prod_repeat, prod_hom', map_id', card_sub], end /-- Vieta's formula for the coefficients of the product of linear terms `X + λ` where `λ` runs through a multiset `s` : the `k`th coefficient is the symmetric function `esymm (card s - k) s`. -/ lemma prod_X_add_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card): polynomial.coeff (s.map (λ r, polynomial.X + polynomial.C r)).prod k = s.esymm (s.card - k) := begin convert polynomial.ext_iff.mp (prod_X_add_C_eq_sum_esymm s) k, simp_rw [polynomial.finset_sum_coeff, polynomial.coeff_C_mul_X_pow], rw finset.sum_eq_single_of_mem (s.card - k) _, { rw if_pos (nat.sub_sub_self h).symm, }, { intros j hj1 hj2, suffices : k ≠ card s - j, { rw if_neg this, }, { intro hn, rw [hn, nat.sub_sub_self (nat.lt_succ_iff.mp (finset.mem_range.mp hj1))] at hj2, exact ne.irrefl hj2, }}, { rw finset.mem_range, exact nat.sub_lt_succ s.card k } end end semiring section ring variables {R : Type*} [comm_ring R] lemma esymm_neg (s : multiset R) (k : ℕ) : (map has_neg.neg s).esymm k = (-1)^k * esymm s k := begin rw [esymm, esymm, ←multiset.sum_map_mul_left, multiset.powerset_len_map, multiset.map_map, map_congr (eq.refl _)], intros x hx, rw [(by { exact (mem_powerset_len.mp hx).right.symm }), ←prod_repeat, ←multiset.map_const], nth_rewrite 2 ←map_id' x, rw [←prod_map_mul, map_congr (eq.refl _)], exact λ z _, neg_one_mul z, end lemma prod_X_sub_C_eq_sum_esymm (s : multiset R) : (s.map (λ t, polynomial.X - polynomial.C t)).prod = ∑ j in finset.range (s.card + 1), (-1)^j* (polynomial.C (s.esymm j) * polynomial.X ^ (s.card - j)) := begin conv_lhs { congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg polynomial.C _, }, convert prod_X_add_C_eq_sum_esymm (map (λ t, -t) s) using 1, { rwa map_map, }, { simp only [esymm_neg, card_map, mul_assoc, map_mul, map_pow, map_neg, map_one], }, end lemma prod_X_sub_C_coeff (s : multiset R) {k : ℕ} (h : k ≤ s.card): polynomial.coeff (s.map (λ t, polynomial.X - polynomial.C t)).prod k = (-1)^(s.card - k) * s.esymm (s.card - k) := begin conv_lhs { congr, congr, congr, funext, rw sub_eq_add_neg, rw ←map_neg polynomial.C _, }, convert prod_X_add_C_coeff (map (λ t, -t) s) _ using 1, { rwa map_map, }, { rwa [esymm_neg, card_map] }, { rwa card_map }, end end ring end multiset namespace mv_polynomial open finset polynomial fintype variables (R σ : Type*) [comm_semiring R] [fintype σ] /-- A sum version of Vieta's formula for `mv_polynomial`: viewing `X i` as variables, the product of linear terms `λ + X i` is equal to a linear combination of the symmetric polynomials `esymm σ R j`. -/ lemma prod_C_add_X_eq_sum_esymm : (∏ i : σ, (polynomial.X + polynomial.C (X i)) : polynomial (mv_polynomial σ R) )= ∑ j in range (card σ + 1), (polynomial.C (esymm σ R j) * polynomial.X ^ (card σ - j)) := begin let s := (multiset.map (λ i : σ, (X i : mv_polynomial σ R)) finset.univ.val), rw (_ : card σ = s.card), { simp_rw [esymm_eq_multiset.esymm σ R _, finset.prod_eq_multiset_prod], convert multiset.prod_X_add_C_eq_sum_esymm s, rwa multiset.map_map, }, { rw multiset.card_map, exact rfl, } end lemma prod_X_add_C_coeff (k : ℕ) (h : k ≤ card σ): (∏ i : σ, (polynomial.X + polynomial.C (X i)) : polynomial (mv_polynomial σ R) ).coeff k = esymm σ R (card σ - k) := begin let s := (multiset.map (λ i : σ, (X i : mv_polynomial σ R)) finset.univ.val), rw (_ : card σ = s.card) at ⊢ h, { rw [esymm_eq_multiset.esymm σ R (s.card - k), finset.prod_eq_multiset_prod], convert multiset.prod_X_add_C_coeff s h, rwa multiset.map_map }, repeat { rw multiset.card_map, exact rfl, }, end end mv_polynomial
55b0ce1f2cdad9cc221a1f6be758aef966f78199
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/order/sub.lean
d6fd57b7a295d6f83e205b8a7a22259b10ea6405
[ "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
30,463
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.order.monoid /-! # Ordered Subtraction This file proves lemmas relating (truncated) subtraction with an order. We provide a class `has_ordered_sub` stating that `a - b ≤ c ↔ a ≤ c + b`. The subtraction discussed here could both be normal subtraction in an additive group or truncated subtraction on a canonically ordered monoid (`ℕ`, `multiset`, `enat`, `ennreal`, ...) ## Implementation details `has_ordered_sub` is a mixin type-class, so that we can use the results in this file even in cases where we don't have a `canonically_ordered_add_monoid` instance (even though that is our main focus). Conversely, this means we can use `canonically_ordered_add_monoid` without necessarily having to define a subtraction. The results in this file are ordered by the type-class assumption needed to prove it. This means that similar results might not be close to each other. Furthermore, we don't prove implications if a bi-implication can be proven under the same assumptions. Lemmas using this class are named using `tsub` instead of `sub` (short for "truncated subtraction"). This is to avoid naming conflicts with similar lemmas about ordered groups. We provide a second version of most results that require `[contravariant_class α α (+) (≤)]`. In the second version we replace this type-class assumption by explicit `add_le_cancellable` assumptions. TODO: maybe we should make a multiplicative version of this, so that we can replace some identical lemmas about subtraction/division in `ordered_[add_]comm_group` with these. TODO: generalize `nat.le_of_le_of_sub_le_sub_right`, `nat.sub_le_sub_right_iff`, `nat.mul_self_sub_mul_self_eq` -/ variables {α β : Type*} /-- `has_ordered_sub α` means that `α` has a subtraction characterized by `a - b ≤ c ↔ a ≤ c + b`. In other words, `a - b` is the least `c` such that `a ≤ b + c`. This is satisfied both by the subtraction in additive ordered groups and by truncated subtraction in canonically ordered monoids on many specific types. -/ class has_ordered_sub (α : Type*) [has_le α] [has_add α] [has_sub α] := (tsub_le_iff_right : ∀ a b c : α, a - b ≤ c ↔ a ≤ c + b) section has_add variables [preorder α] [has_add α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_le_iff_right : a - b ≤ c ↔ a ≤ c + b := has_ordered_sub.tsub_le_iff_right a b c /-- See `add_tsub_cancel_right` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_right : a + b - b ≤ a := tsub_le_iff_right.mpr le_rfl lemma le_tsub_add : b ≤ (b - a) + a := tsub_le_iff_right.mp le_rfl lemma add_hom.le_map_tsub [preorder β] [has_add β] [has_sub β] [has_ordered_sub β] (f : add_hom α β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := by { rw [tsub_le_iff_right, ← f.map_add], exact hf le_tsub_add } lemma le_mul_tsub {R : Type*} [distrib R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * b - a * c ≤ a * (b - c) := (add_hom.mul_left a).le_map_tsub (monotone_id.const_mul' a) _ _ lemma le_tsub_mul {R : Type*} [comm_semiring R] [preorder R] [has_sub R] [has_ordered_sub R] [covariant_class R R (*) (≤)] {a b c : R} : a * c - b * c ≤ (a - b) * c := by simpa only [mul_comm _ c] using le_mul_tsub end has_add /-- An order isomorphism between types with ordered subtraction preserves subtraction provided that it preserves addition. -/ lemma order_iso.map_tsub {M N : Type*} [preorder M] [has_add M] [has_sub M] [has_ordered_sub M] [partial_order N] [has_add N] [has_sub N] [has_ordered_sub N] (e : M ≃o N) (h_add : ∀ a b, e (a + b) = e a + e b) (a b : M) : e (a - b) = e a - e b := begin set e_add : M ≃+ N := { map_add' := h_add, .. e }, refine le_antisymm _ (e_add.to_add_hom.le_map_tsub e.monotone a b), suffices : e (e.symm (e a) - e.symm (e b)) ≤ e (e.symm (e a - e b)), by simpa, exact e.monotone (e_add.symm.to_add_hom.le_map_tsub e.symm.monotone _ _) end /-! ### Preorder -/ section ordered_add_comm_monoid section preorder variables [preorder α] section add_comm_semigroup variables [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_le_iff_left : a - b ≤ c ↔ a ≤ b + c := by rw [tsub_le_iff_right, add_comm] lemma le_add_tsub : a ≤ b + (a - b) := tsub_le_iff_left.mp le_rfl /-- See `add_tsub_cancel_left` for the equality if `contravariant_class α α (+) (≤)`. -/ lemma add_tsub_le_left : a + b - a ≤ b := tsub_le_iff_left.mpr le_rfl lemma tsub_le_tsub_right (h : a ≤ b) (c : α) : a - c ≤ b - c := tsub_le_iff_left.mpr $ h.trans le_add_tsub lemma tsub_le_iff_tsub_le : a - b ≤ c ↔ a - c ≤ b := by rw [tsub_le_iff_left, tsub_le_iff_right] /-- See `tsub_tsub_cancel_of_le` for the equality. -/ lemma tsub_tsub_le : b - (b - a) ≤ a := tsub_le_iff_right.mpr le_add_tsub section cov variable [covariant_class α α (+) (≤)] lemma tsub_le_tsub_left (h : a ≤ b) (c : α) : c - b ≤ c - a := tsub_le_iff_left.mpr $ le_add_tsub.trans $ add_le_add_right h _ lemma tsub_le_tsub (hab : a ≤ b) (hcd : c ≤ d) : a - d ≤ b - c := (tsub_le_tsub_right hab _).trans $ tsub_le_tsub_left hcd _ /-- See `add_tsub_assoc_of_le` for the equality. -/ lemma add_tsub_le_assoc : a + b - c ≤ a + (b - c) := by { rw [tsub_le_iff_left, add_left_comm], exact add_le_add_left le_add_tsub a } lemma add_le_add_add_tsub : a + b ≤ (a + c) + (b - c) := by { rw [add_assoc], exact add_le_add_left le_add_tsub a } lemma le_tsub_add_add : a + b ≤ (a - c) + (b + c) := by { rw [add_comm a, add_comm (a - c)], exact add_le_add_add_tsub } lemma tsub_le_tsub_add_tsub : a - c ≤ (a - b) + (b - c) := begin rw [tsub_le_iff_left, ← add_assoc, add_right_comm], exact le_add_tsub.trans (add_le_add_right le_add_tsub _), end lemma tsub_tsub_tsub_le_tsub : (c - a) - (c - b) ≤ b - a := begin rw [tsub_le_iff_left, tsub_le_iff_left, add_left_comm], exact le_tsub_add.trans (add_le_add_left le_add_tsub _), end lemma tsub_tsub_le_tsub_add {a b c : α} : a - (b - c) ≤ a - b + c := tsub_le_iff_right.2 $ calc a ≤ a - b + b : le_tsub_add ... ≤ a - b + (c + (b - c)) : add_le_add_left le_add_tsub _ ... = a - b + c + (b - c) : (add_assoc _ _ _).symm end cov /-! #### Lemmas that assume that an element is `add_le_cancellable` -/ namespace add_le_cancellable protected lemma le_add_tsub_swap (hb : add_le_cancellable b) : a ≤ b + a - b := hb le_add_tsub protected lemma le_add_tsub (hb : add_le_cancellable b) : a ≤ a + b - b := by { rw add_comm, exact hb.le_add_tsub_swap } protected lemma le_tsub_of_add_le_left (ha : add_le_cancellable a) (h : a + b ≤ c) : b ≤ c - a := ha $ h.trans le_add_tsub protected lemma le_tsub_of_add_le_right (hb : add_le_cancellable b) (h : a + b ≤ c) : a ≤ c - b := hb.le_tsub_of_add_le_left $ by rwa add_comm end add_le_cancellable /-! ### Lemmas where addition is order-reflecting -/ section contra variable [contravariant_class α α (+) (≤)] lemma le_add_tsub_swap : a ≤ b + a - b := contravariant.add_le_cancellable.le_add_tsub_swap lemma le_add_tsub' : a ≤ a + b - b := contravariant.add_le_cancellable.le_add_tsub lemma le_tsub_of_add_le_left (h : a + b ≤ c) : b ≤ c - a := contravariant.add_le_cancellable.le_tsub_of_add_le_left h lemma le_tsub_of_add_le_right (h : a + b ≤ c) : a ≤ c - b := contravariant.add_le_cancellable.le_tsub_of_add_le_right h end contra end add_comm_semigroup variables [add_comm_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_nonpos : a - b ≤ 0 ↔ a ≤ b := by rw [tsub_le_iff_left, add_zero] alias tsub_nonpos ↔ _ tsub_nonpos_of_le lemma add_monoid_hom.le_map_tsub [preorder β] [add_comm_monoid β] [has_sub β] [has_ordered_sub β] (f : α →+ β) (hf : monotone f) (a b : α) : f a - f b ≤ f (a - b) := f.to_add_hom.le_map_tsub hf a b end preorder /-! ### Partial order -/ variables [partial_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] {a b c d : α} lemma tsub_tsub (b a c : α) : b - a - c = b - (a + c) := begin apply le_antisymm, { rw [tsub_le_iff_left, tsub_le_iff_left, ← add_assoc, ← tsub_le_iff_left] }, { rw [tsub_le_iff_left, add_assoc, ← tsub_le_iff_left, ← tsub_le_iff_left] } end section cov variable [covariant_class α α (+) (≤)] lemma tsub_add_eq_tsub_tsub (a b c : α) : a - (b + c) = a - b - c := begin refine le_antisymm (tsub_le_iff_left.mpr _) (tsub_le_iff_left.mpr $ tsub_le_iff_left.mpr _), { rw [add_assoc], refine le_trans le_add_tsub (add_le_add_left le_add_tsub _) }, { rw [← add_assoc], apply le_add_tsub } end lemma tsub_add_eq_tsub_tsub_swap (a b c : α) : a - (b + c) = a - c - b := by { rw [add_comm], apply tsub_add_eq_tsub_tsub } lemma tsub_right_comm : a - b - c = a - c - b := by simp_rw [← tsub_add_eq_tsub_tsub, add_comm] end cov /-! ### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma tsub_eq_of_eq_add (hb : add_le_cancellable b) (h : a = c + b) : a - b = c := le_antisymm (tsub_le_iff_right.mpr h.le) $ by { rw h, exact hb.le_add_tsub } protected lemma eq_tsub_of_add_eq (hc : add_le_cancellable c) (h : a + c = b) : a = b - c := (hc.tsub_eq_of_eq_add h.symm).symm protected theorem tsub_eq_of_eq_add_rev (hb : add_le_cancellable b) (h : a = b + c) : a - b = c := hb.tsub_eq_of_eq_add $ by rw [add_comm, h] @[simp] protected lemma add_tsub_cancel_right (hb : add_le_cancellable b) : a + b - b = a := hb.tsub_eq_of_eq_add $ by rw [add_comm] @[simp] protected lemma add_tsub_cancel_left (ha : add_le_cancellable a) : a + b - a = b := ha.tsub_eq_of_eq_add $ add_comm a b protected lemma lt_add_of_tsub_lt_left (hb : add_le_cancellable b) (h : a - b < c) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_left], refine ⟨h.le, _⟩, rintro rfl, simpa [hb] using h, end protected lemma lt_add_of_tsub_lt_right (hc : add_le_cancellable c) (h : a - c < b) : a < b + c := begin rw [lt_iff_le_and_ne, ← tsub_le_iff_right], refine ⟨h.le, _⟩, rintro rfl, simpa [hc] using h, end end add_le_cancellable /-! #### Lemmas where addition is order-reflecting. -/ section contra variable [contravariant_class α α (+) (≤)] lemma tsub_eq_of_eq_add (h : a = c + b) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add h lemma eq_tsub_of_add_eq (h : a + c = b) : a = b - c := contravariant.add_le_cancellable.eq_tsub_of_add_eq h lemma tsub_eq_of_eq_add_rev (h : a = b + c) : a - b = c := contravariant.add_le_cancellable.tsub_eq_of_eq_add_rev h @[simp] lemma add_tsub_cancel_right (a b : α) : a + b - b = a := contravariant.add_le_cancellable.add_tsub_cancel_right @[simp] lemma add_tsub_cancel_left (a b : α) : a + b - a = b := contravariant.add_le_cancellable.add_tsub_cancel_left lemma lt_add_of_tsub_lt_left (h : a - b < c) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_left h lemma lt_add_of_tsub_lt_right (h : a - c < b) : a < b + c := contravariant.add_le_cancellable.lt_add_of_tsub_lt_right h end contra section both variables [covariant_class α α (+) (≤)] [contravariant_class α α (+) (≤)] lemma add_tsub_add_eq_tsub_right (a c b : α) : (a + c) - (b + c) = a - b := begin apply le_antisymm, { rw [tsub_le_iff_left, add_right_comm], exact add_le_add_right le_add_tsub c }, { rw [tsub_le_iff_left, add_comm b], apply le_of_add_le_add_right, rw [add_assoc], exact le_tsub_add } end lemma add_tsub_add_eq_tsub_left (a b c : α) : (a + b) - (a + c) = b - c := by rw [add_comm a b, add_comm a c, add_tsub_add_eq_tsub_right] end both end ordered_add_comm_monoid /-! ### Lemmas in a linearly ordered monoid. -/ section linear_order variables {a b c d : α} [linear_order α] [add_comm_semigroup α] [has_sub α] [has_ordered_sub α] /-- See `lt_of_tsub_lt_tsub_right_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_right (h : a - c < b - c) : a < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_right h c) h /-- See `lt_tsub_iff_right_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_right : a < b - c ↔ a + c < b := lt_iff_lt_of_le_iff_le tsub_le_iff_right /-- See `lt_tsub_iff_left_of_le` for a weaker statement in a partial order. -/ lemma lt_tsub_iff_left : a < b - c ↔ c + a < b := lt_iff_lt_of_le_iff_le tsub_le_iff_left lemma lt_tsub_comm : a < b - c ↔ c < b - a := lt_tsub_iff_left.trans lt_tsub_iff_right.symm section cov variable [covariant_class α α (+) (≤)] /-- See `lt_of_tsub_lt_tsub_left_of_le` for a weaker statement in a partial order. -/ lemma lt_of_tsub_lt_tsub_left (h : a - b < a - c) : c < b := lt_imp_lt_of_le_imp_le (λ h, tsub_le_tsub_left h a) h end cov end linear_order /-! ### Lemmas in a canonically ordered monoid. -/ section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma add_tsub_cancel_of_le (h : a ≤ b) : a + (b - a) = b := begin refine le_antisymm _ le_add_tsub, obtain ⟨c, rfl⟩ := le_iff_exists_add.1 h, exact add_le_add_left add_tsub_le_left a, end lemma tsub_add_cancel_of_le (h : a ≤ b) : b - a + a = b := by { rw [add_comm], exact add_tsub_cancel_of_le h } lemma add_tsub_cancel_iff_le : a + (b - a) = b ↔ a ≤ b := ⟨λ h, le_iff_exists_add.mpr ⟨b - a, h.symm⟩, add_tsub_cancel_of_le⟩ lemma tsub_add_cancel_iff_le : b - a + a = b ↔ a ≤ b := by { rw [add_comm], exact add_tsub_cancel_iff_le } lemma add_le_of_le_tsub_right_of_le (h : b ≤ c) (h2 : a ≤ c - b) : a + b ≤ c := (add_le_add_right h2 b).trans_eq $ tsub_add_cancel_of_le h lemma add_le_of_le_tsub_left_of_le (h : a ≤ c) (h2 : b ≤ c - a) : a + b ≤ c := (add_le_add_left h2 a).trans_eq $ add_tsub_cancel_of_le h lemma tsub_le_tsub_iff_right (h : c ≤ b) : a - c ≤ b - c ↔ a ≤ b := by rw [tsub_le_iff_right, tsub_add_cancel_of_le h] lemma tsub_left_inj (h1 : c ≤ a) (h2 : c ≤ b) : a - c = b - c ↔ a = b := by simp_rw [le_antisymm_iff, tsub_le_tsub_iff_right h1, tsub_le_tsub_iff_right h2] /-- See `lt_of_tsub_lt_tsub_right` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_right_of_le (h : c ≤ b) (h2 : a - c < b - c) : a < b := by { refine ((tsub_le_tsub_iff_right h).mp h2.le).lt_of_ne _, rintro rfl, exact h2.false } @[simp] lemma tsub_eq_zero_iff_le : a - b = 0 ↔ a ≤ b := by rw [← nonpos_iff_eq_zero, tsub_le_iff_left, add_zero] /-- One direction of `tsub_eq_zero_iff_le`, as a `@[simp]`-lemma. -/ @[simp] lemma tsub_eq_zero_of_le (h : a ≤ b) : a - b = 0 := tsub_eq_zero_iff_le.mpr h @[simp] lemma tsub_self (a : α) : a - a = 0 := tsub_eq_zero_iff_le.mpr le_rfl @[simp] lemma tsub_le_self : a - b ≤ a := tsub_le_iff_left.mpr $ le_add_left le_rfl @[simp] lemma tsub_zero (a : α) : a - 0 = a := le_antisymm tsub_le_self $ le_add_tsub.trans_eq $ zero_add _ @[simp] lemma zero_tsub (a : α) : 0 - a = 0 := tsub_eq_zero_iff_le.mpr $ zero_le a lemma tsub_self_add (a b : α) : a - (a + b) = 0 := by { rw [tsub_eq_zero_iff_le], apply self_le_add_right } lemma tsub_inj_left (h₁ : a ≤ b) (h₂ : a ≤ c) (h₃ : b - a = c - a) : b = c := by rw [← tsub_add_cancel_of_le h₁, ← tsub_add_cancel_of_le h₂, h₃] lemma tsub_pos_iff_not_le : 0 < a - b ↔ ¬ a ≤ b := by rw [pos_iff_ne_zero, ne.def, tsub_eq_zero_iff_le] lemma tsub_pos_of_lt (h : a < b) : 0 < b - a := tsub_pos_iff_not_le.mpr h.not_le lemma tsub_add_tsub_cancel (hab : b ≤ a) (hbc : c ≤ b) : (a - b) + (b - c) = a - c := begin convert tsub_add_cancel_of_le (tsub_le_tsub_right hab c) using 2, rw [tsub_tsub, add_tsub_cancel_of_le hbc], end lemma tsub_tsub_tsub_cancel_right (h : c ≤ b) : (a - c) - (b - c) = a - b := by rw [tsub_tsub, add_tsub_cancel_of_le h] /-! ### Lemmas that assume that an element is `add_le_cancellable`. -/ namespace add_le_cancellable protected lemma eq_tsub_iff_add_eq_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a = b - c ↔ a + c = b := begin split, { rintro rfl, exact tsub_add_cancel_of_le h }, { rintro rfl, exact (hc.add_tsub_cancel_right).symm } end protected lemma tsub_eq_iff_eq_add_of_le (hb : add_le_cancellable b) (h : b ≤ a) : a - b = c ↔ a = c + b := by rw [eq_comm, hb.eq_tsub_iff_add_eq_of_le h, eq_comm] protected lemma add_tsub_assoc_of_le (hc : add_le_cancellable c) (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := by conv_lhs { rw [← add_tsub_cancel_of_le h, add_comm c, ← add_assoc, hc.add_tsub_cancel_right] } protected lemma tsub_add_eq_add_tsub (hb : add_le_cancellable b) (h : b ≤ a) : a - b + c = a + c - b := by rw [add_comm a, hb.add_tsub_assoc_of_le h, add_comm] protected lemma tsub_tsub_assoc (hbc : add_le_cancellable (b - c)) (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := by rw [hbc.tsub_eq_iff_eq_add_of_le (tsub_le_self.trans h₁), add_assoc, add_tsub_cancel_of_le h₂, tsub_add_cancel_of_le h₁] protected lemma tsub_add_tsub_comm (hb : add_le_cancellable b) (hd : add_le_cancellable d) (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := by rw [hb.tsub_add_eq_add_tsub hba, ←hd.add_tsub_assoc_of_le hdc, tsub_tsub, add_comm d] protected lemma le_tsub_iff_left (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := ⟨add_le_of_le_tsub_left_of_le h, ha.le_tsub_of_add_le_left⟩ protected lemma le_tsub_iff_right (ha : add_le_cancellable a) (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := by { rw [add_comm], exact ha.le_tsub_iff_left h } protected lemma tsub_lt_iff_left (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < b + c := begin refine ⟨hb.lt_add_of_tsub_lt_left, _⟩, intro h, refine (tsub_le_iff_left.mpr h.le).lt_of_ne _, rintro rfl, exact h.ne' (add_tsub_cancel_of_le hba) end protected lemma tsub_lt_iff_right (hb : add_le_cancellable b) (hba : b ≤ a) : a - b < c ↔ a < c + b := by { rw [add_comm], exact hb.tsub_lt_iff_left hba } protected lemma lt_tsub_of_add_lt_right (hc : add_le_cancellable c) (h : a + c < b) : a < b - c := begin apply lt_of_le_of_ne, { rw [← add_tsub_cancel_of_le h.le, add_right_comm, add_assoc], rw [hc.add_tsub_assoc_of_le], refine le_self_add, refine le_add_self }, { rintro rfl, apply h.not_le, exact le_tsub_add } end protected lemma lt_tsub_of_add_lt_left (ha : add_le_cancellable a) (h : a + c < b) : c < b - a := by { apply ha.lt_tsub_of_add_lt_right, rwa add_comm } protected lemma tsub_lt_iff_tsub_lt (hb : add_le_cancellable b) (hc : add_le_cancellable c) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := by rw [hb.tsub_lt_iff_left h₁, hc.tsub_lt_iff_right h₂] protected lemma le_tsub_iff_le_tsub (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := by rw [ha.le_tsub_iff_left h₁, hc.le_tsub_iff_right h₂] protected lemma lt_tsub_iff_right_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ a + c < b := begin refine ⟨_, hc.lt_tsub_of_add_lt_right⟩, intro h2, refine (add_le_of_le_tsub_right_of_le h h2.le).lt_of_ne _, rintro rfl, apply h2.not_le, rw [hc.add_tsub_cancel_right] end protected lemma lt_tsub_iff_left_of_le (hc : add_le_cancellable c) (h : c ≤ b) : a < b - c ↔ c + a < b := by { rw [add_comm], exact hc.lt_tsub_iff_right_of_le h } protected lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hca : c ≤ a) (h : a - b < a - c) : c < b := begin conv_lhs at h { rw [← tsub_add_cancel_of_le hca] }, exact lt_of_add_lt_add_left (hb.lt_add_of_tsub_lt_right h), end protected lemma tsub_le_tsub_iff_left (ha : add_le_cancellable a) (hc : add_le_cancellable c) (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := begin refine ⟨_, λ h, tsub_le_tsub_left h a⟩, rw [tsub_le_iff_left, ← hc.add_tsub_assoc_of_le h, hc.le_tsub_iff_right (h.trans le_add_self), add_comm b], apply ha, end protected lemma tsub_right_inj (ha : add_le_cancellable a) (hb : add_le_cancellable b) (hc : add_le_cancellable c) (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := by simp_rw [le_antisymm_iff, ha.tsub_le_tsub_iff_left hb hba, ha.tsub_le_tsub_iff_left hc hca, and_comm] protected lemma tsub_lt_tsub_right_of_le (hc : add_le_cancellable c) (h : c ≤ a) (h2 : a < b) : a - c < b - c := by { apply hc.lt_tsub_of_add_lt_left, rwa [add_tsub_cancel_of_le h] } protected lemma tsub_inj_right (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := by { rw ← hab.inj, rw [tsub_add_cancel_of_le h₁, h₃, tsub_add_cancel_of_le h₂] } protected lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (hb : add_le_cancellable b) (hab : add_le_cancellable (a - b)) (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := begin refine ⟨hb.lt_of_tsub_lt_tsub_left_of_le h₂, _⟩, intro h, refine (tsub_le_tsub_left h.le _).lt_of_ne _, rintro h2, exact h.ne' (hab.tsub_inj_right h₁ h₂ h2) end @[simp] protected lemma add_tsub_tsub_cancel (hac : add_le_cancellable (a - c)) (h : c ≤ a) : (a + b) - (a - c) = b + c := (hac.tsub_eq_iff_eq_add_of_le $ tsub_le_self.trans le_self_add).mpr $ by rw [add_assoc, add_tsub_cancel_of_le h, add_comm] protected lemma tsub_tsub_cancel_of_le (hba : add_le_cancellable (b - a)) (h : a ≤ b) : b - (b - a) = a := by rw [hba.tsub_eq_iff_eq_add_of_le tsub_le_self, add_tsub_cancel_of_le h] end add_le_cancellable section contra /-! ### Lemmas where addition is order-reflecting. -/ variable [contravariant_class α α (+) (≤)] lemma eq_tsub_iff_add_eq_of_le (h : c ≤ b) : a = b - c ↔ a + c = b := contravariant.add_le_cancellable.eq_tsub_iff_add_eq_of_le h lemma tsub_eq_iff_eq_add_of_le (h : b ≤ a) : a - b = c ↔ a = c + b := contravariant.add_le_cancellable.tsub_eq_iff_eq_add_of_le h /-- See `add_tsub_le_assoc` for an inequality. -/ lemma add_tsub_assoc_of_le (h : c ≤ b) (a : α) : a + b - c = a + (b - c) := contravariant.add_le_cancellable.add_tsub_assoc_of_le h a lemma tsub_add_eq_add_tsub (h : b ≤ a) : a - b + c = a + c - b := contravariant.add_le_cancellable.tsub_add_eq_add_tsub h lemma tsub_tsub_assoc (h₁ : b ≤ a) (h₂ : c ≤ b) : a - (b - c) = a - b + c := contravariant.add_le_cancellable.tsub_tsub_assoc h₁ h₂ lemma tsub_add_tsub_comm (hba : b ≤ a) (hdc : d ≤ c) : a - b + (c - d) = a + c - (b + d) := contravariant.add_le_cancellable.tsub_add_tsub_comm contravariant.add_le_cancellable hba hdc lemma le_tsub_iff_left (h : a ≤ c) : b ≤ c - a ↔ a + b ≤ c := contravariant.add_le_cancellable.le_tsub_iff_left h lemma le_tsub_iff_right (h : a ≤ c) : b ≤ c - a ↔ b + a ≤ c := contravariant.add_le_cancellable.le_tsub_iff_right h lemma tsub_lt_iff_left (hbc : b ≤ a) : a - b < c ↔ a < b + c := contravariant.add_le_cancellable.tsub_lt_iff_left hbc lemma tsub_lt_iff_right (hbc : b ≤ a) : a - b < c ↔ a < c + b := contravariant.add_le_cancellable.tsub_lt_iff_right hbc /-- This lemma (and some of its corollaries also holds for `ennreal`, but this proof doesn't work for it. Maybe we should add this lemma as field to `has_ordered_sub`? -/ lemma lt_tsub_of_add_lt_right (h : a + c < b) : a < b - c := contravariant.add_le_cancellable.lt_tsub_of_add_lt_right h lemma lt_tsub_of_add_lt_left (h : a + c < b) : c < b - a := contravariant.add_le_cancellable.lt_tsub_of_add_lt_left h lemma tsub_lt_iff_tsub_lt (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < c ↔ a - c < b := contravariant.add_le_cancellable.tsub_lt_iff_tsub_lt contravariant.add_le_cancellable h₁ h₂ lemma le_tsub_iff_le_tsub (h₁ : a ≤ b) (h₂ : c ≤ b) : a ≤ b - c ↔ c ≤ b - a := contravariant.add_le_cancellable.le_tsub_iff_le_tsub contravariant.add_le_cancellable h₁ h₂ /-- See `lt_tsub_iff_right` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_right_of_le (h : c ≤ b) : a < b - c ↔ a + c < b := contravariant.add_le_cancellable.lt_tsub_iff_right_of_le h /-- See `lt_tsub_iff_left` for a stronger statement in a linear order. -/ lemma lt_tsub_iff_left_of_le (h : c ≤ b) : a < b - c ↔ c + a < b := contravariant.add_le_cancellable.lt_tsub_iff_left_of_le h /-- See `lt_of_tsub_lt_tsub_left` for a stronger statement in a linear order. -/ lemma lt_of_tsub_lt_tsub_left_of_le [contravariant_class α α (+) (<)] (hca : c ≤ a) (h : a - b < a - c) : c < b := contravariant.add_le_cancellable.lt_of_tsub_lt_tsub_left_of_le hca h lemma tsub_le_tsub_iff_left (h : c ≤ a) : a - b ≤ a - c ↔ c ≤ b := contravariant.add_le_cancellable.tsub_le_tsub_iff_left contravariant.add_le_cancellable h lemma tsub_right_inj (hba : b ≤ a) (hca : c ≤ a) : a - b = a - c ↔ b = c := contravariant.add_le_cancellable.tsub_right_inj contravariant.add_le_cancellable contravariant.add_le_cancellable hba hca lemma tsub_lt_tsub_right_of_le (h : c ≤ a) (h2 : a < b) : a - c < b - c := contravariant.add_le_cancellable.tsub_lt_tsub_right_of_le h h2 lemma tsub_inj_right (h₁ : b ≤ a) (h₂ : c ≤ a) (h₃ : a - b = a - c) : b = c := contravariant.add_le_cancellable.tsub_inj_right h₁ h₂ h₃ /-- See `tsub_lt_tsub_iff_left_of_le` for a stronger statement in a linear order. -/ lemma tsub_lt_tsub_iff_left_of_le_of_le [contravariant_class α α (+) (<)] (h₁ : b ≤ a) (h₂ : c ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le_of_le contravariant.add_le_cancellable h₁ h₂ @[simp] lemma add_tsub_tsub_cancel (h : c ≤ a) : (a + b) - (a - c) = b + c := contravariant.add_le_cancellable.add_tsub_tsub_cancel h /-- See `tsub_tsub_le` for an inequality. -/ lemma tsub_tsub_cancel_of_le (h : a ≤ b) : b - (b - a) = a := contravariant.add_le_cancellable.tsub_tsub_cancel_of_le h end contra end canonically_ordered_add_monoid /-! ### Lemmas in a linearly canonically ordered monoid. -/ section canonically_linear_ordered_add_monoid variables [canonically_linear_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] {a b c d : α} @[simp] lemma tsub_pos_iff_lt : 0 < a - b ↔ b < a := by rw [tsub_pos_iff_not_le, not_le] lemma tsub_eq_tsub_min (a b : α) : a - b = a - min a b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] }, end namespace add_le_cancellable protected lemma lt_tsub_iff_right (hc : add_le_cancellable c) : a < b - c ↔ a + c < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_right.mpr, hc.lt_tsub_of_add_lt_right⟩ protected lemma lt_tsub_iff_left (hc : add_le_cancellable c) : a < b - c ↔ c + a < b := ⟨lt_imp_lt_of_le_imp_le tsub_le_iff_left.mpr, hc.lt_tsub_of_add_lt_left⟩ protected lemma tsub_lt_tsub_iff_right (hc : add_le_cancellable c) (h : c ≤ a) : a - c < b - c ↔ a < b := by rw [hc.lt_tsub_iff_left, add_tsub_cancel_of_le h] protected lemma tsub_lt_self (ha : add_le_cancellable a) (h₁ : 0 < a) (h₂ : 0 < b) : a - b < a := begin refine tsub_le_self.lt_of_ne (λ h, _), rw [← h, tsub_pos_iff_lt] at h₁, exact h₂.not_le (ha.add_le_iff_nonpos_left.1 $ add_le_of_le_tsub_left_of_le h₁.le h.ge), end protected lemma tsub_lt_self_iff (ha : add_le_cancellable a) : a - b < a ↔ 0 < a ∧ 0 < b := begin refine ⟨λ h, ⟨(zero_le _).trans_lt h, (zero_le b).lt_of_ne _⟩, λ h, ha.tsub_lt_self h.1 h.2⟩, rintro rfl, rw [tsub_zero] at h, exact h.false end /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ protected lemma tsub_lt_tsub_iff_left_of_le (ha : add_le_cancellable a) (hb : add_le_cancellable b) (h : b ≤ a) : a - b < a - c ↔ c < b := lt_iff_lt_of_le_iff_le $ ha.tsub_le_tsub_iff_left hb h end add_le_cancellable section contra variable [contravariant_class α α (+) (≤)] /-- This lemma also holds for `ennreal`, but we need a different proof for that. -/ lemma tsub_lt_tsub_iff_right (h : c ≤ a) : a - c < b - c ↔ a < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_right h lemma tsub_lt_self : 0 < a → 0 < b → a - b < a := contravariant.add_le_cancellable.tsub_lt_self lemma tsub_lt_self_iff : a - b < a ↔ 0 < a ∧ 0 < b := contravariant.add_le_cancellable.tsub_lt_self_iff /-- See `lt_tsub_iff_left_of_le_of_le` for a weaker statement in a partial order. -/ lemma tsub_lt_tsub_iff_left_of_le (h : b ≤ a) : a - b < a - c ↔ c < b := contravariant.add_le_cancellable.tsub_lt_tsub_iff_left_of_le contravariant.add_le_cancellable h end contra /-! ### Lemmas about `max` and `min`. -/ lemma tsub_add_eq_max : a - b + b = max a b := begin cases le_total a b with h h, { rw [max_eq_right h, tsub_eq_zero_iff_le.mpr h, zero_add] }, { rw [max_eq_left h, tsub_add_cancel_of_le h] } end lemma add_tsub_eq_max : a + (b - a) = max a b := by rw [add_comm, max_comm, tsub_add_eq_max] lemma tsub_min : a - min a b = a - b := begin cases le_total a b with h h, { rw [min_eq_left h, tsub_self, tsub_eq_zero_iff_le.mpr h] }, { rw [min_eq_right h] } end lemma tsub_add_min : a - b + min a b = a := by { rw [← tsub_min, tsub_add_cancel_of_le], apply min_le_left } end canonically_linear_ordered_add_monoid namespace with_top section variables [has_sub α] [has_zero α] /-- If `α` has subtraction and `0`, we can extend the subtraction to `with_top α`. -/ protected def sub : Π (a b : with_top α), with_top α | _ ⊤ := 0 | ⊤ (x : α) := ⊤ | (x : α) (y : α) := (x - y : α) instance : has_sub (with_top α) := ⟨with_top.sub⟩ @[simp, norm_cast] lemma coe_sub {a b : α} : (↑(a - b) : with_top α) = ↑a - ↑b := rfl @[simp] lemma top_sub_coe {a : α} : (⊤ : with_top α) - a = ⊤ := rfl @[simp] lemma sub_top {a : with_top α} : a - ⊤ = 0 := by { cases a; refl } end variables [canonically_ordered_add_monoid α] [has_sub α] [has_ordered_sub α] instance : has_ordered_sub (with_top α) := begin constructor, rintro x y z, induction y using with_top.rec_top_coe, { simp }, induction x using with_top.rec_top_coe, { simp }, induction z using with_top.rec_top_coe, { simp }, norm_cast, exact tsub_le_iff_right end end with_top
0cbdb546abc516e9b55191ebbaf6332a882ed32f
1b8f093752ba748c5ca0083afef2959aaa7dace5
/src/category_theory/idempotent_completion.lean
4b37ca474687b2ff0a2865ec7730adc31fc2ebdd
[]
no_license
khoek/lean-category-theory
7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386
63dcb598e9270a3e8b56d1769eb4f825a177cd95
refs/heads/master
1,585,251,725,759
1,539,344,445,000
1,539,344,445,000
145,281,070
0
0
null
1,534,662,376,000
1,534,662,376,000
null
UTF-8
Lean
false
false
4,222
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.equivalence namespace category_theory universes u u₁ u₂ structure Idempotent (C : Type (u+1)) [large_category C] := (object : C) (idempotent : object ⟶ object) (witness' : idempotent ≫ idempotent = idempotent . obviously) restate_axiom Idempotent.witness' attribute [simp,search] Idempotent.witness local attribute [search] subtype.property variables {C : Type (u+1)} [large_category C] namespace Idempotent structure morphism (X Y : Idempotent C) := (morphism : X.object ⟶ Y.object) (left' : X.idempotent ≫ morphism = morphism . obviously) (right' : morphism ≫ Y.idempotent = morphism . obviously) restate_axiom morphism.left' restate_axiom morphism.right' attribute [simp,search] morphism.left morphism.right @[extensionality] lemma ext {X Y : Idempotent C} (f g : morphism X Y) (w : f.morphism = g.morphism) : f = g := begin induction f, induction g, tidy end end Idempotent instance IdempotentCompletion : large_category (Idempotent C) := { hom := Idempotent.morphism, id := λ X, ⟨ X.idempotent ⟩, comp := λ X Y Z f g, ⟨ f.morphism ≫ g.morphism ⟩ } namespace IdempotentCompletion def functor_to_completion (C : Type (u+1)) [large_category C] : C ⥤ (Idempotent C) := { obj := λ X, { object := X, idempotent := 𝟙 X }, map' := λ _ _ f, { morphism := f } } -- -- PROJECT -- def IdempotentCompletion_functorial (C : Type u) [category C] (D : Type u) [category D] : Functor (Functor C D) (Functor (Idempotent C) (Idempotent D)) := { -- FIXME -- lemma embedding' (C : Type (u+1)) [large_category C] : embedding (functor_to_completion C) := by obviously variable {D : Type (u₂+1)} variable [large_category D] def restrict_Functor_from (F : (Idempotent C) ⥤ D) : C ⥤ D := (functor_to_completion C) ⋙ F @[simp] private lemma double_idempotent_morphism_left (X Y : Idempotent (Idempotent C)) (f : X ⟶ Y) : (X.idempotent).morphism ≫ (f.morphism).morphism = (f.morphism).morphism := congr_arg Idempotent.morphism.morphism f.left @[simp] private lemma double_idempotent_morphism_right (X Y : Idempotent (Idempotent C)) (f : X ⟶ Y) : (f.morphism).morphism ≫ (Y.idempotent).morphism = (f.morphism).morphism := congr_arg Idempotent.morphism.morphism f.right private def idempotent_functor (C : Type (u+1)) [large_category C] : (Idempotent (Idempotent C)) ⥤ (Idempotent C) := { obj := λ X, ⟨ X.object.object, X.idempotent.morphism, congr_arg Idempotent.morphism.morphism X.witness ⟩, -- PROJECT think about automation here map' := λ X Y f, ⟨ f.morphism.morphism, by obviously ⟩ } private def idempotent_inverse (C : Type (u+1)) [large_category C] : (Idempotent C) ⥤ (Idempotent (Idempotent C)) := { obj := λ X, ⟨ X, ⟨ X.idempotent, by obviously ⟩, by obviously ⟩, map' := λ X Y f, ⟨ f, by obviously ⟩ } -- PROJECT prove these lemmas about idempotent completion -- lemma IdempotentCompletion_idempotent (C : Type u) [category C] : -- equivalence (IdempotentCompletion (IdempotentCompletion C)) (IdempotentCompletion C) := -- { -- functor := IdempotentCompletion_idempotent_functor C, -- inverse := IdempotentCompletion_idempotent_inverse C, -- isomorphism_1 := begin tidy, exact C.identity _, tidy, induction f_2, tidy, end, -- PROJECT very slow?? -- isomorphism_2 := sorry --} def extend_Functor_to_completion (F : C ⥤ (Idempotent D)) : (Idempotent C) ⥤ (Idempotent D) := { obj := λ X, { object := (F X.object).object, idempotent := (F.map X.idempotent).morphism }, map' := λ X Y f, { morphism := (F.map f.morphism).morphism } } -- lemma Functor_from_IdempotentCompletion_determined_by_restriction -- {C D : Category} (F : Functor (IdempotentCompletion C) (IdempotentCompletion D)) : -- NaturalIsomorphism (extend_Functor_to_IdempotentCompletion (restrict_Functor_from_IdempotentCompletion F)) F := -- sorry -- PROJECT idempotent completion left adjoint to the forgetful functor from categories to semicategories? end IdempotentCompletion end category_theory
4bbf06bbe4889b78f31920ec6dcf6e7aa7502dc5
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/control/monad/cont.lean
f92d479527385c537c1344bd3b317fe0082bc6bc
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
8,808
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Monad encapsulating continuation passing programming style, similar to Haskell's `Cont`, `ContT` and `MonadCont`: <http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html> -/ import control.monad.writer universes u v w structure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) := (apply : α → m β) def monad_cont.goto {α β} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) := f.apply x class monad_cont (m : Type u → Type v) := (call_cc : Π {α β}, ((monad_cont.label α m β) → m α) → m α) open monad_cont section prio set_option default_priority 100 -- see Note [default priority] class is_lawful_monad_cont (m : Type u → Type v) [monad m] [monad_cont m] extends is_lawful_monad m := (call_cc_bind_right {α ω γ} (cmd : m α) (next : (label ω m γ) → α → m ω) : call_cc (λ f, cmd >>= next f) = cmd >>= λ x, call_cc (λ f, next f x)) (call_cc_bind_left {α} (β) (x : α) (dead : label α m β → β → m α) : call_cc (λ f : label α m β, goto f x >>= dead f) = pure x) (call_cc_dummy {α β} (dummy : m α) : call_cc (λ f : label α m β, dummy) = dummy) end prio export is_lawful_monad_cont def cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r @[reducible] def cont (r : Type u) (α : Type w) := cont_t r id α namespace cont_t export monad_cont (label goto) variables {r : Type u} {m : Type u → Type v} {α β γ ω : Type w} def run : cont_t r m α → (α → m r) → m r := id def map (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x lemma run_cont_t_map_cont_t (f : m r → m r) (x : cont_t r m α) : run (map f x) = f ∘ run x := rfl def with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β := λ g, x $ f g lemma run_with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f := rfl @[ext] protected lemma ext {x y : cont_t r m α} (h : ∀ f, x.run f = y.run f) : x = y := by { ext; apply h } instance : monad (cont_t r m) := { pure := λ α x f, f x, bind := λ α β x f g, x $ λ i, f i g } instance : is_lawful_monad (cont_t r m) := { id_map := by { intros, refl }, pure_bind := by { intros, ext, refl }, bind_assoc := by { intros, ext, refl } } def monad_lift [monad m] {α} : m α → cont_t r m α := λ x f, x >>= f instance [monad m] : has_monad_lift m (cont_t r m) := { monad_lift := λ α, cont_t.monad_lift } lemma monad_lift_bind [monad m] [is_lawful_monad m] {α β} (x : m α) (f : α → m β) : (monad_lift (x >>= f) : cont_t r m β) = monad_lift x >>= monad_lift ∘ f := by { ext, simp only [monad_lift,has_monad_lift.monad_lift,(∘),(>>=),bind_assoc,id.def,run,cont_t.monad_lift] } instance : monad_cont (cont_t r m) := { call_cc := λ α β f g, f ⟨λ x h, g x⟩ g } instance : is_lawful_monad_cont (cont_t r m) := { call_cc_bind_right := by intros; ext; refl, call_cc_bind_left := by intros; ext; refl, call_cc_dummy := by intros; ext; refl } instance (ε) [monad_except ε m] : monad_except ε (cont_t r m) := { throw := λ x e f, throw e, catch := λ α act h f, catch (act f) (λ e, h e f) } instance : monad_run (λ α, (α → m r) → ulift.{u v} (m r)) (cont_t.{u v u} r m) := { run := λ α f x, ⟨ f x ⟩ } end cont_t variables {m : Type u → Type v} [monad m] def except_t.mk_label {α β ε} : label (except.{u u} ε α) m β → label α (except_t ε m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (except.ok a) ⟩ lemma except_t.goto_mk_label {α β ε : Type*} (x : label (except.{u u} ε α) m β) (i : α) : goto (except_t.mk_label x) i = ⟨ except.ok <$> goto x (except.ok i) ⟩ := by cases x; refl def except_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α := except_t.mk (call_cc $ λ x : label _ m β, except_t.run $ f (except_t.mk_label x) : m (except ε α)) instance {ε} [monad_cont m] : monad_cont (except_t ε m) := { call_cc := λ α β, except_t.call_cc } instance {ε} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) := { call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp, congr, ext ⟨ ⟩; simp [except_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right,except_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,except_t.call_cc,@call_cc_dummy m _], ext, refl }, } def option_t.mk_label {α β} : label (option.{u} α) m β → label α (option_t m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (some a) ⟩ lemma option_t.goto_mk_label {α β : Type*} (x : label (option.{u} α) m β) (i : α) : goto (option_t.mk_label x) i = ⟨ some <$> goto x (some i) ⟩ := by cases x; refl def option_t.call_cc [monad_cont m] {α β : Type*} (f : label α (option_t m) β → option_t m α) : option_t m α := option_t.mk (call_cc $ λ x : label _ m β, option_t.run $ f (option_t.mk_label x) : m (option α)) instance [monad_cont m] : monad_cont (option_t m) := { call_cc := λ α β, option_t.call_cc } instance [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) := { call_cc_bind_right := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right], ext, dsimp, congr, ext ⟨ ⟩; simp [option_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right,option_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,option_t.call_cc,@call_cc_dummy m _], ext, refl }, } def writer_t.mk_label {α β ω} [has_one ω] : label (α × ω) m β → label α (writer_t ω m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (a,1) ⟩ lemma writer_t.goto_mk_label {α β ω : Type*} [has_one ω] (x : label (α × ω) m β) (i : α) : goto (writer_t.mk_label x) i = monad_lift (goto x (i,1)) := by cases x; refl def writer_t.call_cc [monad_cont m] {α β ω : Type*} [has_one ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α := ⟨ call_cc (writer_t.run ∘ f ∘ writer_t.mk_label : label (α × ω) m β → m (α × ω)) ⟩ instance (ω) [monad m] [has_one ω] [monad_cont m] : monad_cont (writer_t ω m) := { call_cc := λ α β, writer_t.call_cc } def state_t.mk_label {α β σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β | ⟨ f ⟩ := ⟨ λ a, ⟨ λ s, f (a,s) ⟩ ⟩ lemma state_t.goto_mk_label {α β σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) : goto (state_t.mk_label x) i = ⟨ λ s, (goto x (i,s)) ⟩ := by cases x; refl def state_t.call_cc {σ} [monad_cont m] {α β : Type*} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α := ⟨ λ r, call_cc (λ f', (f $ state_t.mk_label f').run r) ⟩ instance {σ} [monad_cont m] : monad_cont (state_t σ m) := { call_cc := λ α β, state_t.call_cc } instance {σ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) := { call_cc_bind_right := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind], ext, dsimp, congr, ext ⟨x₀,x₁⟩, refl }, call_cc_bind_left := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_left,(>>=),state_t.bind,state_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind,@call_cc_dummy m _], ext, refl }, } def reader_t.mk_label {α β} (ρ) : label α m β → label α (reader_t ρ m) β | ⟨ f ⟩ := ⟨ monad_lift ∘ f ⟩ lemma reader_t.goto_mk_label {α ρ β} (x : label α m β) (i : α) : goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := by cases x; refl def reader_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α := ⟨ λ r, call_cc (λ f', (f $ reader_t.mk_label _ f').run r) ⟩ instance {ρ} [monad_cont m] : monad_cont (reader_t ρ m) := { call_cc := λ α β, reader_t.call_cc } instance {ρ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) := { call_cc_bind_right := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_right], ext, refl }, call_cc_bind_left := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_left,reader_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,reader_t.call_cc,@call_cc_dummy m _], ext, refl } }
6889c0a1318f9094eb5c67ae6b84842a7e5d9e23
94e33a31faa76775069b071adea97e86e218a8ee
/src/tactic/linear_combination.lean
24b435ba60b8fc659fcc0a3b7a8208f0fcabfdf6
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
16,216
lean
/- Copyright (c) 2022 Abby J. Goldberg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Abby J. Goldberg -/ import tactic.ring /-! # linear_combination Tactic In this file, the `linear_combination` tactic is created. This tactic, which works over `ring`s, attempts to prove the target by creating and applying a linear combination of a list of equalities. This file also includes a definition for `linear_combination_config`. A `linear_combination_config` object can be passed into the tactic, allowing the user to specify a normalization tactic. ## Implementation Notes This tactic works by creating a weighted sum of the given equations with the given coefficients. Then, it subtracts the right side of the weighted sum from the left side so that the right side equals 0, and it does the same with the target. Afterwards, it sets the goal to be the equality between the lefthand side of the new goal and the lefthand side of the new weighted sum. Lastly, it uses a normalization tactic to see if the weighted sum is equal to the target. ## References * <https://leanprover.zulipchat.com/#narrow/stream/239415-metaprogramming-.2F.20tactics/topic/Linear.20algebra.20tactic/near/213928196> -/ namespace linear_combo open tactic /-! ### Lemmas -/ lemma left_mul_both_sides {α} [h : has_mul α] {x y : α} (z : α) (h1 : x = y) : z * x = z * y := congr_arg (has_mul.mul z) h1 lemma sum_two_equations {α} [h : has_add α] {x1 y1 x2 y2 : α} (h1 : x1 = y1) (h2: x2 = y2) : x1 + x2 = y1 + y2 := congr (congr_arg has_add.add h1) h2 lemma left_minus_right {α} [h : add_group α] {x y : α} (h1 : x = y) : x - y = 0 := sub_eq_zero.mpr h1 lemma all_on_left_equiv {α} [h : add_group α] (x y : α) : (x = y) = (x - y = 0) := propext (⟨left_minus_right, sub_eq_zero.mp⟩) lemma replace_eq_expr {α} [h : has_zero α] {x y : α} (h1 : x = 0) (h2 : y = x) : y = 0 := by rwa h2 /-! ### Configuration -/ /-- A configuration object for `linear_combination`. `normalize` describes whether or not the normalization step should be used. `normalization_tactic` describes the tactic used for normalization when checking if the weighted sum is equivalent to the goal (when `normalize` is `tt`). -/ meta structure linear_combination_config : Type := (normalize : bool := tt) (normalization_tactic : tactic unit := `[ring1]) /-! ### Part 1: Multiplying Equations by Constants and Adding Them Together -/ /-- Given that `lhs = rhs`, this tactic returns an `expr` proving that `coeff * lhs = coeff * rhs`. * Input: * `h_equality` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `has_mul α` * `coeff` : a `pexpr`, which should be a value of type `α` * Output: an `expr`, which proves that the result of multiplying both sides of `h_equality` by the `coeff` holds -/ meta def mul_equality_expr (h_equality : expr) (coeff : pexpr) : tactic expr := do `(%%lhs = %%rhs) ← infer_type h_equality, -- Mark the coefficient as having the same type as the sides of `h_equality` - -- this is necessary in order to use the left_mul_both_sides lemma left_type ← infer_type lhs, coeff_expr ← to_expr ``(%%coeff : %%left_type), mk_app ``left_mul_both_sides [coeff_expr, h_equality] /-- Given two hypotheses that `a = b` and `c = d`, this tactic returns an `expr` proving that `a + c = b + d`. * Input: * `h_equality1` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `has_add α` * `h_equality2` : an `expr`, whose type should be an equality between terms of type `α` * Output: an `expr`, which proves that the result of adding the two equalities holds -/ meta def sum_equalities (h_equality1 h_equality2 : expr) : tactic expr := mk_app ``sum_two_equations [h_equality1, h_equality2] /-- Given that `a = b` and `c = d`, along with a coefficient, this tactic returns an `expr` proving that `a + coeff * c = b + coeff * d`. * Input: * `h_equality1` : an `expr`, whose type should be an equality between terms of type `α`, where there are instances of `has_add α` and `has_mul α` * `h_equality2` : an `expr`, whose type should be an equality between terms of type `α` * `coeff_for_eq2` : a `pexpr`, which should be a value of type `α` * Output: an `expr`, which proves that the result of adding the first equality to the result of multiplying `coeff_for_eq2` by the second equality holds -/ meta def sum_two_hyps_one_mul_helper (h_equality1 h_equality2 : expr) (coeff_for_eq2 : pexpr) : tactic expr := mul_equality_expr h_equality2 coeff_for_eq2 >>= sum_equalities h_equality1 /-- Given that `l_sum1 = r_sum1`, `l_h1 = r_h1`, ..., `l_hn = r_hn`, and given coefficients `c_1`, ..., `c_n`, this tactic returns an `expr` proving that `l_sum1 + (c_1 * l_h1) + ... + (c_n * l_hn)` `= r_sum1 + (c_1 * r_h1) + ... + (c_n * r_hn)` * Input: * `expected_tp`: the type of the terms being compared in the target equality * an `option (tactic expr)` : `none`, if there is no sum to add to yet, or `some` containing the base summation equation * a `list name` : a list of names, referring to equalities in the local context * a `list pexpr` : a list of coefficients to be multiplied with the corresponding equalities in the list of names * Output: an `expr`, which proves that the weighted sum of the given equalities added to the base equation holds -/ meta def make_sum_of_hyps_helper (expected_tp : expr) : option (tactic expr) → list expr → list pexpr → tactic expr | none [] [] := to_expr ``(rfl : (0 : %%expected_tp) = 0) | (some tactic_hcombo) [] [] := do tactic_hcombo | none (h_equality :: h_eqs_names) (coeff :: coeffs) := do -- This is the first equality, and we do not have anything to add to it -- h_equality ← get_local h_equality_nam, `(@eq %%eqtp _ _) ← infer_type h_equality | fail!"{h_equality} is expected to be a proof of an equality", is_def_eq eqtp expected_tp <|> fail!("{h_equality} is an equality between terms of type {eqtp}, but is expected to be" ++ " between terms of type {expected_tp}"), make_sum_of_hyps_helper (some (mul_equality_expr h_equality coeff)) h_eqs_names coeffs | (some tactic_hcombo) (h_equality :: h_eqs_names) (coeff :: coeffs) := do -- h_equality ← get_local h_equality_nam, hcombo ← tactic_hcombo, -- We want to add this weighted equality to the current equality in -- the hypothesis make_sum_of_hyps_helper (some (sum_two_hyps_one_mul_helper hcombo h_equality coeff)) h_eqs_names coeffs | _ _ _ := do fail ("The length of the input list of equalities should be the " ++ "same as the length of the input list of coefficients") /-- Given a list of names referencing equalities and a list of pexprs representing coefficients, this tactic proves that a weighted sum of the equalities (where each equation is multiplied by the corresponding coefficient) holds. * Input: * `expected_tp`: the type of the terms being compared in the target equality * `h_eqs_names` : a list of names, referring to equalities in the local context * `coeffs` : a list of coefficients to be multiplied with the corresponding equalities in the list of names * Output: an `expr`, which proves that the weighted sum of the equalities holds -/ meta def make_sum_of_hyps (expected_tp : expr) (h_eqs_names : list expr) (coeffs : list pexpr) : tactic expr := make_sum_of_hyps_helper expected_tp none h_eqs_names coeffs /-! ### Part 2: Simplifying -/ /-- This tactic proves that the result of moving all the terms in an equality to the left side of the equals sign by subtracting the right side of the equation from the left side holds. In other words, given `lhs = rhs`, this tactic proves that `lhs - rhs = 0`. * Input: * `h_equality` : an `expr`, whose type should be an equality between terms of type `α`, where there is an instance of `add_group α` * Output: an `expr`, which proves that `lhs - rhs = 0`, where `lhs` and `rhs` are the left and right sides of `h_equality` respectively -/ meta def move_to_left_side (h_equality : expr) : tactic expr := mk_app ``left_minus_right [h_equality] /-- This tactic replaces the target with the result of moving all the terms in the target to the left side of the equals sign by subtracting the right side of the equation from the left side. In other words, when the target is lhs = rhs, this tactic proves that `lhs - rhs = 0` and replaces the target with this new equality. Note: The target must be an equality when this tactic is called, and the equality must have some type `α` on each side, where there is an instance of `add_group α`. * Input: N/A * Output: N/A -/ meta def move_target_to_left_side : tactic unit := do -- Move all the terms in the target equality to the left side target ← target, (targ_lhs, targ_rhs) ← match_eq target, target_left_eq ← to_expr ``(%%targ_lhs - %%targ_rhs = 0), mk_app ``all_on_left_equiv [targ_lhs, targ_rhs] >>= replace_target target_left_eq /-! ### Part 3: Matching the Linear Combination to the Target -/ /-- This tactic changes the goal to be that the lefthand side of the target is equal to the lefthand side of the given expression. For example, if `hsum_on_left` is `5*x - 5*y = 0`, and the target is `-5*y + 5*x = 0`, this tactic will change the target to be `-5*y + 5*x = 5*x - 5*y`. This tactic only should be used when the target's type an equality whose right side is 0. * Input: * `hsum_on_left` : expr, whose type should be an equality with 0 on the right side of the equals sign * Output: N/A -/ meta def set_goal_to_hleft_eq_tleft (hsum_on_left : expr) : tactic unit := do to_expr ``(replace_eq_expr %%hsum_on_left) >>= apply, skip /-- This tactic attempts to prove the goal by normalizing the target if the `normalize` field of the given configuration is true. * Input: * `config` : a `linear_combination_config`, which determines the tactic used for normalization if normalization is done * Output: N/A -/ meta def prove_equal_if_desired (config : linear_combination_config) : tactic unit := when config.normalize config.normalization_tactic /-! ### Part 4: Completed Tactic -/ /-- This is a tactic that attempts to prove the target by creating and applying a linear combination of a list of equalities. (If the `normalize` field of the configuration is set to ff, then the tactic will simply set the user up to prove their target using the linear combination instead of attempting to finish the proof.) Note: The left and right sides of all the equalities should have the same ring type, and the coefficients should also have this type. There must be instances of `has_mul` and `add_group` for this type. Also note that the target must involve at least one variable. * Input: * `h_eqs_names` : a list of names, referring to equations in the local context * `coeffs` : a list of coefficients to be multiplied with the corresponding equations in the list of names * `config` : a `linear_combination_config`, which determines the tactic used for normalization; by default, this value is the standard configuration for a `linear_combination_config` * Output: N/A -/ meta def linear_combination (h_eqs_names : list pexpr) (coeffs : list pexpr) (config : linear_combination_config := {}) : tactic unit := do `(@eq %%ext _ _) ← target | fail "linear_combination can only be used to prove equality goals", h_eqs ← h_eqs_names.mmap to_expr, hsum ← make_sum_of_hyps ext h_eqs coeffs, hsum_on_left ← move_to_left_side hsum, move_target_to_left_side, set_goal_to_hleft_eq_tleft hsum_on_left, prove_equal_if_desired config /-- `mk_mul [p₀, p₁, ..., pₙ]` produces the pexpr `p₀ * p₁ * ... * pₙ`. -/ meta def mk_mul : list pexpr → pexpr | [] := ``(1) | [e] := e | (e::es) := ``(%%e * %%(mk_mul es)) /-- `as_linear_combo neg ms e` is used to parse the argument to `linear_combination`. This argument is a sequence of literals `x`, `-x`, or `c*x` combined with `+` or `-`, given by the pexpr `e`. The `neg` and `ms` arguments are used recursively; called at the top level, its usage should be `as_linear_combo ff [] e`. -/ meta def as_linear_combo : bool → list pexpr → pexpr → list (pexpr × pexpr) | neg ms e := let (head, args) := pexpr.get_app_fn_args e in match head.get_frozen_name, args with | ``has_add.add, [e1, e2] := as_linear_combo neg ms e1 ++ as_linear_combo neg ms e2 | ``has_sub.sub, [e1, e2] := as_linear_combo neg ms e1 ++ as_linear_combo (bnot neg) ms e2 | ``has_mul.mul, [e1, e2] := as_linear_combo neg (e1::ms) e2 | ``has_div.div, [e1, e2] := as_linear_combo neg (``((%%e2)⁻¹)::ms) e1 | ``has_neg.neg, [e1] := as_linear_combo (bnot neg) ms e1 | _, _ := let m := mk_mul ms in [(e, if neg then ``(-%%m) else m)] end section interactive_mode setup_tactic_parser /-- `linear_combination` attempts to prove the target by creating and applying a linear combination of a list of equalities. The tactic will create a linear combination by adding the equalities together from left to right, so the order of the input hypotheses does matter. If the `normalize` field of the configuration is set to false, then the tactic will simply set the user up to prove their target using the linear combination instead of attempting to finish the proof. Note: The left and right sides of all the equalities should have the same type, and the coefficients should also have this type. There must be instances of `has_mul` and `add_group` for this type. * Input: * `input` : the linear combination of proofs of equalities, given as a sum/difference of coefficients multiplied by expressions. The coefficients may be arbitrary pre-expressions; if a coefficient is an application of `+` or `-` it should be surrounded by parentheses. The expressions can be arbitrary proof terms proving equalities. Most commonly they are hypothesis names `h1, h2, ...`. If a coefficient is omitted, it is taken to be `1`. * `config` : a `linear_combination_config`, which determines the tactic used for normalization; by default, this value is the standard configuration for a linear_combination_config. In the standard configuration, `normalize` is set to tt (meaning this tactic is set to use normalization), and `normalization_tactic` is set to `ring1`. Example Usage: ``` example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination 1*h1 - 2*h2 example (x y : ℤ) (h1 : x*y + 2*x = 1) (h2 : x = y) : x*y = -2*y + 1 := by linear_combination h1 - 2*h2 example (x y z : ℝ) (ha : x + 2*y - z = 4) (hb : 2*x + y + z = -2) (hc : x + 2*y + z = 2) : -3*x - 3*y - 4*z = 2 := by linear_combination ha - hb - 2*hc example (x y : ℚ) (h1 : x + y = 3) (h2 : 3*x = 7) : x*x*y + y*x*y + 6*x = 3*x*y + 14 := by linear_combination x*y*h1 + 2*h2 example (x y : ℤ) (h1 : x = -3) (h2 : y = 10) : 2*x = -6 := begin linear_combination 2*h1 with {normalize := ff}, simp, norm_cast end constants (qc : ℚ) (hqc : qc = 2*qc) example (a b : ℚ) (h : ∀ p q : ℚ, p = q) : 3*a + qc = 3*b + 2*qc := by linear_combination 3 * h a b + hqc ``` -/ meta def _root_.tactic.interactive.linear_combination (input : parse (as_linear_combo ff [] <$> texpr)?) (_ : parse (tk "with")?) (config : linear_combination_config := {}) : tactic unit := let (h_eqs_names, coeffs) := list.unzip (input.get_or_else []) in linear_combination h_eqs_names coeffs config add_tactic_doc { name := "linear_combination", category := doc_category.tactic, decl_names := [`tactic.interactive.linear_combination], tags := ["arithmetic"] } end interactive_mode end linear_combo
af06f06d487ac6e9196a4986759f6bf05414fa16
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/assert_exists/test1.lean
aa2cfcc31bbe1564cef64f28248d17d59b4afc63
[ "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
157
lean
import tactic.assert_exists import logic.nontrivial assert_exists nat assert_not_exists rat assert_instance monad option assert_no_instance nontrivial nat
8ee9a74458e460eaddc55560eb0eada19f0d65d7
664d56f0f2c151a9cad4364e1985b16d7451c93e
/mm0-lean/x86/lemmas.lean
2295ce068d98eec00bec4bf0b0fb3a7704b35591
[ "CC0-1.0" ]
permissive
mattsse/mm0
fc684080b092c3bed865afaa92ea16ae71c179d5
247fd3e2ac65eec7d5317285bb2fee639b17a63f
refs/heads/master
1,608,054,450,033
1,580,386,002,000
1,580,386,002,000
235,200,156
0
0
CC0-1.0
1,579,554,774,000
1,579,554,773,000
null
UTF-8
Lean
false
false
62,519
lean
import x86.x86 data.list.basic data.zmod.basic namespace bitvec theorem of_nat_zero (n) : bitvec.of_nat n 0 = 0 := by induction n; [refl, exact congr_arg (vector.cons ff) n_ih] theorem of_nat_one (n) : bitvec.of_nat n 1 = 1 := by cases n; [refl, exact congr_arg (vector.cons tt) (of_nat_zero _)] theorem from_bits_fill_eq : ∀ {n b l} (e : list.length l = n), from_bits_fill b l = ⟨l, e⟩ | 0 b [] e := rfl | (n+1) b (a :: l) e := by rw [from_bits_fill, from_bits_fill_eq (nat.succ_inj e)]; refl theorem bits_to_nat_zero (n) : bits_to_nat (list.repeat ff n) = 0 := by simp [bits_to_nat]; induction n; simp * @[simp] theorem bits_to_nat_cons (a l) : bits_to_nat (a :: l) = nat.bit a (bits_to_nat l) := rfl @[simp] theorem to_nat_nil : to_nat vector.nil = 0 := rfl @[simp] theorem to_nat_zero (n) : to_nat (0 : bitvec n) = 0 := bits_to_nat_zero _ @[simp] theorem to_nat_cons (b) {n} (v : bitvec n) : to_nat (b :: v) = nat.bit b (to_nat v) := by cases v; refl @[simp] theorem of_nat_succ (n i : ℕ) : bitvec.of_nat n.succ i = i.bodd :: bitvec.of_nat n i.div2 := by rw [bitvec.of_nat, nat.bodd_div2_eq, bitvec.of_nat] @[simp] theorem of_nat_bit (n : ℕ) (b i) : bitvec.of_nat n.succ (nat.bit b i) = b :: bitvec.of_nat n i := by rw [of_nat_succ, nat.div2_bit, nat.bodd_bit] theorem of_nat_bits_to_nat {n} (l : list bool) : bitvec.of_nat n (bits_to_nat l) = from_bits_fill ff l := begin rw bits_to_nat, induction l generalizing n, exact of_nat_zero _, cases n, refl, simp [*, bits_to_nat, from_bits_fill, bitvec.of_nat, nat.bodd_bit, nat.div2_bit] end theorem of_nat_bits_to_nat_eq {n} (l : list bool) (e : l.length = n) : bitvec.of_nat n (bits_to_nat l) = ⟨l, e⟩ := begin induction n generalizing l; cases l; injection e, refl, simp [bits_to_nat, nat.div2_bit, nat.bodd_bit], exact congr_arg (vector.cons l_hd) (n_ih _ h_1) end @[simp] theorem of_nat_to_nat : ∀ {n} (v : bitvec n), bitvec.of_nat n (to_nat v) = v | n ⟨l, e⟩ := of_nat_bits_to_nat_eq l e theorem to_nat_of_nat_aux (m n b) : nat.bit b (n % 2 ^ m) = nat.bit b n % 2 ^ nat.succ m := begin have := nat.mod_add_div (n.bit b) (2^m * 2), conv at this { to_rhs, rw [nat.bit_val, ← nat.mod_add_div n (2^m), mul_add, add_right_comm, ← nat.bit_val, mul_left_comm, ← mul_assoc] }, rw [nat.pow_succ], refine add_right_cancel (this.symm.trans _), congr' 2, rw [mul_comm, ← nat.div_div_eq_div_mul, ← nat.div2_val, nat.div2_bit] end theorem to_nat_of_nat (m n) : to_nat (bitvec.of_nat m n) = n % 2 ^ m := begin induction m generalizing n, { simp [bitvec.of_nat, to_nat], refl }, simp [bitvec.of_nat, m_ih], conv { to_rhs, rw ← nat.bit_decomp n }, apply to_nat_of_nat_aux end theorem to_nat_lt_pow2 {n} (v : bitvec n) : to_nat v < 2 ^ n := begin rw [← of_nat_to_nat v, to_nat_of_nat], exact nat.mod_lt _ (nat.pow_pos dec_trivial _), end def pow2 (n : ℕ) : ℕ+ := ⟨2^n, nat.pow_pos dec_trivial _⟩ def to_zmod {n} (v : bitvec n) : zmod (pow2 n) := bitvec.to_nat v def of_zmod {n} (i : zmod (pow2 n)) : bitvec n := bitvec.of_nat _ i.1 theorem to_zmod_of_zmod {n} (i : zmod (pow2 n)) : to_zmod (of_zmod i) = i := ((zmod.eq_iff_modeq_nat' _).2 (by convert nat.modeq.mod_modeq _ _; apply to_nat_of_nat)).trans (zmod.cast_val _) theorem of_zmod_to_zmod {n} (v : bitvec n) : of_zmod (to_zmod v) = v := by unfold of_zmod to_zmod; convert of_nat_to_nat v; exact zmod.val_cast_of_lt (to_nat_lt_pow2 _) theorem of_nat_eq_iff_modeq {m n₁ n₂} : bitvec.of_nat m n₁ = bitvec.of_nat m n₂ ↔ n₁ ≡ n₂ [MOD 2 ^ m] := begin dunfold nat.modeq, split; intro h, { rw [← to_nat_of_nat, h, to_nat_of_nat] }, { rw [← of_nat_to_nat (bitvec.of_nat m n₁), to_nat_of_nat, h, ← to_nat_of_nat, of_nat_to_nat] }, end theorem of_nat_eq_of_zmod (m n) : bitvec.of_nat m n = bitvec.of_zmod n := eq.symm $ of_nat_eq_iff_modeq.2 $ by convert nat.modeq.mod_modeq _ _; apply zmod.val_cast_nat theorem to_zmod_zero (n) : to_zmod (0 : bitvec n) = 0 := by rw [to_zmod, to_nat_zero]; refl theorem of_zmod_zero (n) : (of_zmod 0 : bitvec n) = 0 := by rw [← to_zmod_zero, of_zmod_to_zmod] theorem of_zmod_one (n) : (of_zmod 1 : bitvec n) = 1 := begin cases n, {refl}, change bitvec.of_nat _ (1 % 2 ^ _) = _, rw [nat.mod_eq_of_lt, of_nat_one], exact @nat.pow_lt_pow_of_lt_right _ dec_trivial 0 _ (nat.succ_pos _) end theorem to_zmod_one (n) : to_zmod (1 : bitvec n) = 1 := by rw [← of_zmod_one, to_zmod_of_zmod] theorem to_zmod_add {n} (a b : bitvec n) : to_zmod (a + b) = to_zmod a + to_zmod b := show to_zmod (bitvec.of_nat _ _) = _, by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_add] theorem to_zmod_mul {n} (a b : bitvec n) : to_zmod (a * b) = to_zmod a * to_zmod b := show to_zmod (bitvec.of_nat _ _) = _, by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_mul] theorem to_zmod_neg {n} (a : bitvec n) : to_zmod (-a) = -to_zmod a := show to_zmod (bitvec.of_nat _ _) = _, begin rw [of_nat_eq_of_zmod, to_zmod_of_zmod, eq_neg_iff_add_eq_zero, to_zmod, ← nat.cast_add, nat.sub_add_cancel (le_of_lt (to_nat_lt_pow2 _))], exact zmod.cast_self_eq_zero, end theorem of_zmod_add {n} (a b : zmod (pow2 n)) : of_zmod (a + b) = of_zmod a + of_zmod b := by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]}; rw [← to_zmod_add, of_zmod_to_zmod] theorem of_zmod_mul {n} (a b : zmod (pow2 n)) : of_zmod (a * b) = of_zmod a * of_zmod b := by conv_lhs {rw [← to_zmod_of_zmod a, ← to_zmod_of_zmod b]}; rw [← to_zmod_mul, of_zmod_to_zmod] theorem of_zmod_neg {n} (a : zmod (pow2 n)) : of_zmod (-a) = -of_zmod a := by conv_lhs {rw [← to_zmod_of_zmod a]}; rw [← to_zmod_neg, of_zmod_to_zmod] instance (n : ℕ) : add_comm_semigroup (bitvec n) := { add_assoc := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_add, add_assoc, of_zmod_add, of_zmod_add], add_comm := λ a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_add, add_comm, of_zmod_add], ..bitvec.has_add } instance (n : ℕ) : comm_semigroup (bitvec n) := { mul_assoc := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_mul, ← of_zmod_mul, mul_assoc, of_zmod_mul, of_zmod_mul], mul_comm := λ a b, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_mul, mul_comm, of_zmod_mul], ..bitvec.has_mul } instance (n : ℕ) : comm_ring (bitvec n) := { zero_add := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, zero_add], add_zero := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_zero, ← of_zmod_add, add_zero], add_left_neg := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_neg, ← of_zmod_add, add_left_neg, ← of_zmod_zero], one_mul := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, one_mul], mul_one := λ a, by rw [← of_zmod_to_zmod a, ← of_zmod_one, ← of_zmod_mul, mul_one], left_distrib := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_mul, left_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl, right_distrib := λ a b c, by rw [← of_zmod_to_zmod a, ← of_zmod_to_zmod b, ← of_zmod_to_zmod c, ← of_zmod_add, ← of_zmod_mul, right_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl, ..bitvec.has_zero, ..bitvec.has_one, ..bitvec.has_neg, ..bitvec.add_comm_semigroup n, ..bitvec.comm_semigroup n } theorem to_nat_nth {n} (i j) : (bitvec.of_nat n i).nth j = i.test_bit j.1 := begin generalize e : bitvec.of_nat n i = v, cases v with l e', cases j with j h, rw [vector.nth], dsimp only, induction n generalizing i l j, cases h, cases l; injection e', simp [bitvec.of_nat] at e, generalize_hyp e₂ : bitvec.of_nat n_n i.div2 = v at e, cases v with l e₂', injection e, cases h_2, cases j; simp, refl, rw [← nat.bit_decomp i, nat.test_bit_succ], exact n_ih _ _ _ _ e₂ (nat.lt_of_succ_lt_succ h) end theorem of_nat_from_bits_fill (n m i) (h : n ≤ m) : bitvec.of_nat n i = from_bits_fill ff (bitvec.of_nat m i).1 := begin generalize e : bitvec.of_nat m i = v, cases v with l h, simp, induction n generalizing m i l e, exact (vector.eq_nil _).trans (vector.eq_nil _).symm, rw [of_nat_succ], cases m, cases h, rw [of_nat_succ] at e, generalize e' : bitvec.of_nat m i.div2 = v, cases v with l' h', rw e' at e, injection e, subst l, rw [n_ih _ _ (nat.le_of_succ_le_succ h) _ _ e', from_bits_fill], end theorem of_nat_bit0_aux {n} (j : bitvec (nat.succ n)) : bit0 j = ff :: from_bits_fill ff (j.val) := begin change bitvec.of_nat n.succ (bit0 (to_nat j)) = _, rw [of_nat_succ, nat.bodd_bit0, nat.div2_bit0, to_nat, of_nat_bits_to_nat] end theorem of_nat_bit0 (n i) : bitvec.of_nat n (bit0 i) = bit0 (bitvec.of_nat n i) := begin induction n generalizing i, refl, rw [of_nat_succ, nat.bodd_bit0, nat.div2_bit0], rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)], generalize : bitvec.of_nat n_n.succ i = j, rw of_nat_bit0_aux, end theorem of_nat_bit1 (n i) : bitvec.of_nat n (bit1 i) = bit1 (bitvec.of_nat n i) := begin induction n generalizing i, refl, rw [of_nat_succ, nat.bodd_bit1, nat.div2_bit1], rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)], generalize : bitvec.of_nat n_n.succ i = j, change _ = bitvec.of_nat _ (to_nat (bit0 j) + bit0 (@to_nat n_n 0) + 1), rw [to_nat_zero], change _ = bitvec.of_nat _ (to_nat (bit0 j) + 1), rw [of_nat_bit0_aux, to_nat_cons], change _ = bitvec.of_nat _ (nat.bit tt _), rw [of_nat_bit, of_nat_to_nat], end theorem add_nat_assoc {n} (v : bitvec n) (a b : ℕ) : v + a + b = v + (a + b : ℕ) := by rw [nat.cast_add, add_assoc] theorem of_nat_add {n} (a b : ℕ) : bitvec.of_nat n (a + b) = bitvec.of_nat n a + bitvec.of_nat n b := by simp [of_nat_eq_of_zmod, of_zmod_add] theorem of_nat_succ' {n} (a : ℕ) : bitvec.of_nat n a.succ = bitvec.of_nat n a + 1 := (of_nat_add a 1).trans $ by simp [of_nat_one] theorem of_nat_mul {n} (a b : ℕ) : bitvec.of_nat n (a * b) = bitvec.of_nat n a * bitvec.of_nat n b := by simp [of_nat_eq_of_zmod, of_zmod_mul] theorem coe_eq_of_nat {n} (a : ℕ) : (a : bitvec n) = bitvec.of_nat n a := begin induction a, exact (bitvec.of_nat_zero _).symm, rw [of_nat_succ', ← a_ih], refl, end theorem coe_to_nat {n} (v : bitvec n) : (to_nat v : bitvec n) = v := by rw [coe_eq_of_nat, of_nat_to_nat] theorem bits_to_nat_inj : ∀ {l₁ l₂}, bits_to_nat l₁ = bits_to_nat l₂ → l₁.length = l₂.length → l₁ = l₂ | [] [] _ _ := rfl | (a :: l₁) (b :: l₂) e e' := begin rw [bits_to_nat_cons, bits_to_nat_cons] at e, rw [← nat.bodd_bit a (bits_to_nat l₁), e, nat.bodd_bit, @bits_to_nat_inj l₁ l₂ _ (nat.succ_inj e')], rw [← nat.div2_bit a (bits_to_nat l₁), e, nat.div2_bit] end theorem to_nat_inj {n v₁ v₂} (h : @bitvec.to_nat n v₁ = bitvec.to_nat v₂) : v₁ = v₂ := subtype.eq $ bits_to_nat_inj h (v₁.2.trans v₂.2.symm) theorem coe_shl {n} (a b) : (nat.shiftl a b : bitvec n) = bitvec.shl a b := begin rw [shl, coe_eq_of_nat, nat.shiftl_eq_mul_pow, nat.shiftl_eq_mul_pow], refine of_nat_eq_iff_modeq.2 (nat.modeq.modeq_mul_right _ _), rw [← of_nat_eq_iff_modeq, of_nat_to_nat, coe_eq_of_nat], end theorem sign_iff_neg {n v} : @bitvec.sign n v ↔ bitvec.to_int v < 0 := begin unfold bitvec.to_int, cases sign v; simp, apply sub_lt_zero.2, norm_cast, exact to_nat_lt_pow2 _ end theorem to_int_inj {n v₁ v₂} (h : @bitvec.to_int n v₁ = bitvec.to_int v₂) : v₁ = v₂ := begin have : sign v₁ = sign v₂, { apply bool.coe_bool_iff.1, rw [sign_iff_neg, sign_iff_neg, h] }, revert h, unfold bitvec.to_int, rw this, cases sign v₂; simp; exact to_nat_inj end theorem pow2_eq_zero {n} : (2 ^ n : bitvec n) = 0 := begin suffices : ((2 ^ n : ℕ) : bitvec n) = 0, {exact_mod_cast this}, have := to_nat_of_nat n (2^n), apply to_nat_inj, rw [coe_eq_of_nat, to_nat_of_nat, nat.mod_self, to_nat_zero], end theorem coe_to_int {n} (v : bitvec n) : (to_int v : bitvec n) = v := by unfold to_int; cases sign v; simp [coe_to_nat, pow2_eq_zero] @[class] def reify {n} (v : bitvec n) (l : out_param (list bool)) : Prop := from_bits_fill ff l = v theorem reify.mk {n} (v) {l} [h : @reify n v l] : from_bits_fill ff l = v := h theorem reify_eq {n v l l'} [@reify n v l] (h : l' = v.1) : l' = (@from_bits_fill ff l n).1 := by rwa reify.mk v theorem reify_eq' {n v l l'} [@reify n v l] (h : l' = v) : l' = @from_bits_fill ff l n := by rwa reify.mk v theorem reify_eq₂ {n v₁ l₁ v₂ l₂} [@reify n v₁ l₁] [@reify n v₂ l₂] (h : v₁ = v₂) : @from_bits_fill ff l₁ n = from_bits_fill ff l₂ := by rwa [reify.mk v₁, reify.mk v₂] theorem reify_iff {n v l} : @reify n v l ↔ bitvec.of_nat n (bits_to_nat l) = v := iff_of_eq $ congr_arg (= v) (of_nat_bits_to_nat _).symm instance reify_0 {n} : @reify n 0 [] := rfl instance reify_1 {n} : @reify n 1 [tt] := by cases n; exact rfl instance reify_bit0 {n} (v l) [h : @reify n v l] : reify (bit0 v) (ff :: l) := reify_iff.2 $ by have := of_nat_bit0 n (bits_to_nat l); rwa [reify_iff.1 h] at this instance reify_bit1 {n} (v l) [h : @reify n v l] : reify (bit1 v) (tt :: l) := reify_iff.2 $ by have := of_nat_bit1 n (bits_to_nat l); rwa [reify_iff.1 h] at this end bitvec namespace x86 def split_bits_spec : list (Σ n, bitvec n) → list bool → Prop | [] l := list.all l bnot | (⟨n, v⟩ :: s) l := let ⟨l₁, l₂⟩ := l.split_at n in (@bitvec.from_bits_fill ff l₁ n).1 = v.1 ∧ split_bits_spec s l₂ theorem split_bits_ok {l s} : split_bits (bitvec.bits_to_nat l) s → split_bits_spec s l := begin generalize e₁ : bitvec.bits_to_nat l = n, induction s generalizing l n, rintro ⟨⟩, { induction l, constructor, cases l_hd, { exact bool.band_intro rfl (l_ih (not_imp_not.1 (nat.bit_ne_zero _) e₁)) }, { cases nat.bit1_ne_zero _ e₁ } }, { rcases s_hd with ⟨i, l', e₂⟩, unfold split_bits_spec, generalize e₃ : l.split_at i = p, cases p with l₁ l₂, dsimp [split_bits_spec], induction i with i generalizing l' l₁ l₂ e₂ l n; cases l'; injection e₂, { cases h_2, cases e₃, exact ⟨rfl, s_ih _ e₁ h_2_a⟩ }, { generalize_hyp e₄ : (⟨l'_hd :: l'_tl, e₂⟩ : bitvec _) = f at h_2, cases h_2, cases h_2_bs with _ pr, injection e₄, cases h_3, generalize e₅ : l.tail.split_at i = p, cases p with l₁' l₂', have : bitvec.bits_to_nat l.tail = nat.div2 n, { subst e₁, cases l, refl, exact (nat.div2_bit _ _).symm }, rcases i_ih _ _ _ h_1 _ this e₅ h_2_a with ⟨e₆, h'⟩, replace e₆ : bitvec.from_bits_fill ff l₁' = ⟨l'_tl, pr⟩ := subtype.eq e₆, cases l, { cases e₃, have : (l₁', l₂') = ([], []), {cases i; cases e₅; refl}, cases this, simp [bitvec.from_bits_fill, h', vector.repeat] at e₆ ⊢, cases e₁, exact ⟨rfl, e₆⟩ }, { rw [list.split_at, show l_tl.split_at i = (l₁', l₂'), from e₅] at e₃, cases e₃, rw [bitvec.from_bits_fill, ← e₁, e₆], refine ⟨_, h'⟩, simp [vector.cons], exact (nat.bodd_bit _ _).symm } } } end theorem split_bits.determ_l {n₁ n₂ l} (h₁ : split_bits n₁ l) (h₂ : split_bits n₂ l) : n₁ = n₂ := begin induction l generalizing n₁ n₂, {cases h₁, cases h₂, refl}, rcases l_hd with ⟨_, l', rfl⟩, induction l' generalizing n₁ n₂, { cases h₁, cases h₂, exact l_ih h₁_a h₂_a }, { have : ∀ {n l'}, split_bits n l' → l' = ⟨_, l'_hd :: l'_tl, rfl⟩ :: l_tl → l'_hd = nat.bodd n ∧ split_bits (nat.div2 n) (⟨_, l'_tl, rfl⟩ :: l_tl), { intros, cases a; try {cases a_1}, rcases a_bs with ⟨l₂, rfl⟩, injection a_1, cases h_2, cases congr_arg (λ v : Σ n, bitvec n, v.2.1) h_1, exact ⟨rfl, a_a⟩ }, rcases this h₁ rfl with ⟨rfl, h₁'⟩, rcases this h₂ rfl with ⟨e, h₂'⟩, rw [← nat.bit_decomp n₁, e, l'_ih h₁' h₂', nat.bit_decomp] } end theorem split_bits.determ {n l₁ l₂} (h₁ : split_bits n l₁) (h₂ : split_bits n l₂) (h : l₁.map sigma.fst = l₂.map sigma.fst) : l₁ = l₂ := begin induction l₁ generalizing n l₂; cases l₂; injection h, refl, cases l₁_hd with i v₁, cases l₂_hd with _ v₂, cases h_1, clear h h_1, induction i with i generalizing v₁ v₂ n, { cases h₁, cases h₂, rw l₁_ih h₁_a h₂_a h_2 }, { cases h₁, cases h₂, cases i_ih _ _ h₁_a h₂_a, refl } end theorem bits_to_byte.determ_l {n m w1 w2 l} : @bits_to_byte n m w1 l → @bits_to_byte n m w2 l → w1 = w2 | ⟨e₁, h₁⟩ ⟨_, h₂⟩ := bitvec.to_nat_inj $ split_bits.determ_l h₁ h₂ theorem bits_to_byte.determ_l_aux {n m w1 w2 l l'} : @bits_to_byte n m w1 l → @bits_to_byte n m w2 (l ++ l') → (w1, l') = (w2, []) | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := begin simp, suffices, refine ⟨_, this⟩, swap, { apply list.length_eq_zero.1, apply @eq_of_add_eq_add_left _ _ l.length, rw [add_zero, ← list.length_append, e₁, e₂] }, clear bits_to_byte.determ_l_aux, subst this, rw list.append_nil at h₂, exact bitvec.to_nat_inj (split_bits.determ_l h₁ h₂) end theorem bits_to_byte.determ {n m w l1 l2} : @bits_to_byte n m w l1 → @bits_to_byte n m w l2 → l1 = l2 | ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ := list.injective_map_iff.2 (by rintro x y ⟨⟩; refl) (split_bits.determ h₁ h₂ (by rw [list.map_map, list.map_map, (_ : _∘_ = _), list.map_const _ 8, e₁, list.map_const, e₂]; refl)) theorem read_prefixes.determ {r₁ r₂ l} : read_prefixes r₁ l → read_prefixes r₂ l → r₁ = r₂ := begin intros h₁ h₂, cases h₁; cases h₂; congr, cases split_bits.determ h₁_a h₂_a rfl, refl, end @[elab_as_eliminator] theorem byte_split {C : byte → Sort*} : ∀ b : byte, (∀ b0 b1 b2 b3 b4 b5 b6 b7, C ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩) → C b | ⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ H := H _ _ _ _ _ _ _ _ def binop.from_bits : ∀ (b0 b1 b2 b3 : bool), binop | ff ff ff ff := binop.add | tt ff ff ff := binop.or | ff tt ff ff := binop.adc | tt tt ff ff := binop.sbb | ff ff tt ff := binop.and | tt ff tt ff := binop.sub | ff tt tt ff := binop.xor | tt tt tt ff := binop.cmp | ff ff ff tt := binop.rol | tt ff ff tt := binop.ror | ff tt ff tt := binop.rcl | tt tt ff tt := binop.rcr | ff ff tt tt := binop.shl | tt ff tt tt := binop.shr | ff tt tt tt := binop.tst | tt tt tt tt := binop.sar theorem binop.bits_eq {b0 b1 b2 b3 e op} : binop.bits op ⟨[b0, b1, b2, b3], e⟩ → op = binop.from_bits b0 b1 b2 b3 := begin generalize e' : (⟨[b0, b1, b2, b3], e⟩ : bitvec 4) = v, intro h, induction h; { cases bitvec.reify_eq (congr_arg subtype.val e'), refl } end theorem binop.bits.determ : ∀ {op1 op2 v}, binop.bits op1 v → binop.bits op2 v → op1 = op2 | op1 op2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 := (binop.bits_eq h1).trans (binop.bits_eq h2).symm def basic_cond.from_bits : ∀ (b0 b1 b2 : bool), option basic_cond | ff ff ff := some basic_cond.o | tt ff ff := some basic_cond.b | ff tt ff := some basic_cond.e | tt tt ff := some basic_cond.na | ff ff tt := some basic_cond.s | tt ff tt := none | ff tt tt := some basic_cond.l | tt tt tt := some basic_cond.ng theorem basic_cond.bits_eq {b0 b1 b2 e c} : basic_cond.bits c ⟨[b0, b1, b2], e⟩ → basic_cond.from_bits b0 b1 b2 = some c := begin generalize e' : (⟨[b0, b1, b2], e⟩ : bitvec 3) = v, intro h, induction h; { cases bitvec.reify_eq (congr_arg subtype.val e'), refl } end def cond_code.from_bits (b0 b1 b2 b3 : bool) : option cond_code := option.map (cond_code.mk b3) (basic_cond.from_bits b0 b1 b2) theorem cond_code.bits_eq {b0 b1 b2 b3 e c} : cond_code.bits c ⟨[b0, b1, b2, b3], e⟩ → cond_code.from_bits b0 b1 b2 b3 = some c := begin rintro ⟨⟩, rcases split_bits_ok a_a with ⟨h₁, ⟨⟩, _⟩, cases subtype.eq h₁, rw [cond_code.from_bits, basic_cond.bits_eq a_a_1], refl end theorem cond_code.bits.determ : ∀ {c1 c2 v}, cond_code.bits c1 v → cond_code.bits c2 v → c1 = c2 | c1 c2 ⟨[b0, b1, b2, b3], _⟩ h1 h2 := option.some_inj.1 $ (cond_code.bits_eq h1).symm.trans (cond_code.bits_eq h2) theorem read_displacement_ne_3 {mod disp l} : read_displacement mod disp l → mod ≠ 3 := by rintro ⟨⟩ ⟨⟩ theorem read_displacement.determ_aux {mod disp1 disp2 l l'} (h₁ : read_displacement mod disp1 l) (h₂ : read_displacement mod disp2 (l ++ l')) : (disp1, l') = (disp2, []) := begin cases h₁; cases h₂; try {refl}, cases bits_to_byte.determ_l_aux h₁_a h₂_a, refl end theorem read_displacement.determ {mod disp1 disp2 l} (h₁ : read_displacement mod disp1 l) (h₂ : read_displacement mod disp2 l) : disp1 = disp2 := by cases read_displacement.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_sib_displacement_ne_3 {mod bbase w Base l} : read_sib_displacement mod bbase w Base l → mod ≠ 3 := by rw [read_sib_displacement]; split_ifs; [ {rcases h with ⟨_, rfl⟩; rintro _ ⟨⟩}, exact λ h, read_displacement_ne_3 h.1] theorem read_sib_displacement.determ_aux {mod bbase w1 w2 Base1 Base2 l l'} (h₁ : read_sib_displacement mod bbase w1 Base1 l) (h₂ : read_sib_displacement mod bbase w2 Base2 (l ++ l')) : (w1, Base1, l') = (w2, Base2, []) := begin rw read_sib_displacement at h₁ h₂, split_ifs at h₁ h₂, { rcases h₁ with ⟨b, rfl, rfl, rfl⟩, rcases h₂ with ⟨_, rfl, rfl, ⟨⟩⟩, refl }, { rcases h₁ with ⟨h1, rfl⟩, rcases h₂ with ⟨h2, rfl⟩, cases read_displacement.determ_aux h1 h2, refl }, end theorem read_sib_displacement.determ {mod bbase w1 w2 Base1 Base2 l} (h₁ : read_sib_displacement mod bbase w1 Base1 l) (h₂ : read_sib_displacement mod bbase w2 Base2 l) : (w1, Base1) = (w2, Base2) := by cases read_sib_displacement.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_SIB_ne_3 {rex mod rm l} : read_SIB rex mod rm l → mod ≠ 3 := by rintro ⟨⟩; exact read_sib_displacement_ne_3 a_a_1 theorem read_SIB.determ_aux {rex mod rm1 rm2 l l'} (h₁ : read_SIB rex mod rm1 l) (h₂ : read_SIB rex mod rm2 (l ++ l')) : (rm1, l') = (rm2, []) := begin cases h₁, cases h₂, cases split_bits.determ h₁_a h₂_a rfl, cases read_sib_displacement.determ_aux h₁_a_1 h₂_a_1, refl end theorem read_SIB.determ {rex mod rm1 rm2 l} (h₁ : read_SIB rex mod rm1 l) (h₂ : read_SIB rex mod rm2 l) : rm1 = rm2 := by cases read_SIB.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_ModRM_nil {rex reg r} : ¬ read_ModRM rex reg r [] := by rintro ⟨⟩ def read_ModRM' (rex : REX) (r : RM) (rm : bitvec 3) (mod : bitvec 2) (l : list byte) : Prop := if mod = 3 then r = RM.reg (rex_reg rex.B rm) ∧ l = [] else if rm = 4 then read_SIB rex mod r l else if rm = 5 ∧ mod = 0 then ∃ i : word, i.to_list_byte l ∧ r = RM.mem none base.rip (EXTS i) else ∃ disp, read_displacement mod disp l ∧ r = RM.mem none (base.reg (rex_reg rex.B rm)) disp theorem read_ModRM_ModRM' {rex : REX} {reg : regnum} {r : RM} {rm reg_opc : bitvec 3} {mod : bitvec 2} {b : byte} {l : list byte} (h₁ : split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩]) (h₂ : read_ModRM rex reg r (b :: l)) : reg = rex_reg rex.R reg_opc ∧ read_ModRM' rex r rm mod l := begin generalize_hyp e : list.cons b l = l' at h₂, induction h₂; cases e; cases split_bits.determ h₁ h₂_a rfl; refine ⟨rfl, _⟩, { rw [read_ModRM', if_neg, if_neg, if_pos], exact ⟨_, h₂_a_1, rfl⟩, all_goals {exact dec_trivial} }, { rw [read_ModRM', if_pos], exact ⟨rfl, rfl⟩, exact dec_trivial }, { rw [read_ModRM', if_neg (read_SIB_ne_3 h₂_a_1), if_pos], exact h₂_a_1, refl }, { rw [read_ModRM', if_neg (read_displacement_ne_3 h₂_a_3), if_neg h₂_a_1, if_neg h₂_a_2], exact ⟨_, h₂_a_3, rfl⟩ }, end theorem read_ModRM_split {rex reg r b l} (h : read_ModRM rex reg r (b :: l)) : ∃ rm reg_opc mod, split_bits b.to_nat [⟨3, rm⟩, ⟨3, reg_opc⟩, ⟨2, mod⟩] := by cases h; exact ⟨_, _, _, by assumption⟩ theorem read_ModRM.determ_aux {rex reg1 r1 reg2 r2 l l'} (h₁ : read_ModRM rex reg1 r1 l) (h₂ : read_ModRM rex reg2 r2 (l ++ l')) : (reg1, r1, l') = (reg2, r2, []) := begin simp, cases l with b l, {cases read_ModRM_nil h₁}, rcases read_ModRM_split h₁ with ⟨rm, reg_opc, r, s⟩, rcases read_ModRM_ModRM' s h₁ with ⟨rfl, h₁'⟩, rcases read_ModRM_ModRM' s h₂ with ⟨rfl, h₂'⟩, refine ⟨rfl, _⟩, clear h₁ h₂ s, unfold read_ModRM' at h₁' h₂', split_ifs at h₁' h₂', { rw h₁'.2 at h₂', exact ⟨h₁'.1.trans h₂'.1.symm, h₂'.2⟩ }, { cases read_SIB.determ_aux h₁' h₂', exact ⟨rfl, rfl⟩ }, { rcases h₁' with ⟨i1, h11, h12⟩, rcases h₂' with ⟨i2, h21, h22⟩, cases bits_to_byte.determ_l_aux h11 h21, exact ⟨h12.trans h22.symm, rfl⟩ }, { rcases h₁' with ⟨i1, h11, h12⟩, rcases h₂' with ⟨i2, h21, h22⟩, cases read_displacement.determ_aux h11 h21, exact ⟨h12.trans h22.symm, rfl⟩ }, end theorem read_ModRM.determ {rex reg1 r1 reg2 r2 l} (h₁ : read_ModRM rex reg1 r1 l) (h₂ : read_ModRM rex reg2 r2 l) : (reg1, r1) = (reg2, r2) := by cases read_ModRM.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_ModRM.determ₂ {rex reg1 r1 reg2 r2 l1 l2 l1' l2'} (h₁ : read_ModRM rex reg1 r1 l1) (h₂ : read_ModRM rex reg2 r2 l2) (e : l1 ++ l1' = l2 ++ l2') : (reg1, r1, l1, l1') = (reg2, r2, l2, l2') := begin have : ∀ {reg1 r1 reg2 r2 l1 l2 l1' l2'} (h₁ : read_ModRM rex reg1 r1 l1) (h₂ : read_ModRM rex reg2 r2 l2) (e : ∃ a', l2 = l1 ++ a' ∧ l1' = a' ++ l2'), (l1, l1') = (l2, l2'), { intros, rcases e_1 with ⟨l3, rfl, rfl⟩, cases read_ModRM.determ_aux h₁_1 h₂_1, simp }, cases (list.append_eq_append_iff.1 e).elim (λ h, this h₁ h₂ h) (λ h, (this h₂ h₁ h).symm), cases read_ModRM.determ h₁ h₂, refl, end theorem read_opcode_ModRM.determ_aux {rex v1 r1 v2 r2 l l'} (h₁ : read_opcode_ModRM rex v1 r1 l) (h₂ : read_opcode_ModRM rex v2 r2 (l ++ l')) : (v1, r1, l') = (v2, r2, []) := begin cases h₁, cases h₂, cases read_ModRM.determ_aux h₁_a h₂_a, cases split_bits.determ h₁_a_1 h₂_a_1 rfl, refl, end theorem read_opcode_ModRM.determ {rex v1 r1 v2 r2 l} (h₁ : read_opcode_ModRM rex v1 r1 l) (h₂ : read_opcode_ModRM rex v2 r2 l) : (v1, r1) = (v2, r2) := by cases read_opcode_ModRM.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_opcode_ModRM.determ₂_aux {rex v1 r1 v2 r2 l1 l2 l1' l2' l'} (h₁ : read_opcode_ModRM rex v1 r1 l1) (h₂ : read_opcode_ModRM rex v2 r2 l2) (e : l1 ++ l1' ++ l' = l2 ++ l2') : (v1, r1, l1, l1' ++ l') = (v2, r2, l2, l2') := begin cases h₁, cases h₂, rw [list.append_assoc, list.append_eq_append_iff] at e, rcases e with ⟨x, rfl, e⟩ | ⟨x, rfl, rfl⟩, { cases read_ModRM.determ_aux h₁_a h₂_a, cases e, cases split_bits.determ h₁_a_1 h₂_a_1 rfl, rw list.append_nil, refl }, { cases read_ModRM.determ_aux h₂_a h₁_a, cases split_bits.determ h₁_a_1 h₂_a_1 rfl, rw list.append_nil, refl }, end theorem read_opcode_ModRM.determ₂ {rex v1 r1 v2 r2 l1 l2 l1' l2'} (h₁ : read_opcode_ModRM rex v1 r1 l1) (h₂ : read_opcode_ModRM rex v2 r2 l2) : l1 ++ l1' = l2 ++ l2' → (v1, r1, l1, l1') = (v2, r2, l2, l2') := by simpa using @read_opcode_ModRM.determ₂_aux _ _ _ _ _ _ _ l1' l2' [] h₁ h₂ theorem read_imm8.determ_aux {w1 w2 l l'} (h₁ : read_imm8 w1 l) (h₂ : read_imm8 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases h₂; refl theorem read_imm16.determ_aux {w1 w2 l l'} (h₁ : read_imm16 w1 l) (h₂ : read_imm16 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases h₂; cases bits_to_byte.determ_l_aux h₁_a h₂_a; refl theorem read_imm32.determ_aux {w1 w2 l l'} (h₁ : read_imm32 w1 l) (h₂ : read_imm32 w2 (l ++ l')) : (w1, l') = (w2, []) := by cases h₁; cases h₂; cases bits_to_byte.determ_l_aux h₁_a h₂_a; refl theorem read_imm8.determ {w1 w2 l} (h₁ : read_imm8 w1 l) (h₂ : read_imm8 w2 l) : w1 = w2 := by cases h₁; cases h₂; refl theorem read_imm16.determ {w1 w2 l} (h₁ : read_imm16 w1 l) (h₂ : read_imm16 w2 l) : w1 = w2 := by cases h₁; cases h₂; cases bits_to_byte.determ_l h₁_a h₂_a; refl theorem read_imm32.determ {w1 w2 l} (h₁ : read_imm32 w1 l) (h₂ : read_imm32 w2 l) : w1 = w2 := by cases h₁; cases h₂; cases bits_to_byte.determ_l h₁_a h₂_a; refl theorem read_imm.determ_aux : ∀ {sz w1 w2 l l'}, read_imm sz w1 l → read_imm sz w2 (l ++ l') → (w1, l') = (w2, []) | (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux | wsize.Sz16 _ _ _ _ := read_imm16.determ_aux | wsize.Sz32 _ _ _ _ := read_imm32.determ_aux | wsize.Sz64 _ _ _ _ := false.elim theorem read_full_imm.determ_aux : ∀ {sz w1 w2 l l'}, read_full_imm sz w1 l → read_full_imm sz w2 (l ++ l') → (w1, l') = (w2, []) | (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux | wsize.Sz16 _ _ _ _ := read_imm16.determ_aux | wsize.Sz32 _ _ _ _ := read_imm32.determ_aux | wsize.Sz64 _ _ _ _ := bits_to_byte.determ_l_aux theorem read_imm.determ {sz w1 w2 l} (h₁ : read_imm sz w1 l) (h₂ : read_imm sz w2 l) : w1 = w2 := by cases read_imm.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem read_full_imm.determ {sz w1 w2 l} (h₁ : read_full_imm sz w1 l) (h₂ : read_full_imm sz w2 l) : w1 = w2 := by cases read_full_imm.determ_aux h₁ (by rw list.append_nil; exact h₂); refl def decode_two' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop := cond b7 (cond b6 ( -- xadd [b1, b2, b3, b4, b5] = [ff, ff, ff, ff, ff] ∧ let v := b0, sz := op_size_W rex v in ∃ reg r, read_ModRM rex reg r l ∧ a = ast.xadd sz r reg) (cond b5 (cond b2 ( -- movsx [b1, b4] = [tt, tt] ∧ let sz2 := op_size_W rex tt, sz := if b0 then wsize.Sz16 else wsize.Sz8 rex.is_some in ∃ reg r, read_ModRM rex reg r l ∧ a = (if b3 then ast.movsx else ast.movzx) sz (dest_src.R_rm reg r) sz2) ( -- cmpxchg [b1, b4] = [ff, tt] ∧ let v := b0, sz := op_size_W rex v in ∃ reg r, read_ModRM rex reg r l ∧ a = ast.cmpxchg sz r reg)) (cond b4 ( -- setcc ∃ reg r code, read_ModRM rex reg r l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.setcc code rex.is_some r) ( -- jcc ∃ imm code, read_imm32 imm l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.jcc code imm)))) (cond b6 ( -- cmov [b4, b5] = [ff, ff] ∧ let sz := op_size tt rex.W tt in ∃ reg r code, read_ModRM rex reg r l ∧ cond_code.from_bits b0 b1 b2 b3 = some code ∧ a = ast.cmov code sz (dest_src.R_rm reg r)) ( -- syscall [b0, b1, b2, b3, b4, b5] = [tt, ff, tt, ff, ff, ff] ∧ a = ast.syscall ∧ l = [])) theorem decode_two_two' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} : decode_two rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) → decode_two' rex a b0 b1 b2 b3 b4 b5 b6 b7 l := begin generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l', intro a, cases a, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨rfl, _, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨_, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨_, _, _, a_a_1, cond_code.bits_eq a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, ⟨⟩, h₂, _⟩, cases bitvec.reify_eq h₁, cases bitvec.reify_eq h₂, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, end theorem decode_two_nil {rex a} : ¬ decode_two rex a []. theorem decode_two.determ_aux {rex a₁ a₂ l l'} : decode_two rex a₁ l → decode_two rex a₂ (l ++ l') → (a₁, l') = (a₂, []) := begin cases l with b l, {exact decode_two_nil.elim}, apply byte_split b, introv h1 h2, replace h1 := decode_two_two' h1, replace h2 := decode_two_two' h2, unfold decode_two' at h1 h2, repeat { do `(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type, tactic.cases e $> (); `[dsimp only [cond] at h1 h2] }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨reg1, r1, h11, h12, h13, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, h22, h23, rfl⟩, cases read_ModRM.determ_aux h12 h22, cases h13.symm.trans h23, refl }, { rcases h1 with ⟨imm1, code1, h11, h12, rfl⟩, rcases h2 with ⟨imm2, code2, h21, h22, rfl⟩, cases read_imm32.determ_aux h11 h21, cases h12.symm.trans h22, refl }, { rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩, rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, cases h12.symm.trans h22, refl }, { rcases h1 with ⟨reg1, r1, code1, h11, h12, rfl⟩, rcases h2 with ⟨reg2, r2, code2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, end theorem decode_two.determ {rex a₁ a₂ l} (h₁ : decode_two rex a₁ l) (h₂ : decode_two rex a₂ l) : a₁ = a₂ := by cases decode_two.determ_aux h₁ (by rw list.append_nil; exact h₂); refl def decode_hi' (v : bool) (sz : wsize) (r : RM) : ∀ (b0 b1 b2 x : bool), ast → list byte → Prop | ff ff ff ff a l := ∃ imm, read_imm sz imm l ∧ a = ast.binop binop.tst sz (dest_src.Rm_i r imm) | ff tt ff ff a l := a = ast.unop unop.not sz r ∧ l = [] | tt tt ff ff a l := a = ast.unop unop.neg sz r ∧ l = [] | ff ff tt ff a l := a = ast.mul sz r ∧ l = [] | ff tt tt ff a l := a = ast.div sz r ∧ l = [] | ff ff ff tt a l := a = ast.unop unop.inc sz r ∧ l = [] | tt ff ff tt a l := a = ast.unop unop.dec sz r ∧ l = [] | ff tt ff tt a l := a = ast.call (imm_rm.rm r) ∧ l = [] | ff ff tt tt a l := a = ast.jump r ∧ l = [] | ff tt tt tt a l := a = ast.push (imm_rm.rm r) ∧ l = [] | _ _ _ _ a l := false theorem decode_hi_hi' {v sz r x b0 b1 b2 a l} (h : decode_hi v sz r x ⟨[b0, b1, b2], rfl⟩ a l) : decode_hi' v sz r b0 b1 b2 x a l := begin generalize_hyp e : (⟨[b0, b1, b2], rfl⟩ : bitvec 3) = opc at h, induction h; cases congr_arg subtype.val (bitvec.reify_eq' e), exact ⟨_, h_a, rfl⟩, all_goals { exact ⟨rfl, rfl⟩ } end theorem decode_hi.determ_aux {v sz r x a₁ a₂ l l'} : ∀ {opc}, decode_hi v sz r x opc a₁ l → decode_hi v sz r x opc a₂ (l ++ l') → (a₁, l') = (a₂, []) | ⟨[b0, b1, b2], _⟩ h1 h2 := begin replace h1 := decode_hi_hi' h1, replace h2 := decode_hi_hi' h2, clear decode_hi.determ_aux, cases b0; cases b1; cases b2; cases x; cases h1; cases h2, { cases read_imm.determ_aux h1_h.1 h2_h.1, cases h1_h.2.trans h2_h.2.symm, refl }, all_goals { rw [h1_left, ← h2_left], cases h1_right, cases h2_right, refl } end theorem decode_hi.determ {v sz r x opc a₁ a₂ l} (h₁ : decode_hi v sz r x opc a₁ l) (h₂ : decode_hi v sz r x opc a₂ l) : a₁ = a₂ := by cases decode_hi.determ_aux h₁ (by rw list.append_nil; exact h₂); refl def decode_aux' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop := cond b7 (cond b6 (cond b5 (cond b4 (cond b2 (cond b1 ( -- hi let v := b0, sz := op_size_W rex v in ∃ opc r l1 l2, read_opcode_ModRM rex opc r l1 ∧ decode_hi v sz r b3 opc a l2 ∧ l = l1 ++ l2) ( -- cmc b0 = tt ∧ a = ast.cmc ∧ l = [])) ( -- clc, stc [b1, b3] = [ff, tt] ∧ a = cond b0 ast.stc ast.clc ∧ l = [])) (cond b0 ( -- jump [b2, b3] = [ff, tt] ∧ ∃ imm, (if b1 then read_imm8 imm l else read_imm32 imm l) ∧ a = ast.jcc cond_code.always imm) ( -- call [b2, b3] = [ff, tt] ∧ ∃ imm, read_imm32 imm l ∧ a = ast.call (imm_rm.imm imm)))) ( let v := b0, sz := op_size_W rex v in cond b4 ( -- binop_hi_reg [b2, b3] = [ff, ff] ∧ ∃ opc r op, read_opcode_ModRM rex opc r l ∧ opc ≠ 6 ∧ binop.bits op (rex_reg tt opc) ∧ let src_dst := if b1 then dest_src.Rm_r r RCX else dest_src.Rm_i r 1 in a = ast.binop op sz src_dst) (cond b3 ( -- leave [b0, b1, b2] = [tt, ff, ff] ∧ a = ast.leave ∧ l = []) (cond b2 ( -- mov_imm b1 = tt ∧ ∃ opc r imm l1 l2, read_opcode_ModRM rex opc r l1 ∧ read_imm sz imm l2 ∧ a = ast.mov sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2) (cond b1 ( -- ret ∃ imm, (if v then imm = 0 ∧ l = [] else read_imm16 imm l) ∧ a = ast.ret imm) ( -- binop_hi ∃ opc r imm op l1 l2, read_opcode_ModRM rex opc r l1 ∧ opc ≠ 6 ∧ binop.bits op (rex_reg tt opc) ∧ read_imm8 imm l2 ∧ a = ast.binop op sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2)))))) (cond b5 (cond b4 ( -- mov64 let v := b3, sz := op_size_W rex v in ∃ imm, read_full_imm sz imm l ∧ a = ast.mov sz (dest_src.Rm_i (RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩) imm)) ( -- test_rax [b1, b2, b3] = [ff, ff, tt] ∧ let v := b0, sz := op_size tt rex.W v in ∃ imm, read_imm sz imm l ∧ a = ast.binop binop.tst sz (dest_src.Rm_i (RM.reg RAX) imm))) (cond b4 ( -- xchg_rax b3 = ff ∧ let sz := op_size tt rex.W tt in a = ast.xchg sz (RM.reg RAX) ⟨[b0, b1, b2, rex.B], rfl⟩ ∧ l = []) (cond b3 (cond b2 (cond b1 ( -- pop_rm b0 = tt ∧ ∃ r, read_opcode_ModRM rex 0 r l ∧ a = ast.pop r) ( -- lea b0 = tt ∧ ∃ reg r, let sz := op_size tt rex.W tt in read_ModRM rex reg r l ∧ RM.is_mem r ∧ a = ast.lea sz (dest_src.R_rm reg r))) ( -- mov let v := b0, sz := op_size_W rex v in ∃ reg r, read_ModRM rex reg r l ∧ let src_dst := if b1 then dest_src.R_rm reg r else dest_src.Rm_r r reg in a = ast.mov sz src_dst)) (cond b2 ( let v := b0, sz := op_size_W rex v in -- xchg, test ∃ reg r, read_ModRM rex reg r l ∧ a = cond b1 (ast.xchg sz r reg) (ast.binop binop.tst sz (dest_src.Rm_r r reg))) ( -- binop_imm, binop_imm8 let sz := op_size_W rex (cond b1 tt b0) in ∃ opc r l1 imm l2 op, read_opcode_ModRM rex opc r l1 ∧ binop.bits op (EXTZ opc) ∧ cond b1 (read_imm8 imm l2) (read_imm sz imm l2) ∧ a = ast.binop op sz (dest_src.Rm_i r imm) ∧ l = l1 ++ l2)))))) (cond b6 (cond b5 (cond b4 ( -- jcc8 ∃ code imm, cond_code.from_bits b0 b1 b2 b3 = some code ∧ read_imm8 imm l ∧ a = ast.jcc code imm) (cond b3 ( -- push_imm [b0, b2] = [ff, ff] ∧ ∃ imm, read_imm (if b1 then wsize.Sz8 ff else wsize.Sz32) imm l ∧ a = ast.push (imm_rm.imm imm)) ( -- movsx [b0, b1, b2] = [tt, tt, ff] ∧ ∃ reg r, read_ModRM rex reg r l ∧ a = ast.movsx wsize.Sz32 (dest_src.R_rm reg r) wsize.Sz64))) (cond b4 ( -- pop, push_rm let reg := RM.reg ⟨[b0, b1, b2, rex.B], rfl⟩ in a = cond b3 (ast.pop reg) (ast.push (imm_rm.rm reg)) ∧ l = []) ( -- prefix byte false))) (cond b2 (cond b1 ( -- decode_two [b0, b3, b4, b5] = [tt, tt, ff, ff] ∧ decode_two rex a l) ( -- binop_imm_rax let v := b0, sz := op_size_W rex v, op := binop.from_bits b3 b4 b5 ff in ∃ imm, read_imm sz imm l ∧ a = ast.binop op sz (dest_src.Rm_i (RM.reg RAX) imm))) ( -- binop1 let v := b0, d := b1, sz := op_size_W rex v, op := binop.from_bits b3 b4 b5 ff in ∃ reg r, read_ModRM rex reg r l ∧ let src_dst := if d then dest_src.R_rm reg r else dest_src.Rm_r r reg in a = ast.binop op sz src_dst))) theorem decode_aux_aux' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} : decode_aux rex a (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l) → decode_aux' rex a b0 b1 b2 b3 b4 b5 b6 b7 l := begin generalize e : (⟨[b0, b1, b2, b3, b4, b5, b6, b7], rfl⟩ :: l : list byte) = l', intro a, cases a, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, ⟨⟩, h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, cases binop.bits_eq a_a_2, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, h₂, h₃, _⟩, cases bitvec.reify_eq h₁, cases subtype.eq h₂, cases bitvec.reify_eq h₃, cases binop.bits_eq a_a_1, exact ⟨_, a_a_2, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, _, _, _, _, a_a_1, a_a_3, a_a_2, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), exact ⟨_, _, _, _, _, _, a_a, a_a_1, a_a_2, rfl, h_2⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, _, _, _, _, a_a_1, a_a_2, a_a_3, a_a_4, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, _, a_a_1, a_a_2, a_a_3, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, a_a_1⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, ⟨⟩, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨_, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, _, _, _, _, a_a_1, a_a_2, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨rfl, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, ⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨h₁, h₂, _⟩, cases subtype.eq h₁, cases bitvec.reify_eq h₂, exact ⟨_, _, cond_code.bits_eq a_a_1, a_a_2, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, a_a, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, _, _, a_a, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨_, _, a_a_1, rfl⟩ }, { cases e, rcases split_bits_ok a_a with ⟨⟨⟩, h₁, _⟩, cases bitvec.reify_eq h₁, exact ⟨rfl, _, a_a_1, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1), cases h_2, exact ⟨rfl, rfl, rfl⟩ }, { cases e, rcases split_bits_ok a_a_1 with ⟨⟨⟩, h₁, ⟨⟩, h₂, _⟩, cases bitvec.reify_eq h₁, cases bitvec.reify_eq h₂, exact ⟨_, _, _, _, a_a_2, a_a_3, rfl⟩ }, end theorem decode_aux_nil {rex a} : ¬ decode_aux rex a []. theorem decode_aux.determ_aux {rex a₁ a₂ l l'} : decode_aux rex a₁ l → decode_aux rex a₂ (l ++ l') → (a₁, l') = (a₂, []) := begin cases l with b l, {exact decode_aux_nil.elim}, apply byte_split b, introv h1 h2, replace h1 := decode_aux_aux' h1, replace h2 := decode_aux_aux' h2, unfold decode_aux' at h1 h2, repeat { do `(cond %%e _ _) ← tactic.get_local `h1 >>= tactic.infer_type, tactic.cases e $> (); `[dsimp only [cond] at h1 h2] }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { exact decode_two.determ_aux h1.2 h2.2 }, { cases h2 }, { rcases h1 with ⟨rfl, rfl⟩, rcases h2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨reg1, r1, h11, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨code1, imm1, h11, h12, rfl⟩, rcases h2 with ⟨code2, imm2, h21, h22, rfl⟩, cases h11.symm.trans h21, cases read_imm8.determ_aux h12 h22, refl }, { rcases h1 with ⟨opc1, r1, l11, imm1, l12, op1, h11, h12, h13, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, l21, imm2, l22, op2, h21, h22, h23, rfl, e⟩, cases read_opcode_ModRM.determ₂_aux h11 h21 e, cases binop.bits.determ h12 h22, cases b1, { cases read_imm.determ_aux h13 h23, refl }, { cases read_imm8.determ_aux h13 h23, refl } }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1 with ⟨reg1, r1, h11, rfl⟩, rcases h2 with ⟨reg2, r2, h21, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨reg1, r1, h11, h12, rfl⟩, rcases h2.2 with ⟨reg2, r2, h21, h22, rfl⟩, cases read_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨r1, h11, h12, rfl⟩, rcases h2.2 with ⟨r2, h21, h22, rfl⟩, cases read_opcode_ModRM.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, cases read_full_imm.determ_aux h11 h21, refl }, { rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, _, h12, h13, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, _, h22, h23, rfl, e⟩, cases read_opcode_ModRM.determ₂_aux h11 h21 e, cases binop.bits.determ h12 h22, cases read_imm8.determ_aux h13 h23, refl }, { rcases h1 with ⟨imm1, h11, rfl⟩, rcases h2 with ⟨imm2, h21, rfl⟩, split_ifs at h11 h21, { rcases h11 with ⟨rfl, rfl⟩, rcases h21 with ⟨rfl, ⟨⟩⟩, refl }, { cases read_imm16.determ_aux h11 h21, refl } }, { rcases h1 with ⟨opc1, r1, imm1, op1, l11, l12, h11, h12, rfl, rfl⟩, rcases h2 with ⟨opc2, r2, imm2, op2, l21, l22, h21, h22, rfl, e⟩, cases read_opcode_ModRM.determ₂_aux h11 h21 e, cases read_imm.determ_aux h12 h22, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨opc1, r1, op1, h11, _, h12, rfl⟩, rcases h2.2 with ⟨opc2, r2, op2, h21, _, h22, rfl⟩, cases read_opcode_ModRM.determ_aux h11 h21, cases binop.bits.determ h12 h22, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, cases read_imm32.determ_aux h11 h21, refl }, { rcases h1.2 with ⟨imm1, h11, rfl⟩, rcases h2.2 with ⟨imm2, h21, rfl⟩, split_ifs at h11 h21, { cases read_imm8.determ_aux h11 h21, refl }, { cases read_imm32.determ_aux h11 h21, refl } }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1.2 with ⟨rfl, rfl⟩, rcases h2.2 with ⟨rfl, ⟨⟩⟩, refl }, { rcases h1 with ⟨opc1, r1, l11, l12, h11, h12, rfl⟩, rcases h2 with ⟨opc2, r2, l21, l22, h21, h22, e⟩, cases read_opcode_ModRM.determ₂_aux h11 h21 e, exact decode_hi.determ_aux h12 h22 }, end theorem decode_aux.determ {rex a₁ a₂ l} (h₁ : decode_aux rex a₁ l) (h₂ : decode_aux rex a₂ l) : a₁ = a₂ := by cases decode_aux.determ_aux h₁ (by rw list.append_nil; exact h₂); refl theorem decode.no_prefix {rex rex' a l b l'} : read_prefixes rex l → b ∈ l → ¬ decode_aux rex' a (b :: l') := begin rintro ⟨⟩ (rfl|⟨⟨⟩⟩), -- generalize e : b :: l' = l₂, revert a_1_a, apply byte_split b, intros, rcases split_bits_ok a_1_a with ⟨_, ⟨⟩, _⟩, exact decode_aux_aux' end theorem decode_nil {a} : ¬ decode a [] := begin generalize e : [] = l, rintro ⟨⟩, cases a_1_l1; cases e, exact decode_aux_nil a_1_a_2 end theorem decode.determ_aux {a₁ a₂ l l'} (h₁ : decode a₁ l) (h₂ : decode a₂ (l ++ l')) : (a₁, l') = (a₂, []) := begin generalize_hyp e : l ++ l' = x at h₂, induction h₁, induction h₂, rw [list.append_assoc, list.append_eq_append_iff] at e, rcases e with ⟨_|⟨b, x⟩, rfl, e⟩ | ⟨_|⟨b, x⟩, rfl, rfl⟩, { rw list.append_nil at h₂_a_1, cases e, cases read_prefixes.determ h₁_a_1 h₂_a_1, exact decode_aux.determ_aux h₁_a_2 h₂_a_2 }, { cases h₁_l2 with b' l2, cases decode_aux_nil h₁_a_2, injection e, subst b', cases decode.no_prefix h₂_a_1 (list.mem_append_right _ (or.inl rfl)) h₁_a_2 }, { rw list.append_nil at h₁_a_1, cases read_prefixes.determ h₁_a_1 h₂_a_1, exact decode_aux.determ_aux h₁_a_2 h₂_a_2 }, { cases decode.no_prefix h₁_a_1 (list.mem_append_right _ (or.inl rfl)) h₂_a_2 }, end theorem decode.determ {a₁ a₂ l} (h₁ : decode a₁ l) (h₂ : decode a₂ l) : a₁ = a₂ := by cases decode.determ_aux h₁ (by rw list.append_nil; exact h₂); refl instance : add_comm_monoid perm := { zero := ⟨ff, ff, ff⟩, add_assoc := λ a b c, show perm.mk (_||_||_) (_||_||_) (_||_||_) = _, by repeat {rw bool.bor_assoc}; refl, zero_add := λ ⟨r, w, x⟩, show perm.mk (ff||_) (ff||_) (ff||_) = _, by repeat {rw ff_bor}, add_zero := λ ⟨r, w, x⟩, show perm.mk (_||ff) (_||ff) (_||ff) = _, by repeat {rw bor_ff}, add_comm := λ a b, show perm.mk (_||_) (_||_) (_||_) = _, by rw [bool.bor_comm, bool.bor_comm a.isW, bool.bor_comm a.isX]; refl, ..perm.has_add } theorem perm.add_self : ∀ p : perm, p + p = p | ⟨r, w, x⟩ := show perm.mk (r||r) (w||w) (x||x) = _, by repeat {rw bor_self} instance : partial_order perm := { le_refl := perm.add_self, le_trans := λ a b c (h₁ : a + b = b) (h₂ : b + c = c), show a + c = c, by rw [← h₂, ← add_assoc, h₁], le_antisymm := λ a b (h₁ : a + b = b) (h₂ : b + a = a), by rw [← h₂, add_comm, h₁], ..perm.has_le } theorem perm.le_add_left {p₁ p₂ : perm} : p₁ ≤ p₁ + p₂ := show _=_, by rw [← add_assoc, perm.add_self] theorem mem.read1.determ {p1 p2 m a b1 b2} : mem.read1 p1 m a b1 → mem.read1 p2 m a b2 → b1 = b2 := by rintro ⟨_, rfl, _⟩ ⟨_, rfl, _⟩; refl theorem mem.read'.determ_aux {p1 p2 m a l1 l2} (h₁ : mem.read' p1 m a l1) (h₂ : mem.read' p2 m a l2) : l1 <+: l2 ∨ l2 <+: l1 := begin induction h₁ generalizing l2, { exact or.inl (list.nil_prefix _) }, cases h₂, { exact or.inr (list.nil_prefix _) }, cases h₁_a.determ h₂_a, rw [list.prefix_cons_inj, list.prefix_cons_inj], exact h₁_ih h₂_a_1, end theorem mem.read'.determ_len {p1 p2 m a l1 l2} (h₁ : mem.read' p1 m a l1) (h₂ : mem.read' p2 m a l2) (h : l1.length = l2.length) : l1 = l2 := (mem.read'.determ_aux h₁ h₂).elim (λ h', list.eq_of_prefix_of_length_eq h' h) (λ h', (list.eq_of_prefix_of_length_eq h' h.symm).symm) theorem mem_decode.determ {p1 p2 m a l1 l2 ast1 ast2} (m₁ : mem.read' p1 m a l1) (h₁ : decode ast1 l1) (m₂ : mem.read' p2 m a l2) (h₂ : decode ast2 l2) : (ast1, l1) = (ast2, l2) := begin rcases mem.read'.determ_aux m₁ m₂ with ⟨x, rfl⟩ | ⟨x, rfl⟩, { cases decode.determ_aux h₁ h₂, simp }, { cases decode.determ_aux h₂ h₁, simp }, end theorem config.step_noIO {k k₁ k₂} : config.step k k₁ → ¬ config.isIO k k₂ := λ h₁ h₂, begin cases h₁, cases h₂, cases mem_decode.determ h₁_a_1 h₁_a_2 h₂_a h₂_a_1, rcases h₁_a_3 with ⟨_, s₁, _, ⟨⟩, _⟩ end theorem mem.write1.determ {m a b m₁ m₂} (h₁ : mem.write1 m a b m₁) (h₂ : mem.write1 m a b m₂) : m₁ = m₂ := by cases h₁; cases h₂; refl theorem mem.write.determ {m a l m₁ m₂} (h₁ : mem.write m a l m₁) (h₂ : mem.write m a l m₂) : m₁ = m₂ := begin induction h₁ generalizing m₂; cases h₂, refl, cases mem.write1.determ h₁_a h₂_a, cases h₁_ih h₂_a_1, refl end theorem config.write_mem.determ {k a l k₁ k₂} (h₁ : config.write_mem k a l k₁) (h₂ : config.write_mem k a l k₂) : k₁ = k₂ := by cases h₁; cases h₂; cases mem.write.determ h₁_a_1 h₂_a_1; refl theorem EA.write.determ {k ea sz v k₁ k₂} (h₁ : EA.write k ea sz v k₁) (h₂ : EA.write k ea sz v k₂) : k₁ = k₂ := begin cases h₁; cases h₂, refl, cases bits_to_byte.determ h₁_a_1 h₂_a_1, exact config.write_mem.determ h₁_a_2 h₂_a_2 end theorem config.isIO.determ {k k₁ k₂} : config.isIO k k₁ → config.isIO k k₂ → ∃ k' v₁ v₂, k₁ = config.set_reg k' 11 v₁ ∧ k₂ = config.set_reg k' 11 v₂ := begin rintro ⟨l₁, _, m₁, d₁, _, _, ⟨⟩, ⟨⟩, k', a₁, q₁, _, ⟨⟨⟩, rfl⟩, h₁⟩ ⟨l₂, _, m₂, d₂, _, _, ⟨⟩, ⟨⟩, k'', a₂, q₂, _, ⟨⟨⟩, rfl⟩, h₂⟩, cases mem_decode.determ m₁ d₁ m₂ d₂, cases EA.write.determ a₁ a₂, cases h₁, cases h₂, exact ⟨_, _, _, rfl, rfl⟩ end theorem config.step.no_exit {k k₁ r} : config.step k k₁ → ¬ config.exit k r := λ h ⟨k', h', _⟩, config.step_noIO h h' theorem set_reg_ne {k r r' q} (h : r' ≠ r) : (config.set_reg k r q).regs r' = k.regs r' := if_neg h theorem config.set_reg_11_exec_exit {k v r} : exec_exit (config.set_reg k 11 v) r ↔ exec_exit k r := begin split; rintro ⟨e⟩; split, { rwa set_reg_ne at e, rintro ⟨⟩ }, { rwa set_reg_ne, rintro ⟨⟩ }, end theorem config.isIO.determ_exec {k k₁ k₂ r} (h₁ : config.isIO k k₁) (h₂ : config.isIO k k₂) : exec_exit k₁ r ↔ exec_exit k₂ r := begin rcases h₁.determ h₂ with ⟨k', v₁, v₂, rfl, rfl⟩, simp [config.set_reg_11_exec_exit], end theorem exec_io.no_exit {i o k i' o' k' ret r} : exec_io i o k (k.regs RAX) i' o' k' ret → ¬ exec_exit k r := begin rintro h ⟨e⟩, rw e at h, rcases h with ⟨_, _, _, _, e⟩ | ⟨_, _, _, _, _, _, _, e⟩; cases bitvec.reify_eq₂ e, end theorem read_from_fd.io_part {fd i H_dat i'} (H : read_from_fd fd i H_dat i') : i' <:+ i := begin cases H, apply list.suffix_refl, exact ⟨_, rfl⟩ end theorem exec_read.io_part {i k fd count i' k' ret} (H : exec_read i k fd count i' k' ret) : i' <:+ i := begin cases H, apply list.suffix_refl, exact read_from_fd.io_part H_a_2 end theorem exec_io.io_part {k₁ i₁ o₁ k₂ i₂ o₂ call ret} (H : exec_io i₁ o₁ k₁ call i₂ o₂ k₂ ret) : i₂ <:+ i₁ ∧ o₁ <+: o₂ := begin induction H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩, exact ⟨exec_read.io_part H_a_2, list.prefix_refl _⟩, end theorem kcfg.step.no_exit {k k' r} : kcfg.step k k' → ¬ config.exit k.k r := begin rintro (⟨_, _, _, _, h⟩ | ⟨_, _, k₁, k₂, _, _, _, _, h₁, h⟩), { exact h.no_exit }, { rintro ⟨k₃, h₂, e⟩, exact h.no_exit ((h₁.determ_exec h₂).2 e) }, end theorem kcfg.step.io_part {k₁ i₁ o₁ k₂ i₂ o₂} (H : kcfg.step ⟨i₁, o₁, k₁⟩ ⟨i₂, o₂, k₂⟩) : i₂ <:+ i₁ ∧ o₁ <+: o₂ := begin cases H, exact ⟨list.suffix_refl _, list.prefix_refl _⟩, exact exec_io.io_part H_a_1 end @[simp] theorem EXTZ_id {n} (w : bitvec n) : EXTZ w = w := begin suffices : ∀ l n, list.length l = n → (@EXTZ_aux l n).to_list = l, { exact subtype.eq (this w.1 _ w.2) }, intro l, induction l; intros n e; cases e, {refl}, unfold EXTZ_aux, rw [vector.to_list_cons, l_ih _ rfl], end @[simp] theorem EXTS_id {n} (w : bitvec n) : EXTS w = w := begin suffices : ∀ l a n, list.length l = n → (@EXTS_aux l a n).to_list = l, { exact subtype.eq (this w.1 _ _ w.2) }, intro l, induction l; intros n a e; cases e, {refl}, unfold EXTS_aux, rw [vector.to_list_cons, l_ih _ _ rfl], end theorem EA.read_reg_64 {r k q} : (EA.r r).read k wsize.Sz64 q ↔ q = k.regs r := by simp [EA.read] theorem EA.readq_reg_64 {r k q} : (EA.r r).readq k wsize.Sz64 q ↔ q = k.regs r := by simp [EA.readq, EA.read_reg_64] theorem EA.write_reg_64 {r k q k'} : (EA.r r).write k wsize.Sz64 q k' ↔ k' = k.set_reg r q := by split; [{rintro ⟨⟩, refl}, {rintro rfl, constructor}] theorem EA.writeq_reg_64 {r k q k'} : (EA.r r).writeq k wsize.Sz64 q k' ↔ k' = k.set_reg r q := by simp [EA.writeq, EA.write_reg_64] theorem mem.set.read'_exists {p m q w b v} (h1 : mem.read' p m q v) : ∃ v', mem.read' p (m.set w b) q v' := begin induction h1, {exact ⟨_, mem.read'.nil _ _ _⟩}, cases h1_ih with v1 ih, rcases h1_a with ⟨_, rfl, h1⟩, exact ⟨_, mem.read'.cons ⟨_, rfl, h1⟩ ih⟩, end theorem mem.write.read'_exists {p m q a v v2 m'} (h1 : mem.read' p m q v) (h2 : mem.write m a v2 m') : ∃ v', mem.read' p m' q v' := begin induction h2 generalizing v, {exact ⟨_, h1⟩}, cases h2_a with h3 h4, cases mem.set.read'_exists h1 with v1 h1, exact h2_ih h1, end theorem EA.read.determ {k ea sz w1 w2} (h1 : EA.read k ea sz w1) (h2 : EA.read k ea sz w2) : w1 = w2 := begin cases ea, { exact h1.trans h2.symm }, { cases sz, cases sz, all_goals {exact h1.trans h2.symm} }, { rcases h1 with ⟨_, a1, b1⟩, rcases h2 with ⟨_, a2, b2⟩, cases a1.determ_len a2 (b1.1.trans b2.1.symm), exact bits_to_byte.determ_l b1 b2 }, end theorem EA.readq.determ {k ea sz q1 q2} : EA.readq k ea sz q1 → EA.readq k ea sz q2 → q1 = q2 | ⟨a1, b1, e1⟩ ⟨a2, b2, e2⟩ := by cases b1.determ b2; exact e1.trans e2.symm theorem hoare_p.bind {P P' : kcfg → Prop} (H : ∀ {{k}}, P k → hoare_p P' k) {k} : hoare_p P k → hoare_p P' k := begin intro h, induction h, exact H h_a, exact hoare_p.step h_a (λ k', h_ih _), by_cases h_ret = 0, { cases H (h_a_1 h), { exact hoare_p.zero a }, { cases a with k' h, cases h.no_exit h_a }, { exact hoare_p.exit _ _ a a_1 } }, { exact hoare_p.exit _ _ h_a h.elim }, end theorem hoare_p.mono {P P' : kcfg → Prop} (H : ∀ {{k}}, P k → P' k) {k} : hoare_p P k → hoare_p P' k := hoare_p.bind (λ k h, hoare_p.zero (H h)) end x86
3a3f1c234c5e11505fbb883f4a0b44e541792700
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/tactic14.lean
76a4347d47e8e52a0035355a60aee988f1e02d2c
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
441
lean
import Int. (* -- Tactic for trying to prove goal using reflexivity, congruence and available assumptions congr_tac = Try(unfold_tac("eq")) .. Repeat(OrElse(apply_tac("refl"), apply_tac("congr"), assumption_tac())) *) exit -- temporarily disable the following test theorem T1 (a b : Int) (f : Int -> Int) : a = b -> (f (f a)) = (f (f b)) := fun assumption : a = b, show (f (f a)) = (f (f b)), by congr_tac print environment 1.
4e00527fa6484d10f3dcaa107af5af2734aab839
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/data/int/parity.lean
f40219c0f93cc4487d477605033f113edc09e217
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
3,193
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The `even` predicate on the integers. -/ import .modeq data.nat.parity algebra.group_power namespace int @[simp] theorem mod_two_ne_one {n : int} : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] local attribute [simp] -- euclidean_domain.mod_eq_zero uses (2 ∣ n) as normal form theorem mod_two_ne_zero {n : int} : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] def even (n : int) : Prop := 2 ∣ n @[simp] theorem even_coe_nat (n : nat) : even n ↔ nat.even n := have ∀ m, 2 * to_nat m = to_nat (2 * m), from λ m, by cases m; refl, ⟨λ ⟨m, hm⟩, ⟨to_nat m, by rw [this, ←to_nat_coe_nat n, hm]⟩, λ ⟨m, hm⟩, ⟨m, by simp [hm]⟩⟩ theorem even_iff {n : int} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ lemma not_even_iff {n : ℤ} : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] @[simp] theorem two_dvd_ne_zero {n : int} : ¬ 2 ∣ n ↔ n % 2 = 1 := not_even_iff instance : decidable_pred even := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm @[simp] theorem even_zero : even (0 : int) := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even (1 : int) := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : int) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : int} : even (m + n) ↔ (even m ↔ even n) := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, -euclidean_domain.mod_eq_zero], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_neg {n : ℤ} : even (-n) ↔ even n := by simp [even] @[simp] theorem not_even_bit1 (n : int) : ¬ even (bit1 n) := by simp [bit1] with parity_simps @[parity_simps] theorem even_sub {m n : int} : even (m - n) ↔ (even m ↔ even n) := by simp [sub_eq_add_neg] with parity_simps @[parity_simps] theorem even_mul {m n : int} : even (m * n) ↔ even m ∨ even n := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, -euclidean_domain.mod_eq_zero], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_pow {m : int} {n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, even_mul, pow_succ], tauto } -- Here are examples of how `parity_simps` can be used with `int`. example (m n : int) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even (25394535 : int) := by simp end int
97f9f09aadfcfa5a0c0fc8a5b68368e762e04a94
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/bug.lean
7b9c486ce1e87de1048b5b431a61bd0f714f9ce5
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
49
lean
check fun (A A' : (Type U)) (H : A = A'), symm H
47c960ff289d5d4aefd8e2e1659dc7a58aa89798
4727251e0cd73359b15b664c3170e5d754078599
/src/number_theory/lucas_primality.lean
b7d0084fffc2650d282b257461dac1ad7036711f
[ "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,736
lean
/- Copyright (c) 2020 Bolton Bailey. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bolton Bailey -/ import data.fintype.basic import group_theory.order_of_element import tactic.zify import data.nat.totient import data.zmod.basic /-! # The Lucas test for primes. This file implements the Lucas test for primes (not to be confused with the Lucas-Lehmer test for Mersenne primes). A number `a` witnesses that `n` is prime if `a` has order `n-1` in the multiplicative group of integers mod `n`. This is checked by verifying that `a^(n-1) = 1 (mod n)` and `a^d ≠ 1 (mod n)` for any divisor `d | n - 1`. This test is the basis of the Pratt primality certificate. ## TODO - Bonus: Show the reverse implication i.e. if a number is prime then it has a Lucas witness. Use `units.is_cyclic` from `ring_theory/integral_domain` to show the group is cyclic. - Write a tactic that uses this theorem to generate Pratt primality certificates - Integrate Pratt primality certificates into the norm_num primality verifier ## Implementation notes Note that the proof for `lucas_primality` relies on analyzing the multiplicative group modulo `p`. Despite this, the theorem still holds vacuously for `p = 0` and `p = 1`: In these cases, we can take `q` to be any prime and see that `hd` does not hold, since `a^((p-1)/q)` reduces to `1`. -/ /-- If `a^(p-1) = 1 mod p`, but `a^((p-1)/q) ≠ 1 mod p` for all prime factors `q` of `p-1`, then `p` is prime. This is true because `a` has order `p-1` in the multiplicative group mod `p`, so this group must itself have order `p-1`, which only happens when `p` is prime. -/ theorem lucas_primality (p : ℕ) (a : zmod p) (ha : a^(p-1) = 1) (hd : ∀ q : ℕ, q.prime → q ∣ (p-1) → a^((p-1)/q) ≠ 1) : p.prime := begin have h0 : p ≠ 0, { rintro ⟨⟩, exact hd 2 nat.prime_two (dvd_zero _) (pow_zero _) }, have h1 : p ≠ 1, { rintro ⟨⟩, exact hd 2 nat.prime_two (dvd_zero _) (pow_zero _) }, have hp1 : 1 < p := lt_of_le_of_ne h0.bot_lt h1.symm, have order_of_a : order_of a = p-1, { apply order_of_eq_of_pow_and_pow_div_prime _ ha hd, exact tsub_pos_of_lt hp1, }, haveI fhp0 : fact (0 < p) := ⟨h0.bot_lt⟩, rw nat.prime_iff_card_units, -- Prove cardinality of `units` of `zmod p` is both `≤ p-1` and `≥ p-1` refine le_antisymm (nat.card_units_zmod_lt_sub_one hp1) _, have hp' : p - 2 + 1 = p - 1 := tsub_add_eq_add_tsub hp1, let a' : (zmod p)ˣ := units.mk_of_mul_eq_one a (a ^ (p-2)) (by rw [←pow_succ, hp', ha]), calc p - 1 = order_of a : order_of_a.symm ... = order_of a' : order_of_injective (units.coe_hom (zmod p)) units.ext a' ... ≤ fintype.card (zmod p)ˣ : order_of_le_card_univ, end
51f4bde835befb8cde777143f73aa7c5d131dd98
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/category_theory/pempty.lean
0607b9f92eadd452dc6a0f67e2483dde5de9d058
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
583
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.functor universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory instance pempty_category : small_category pempty := { hom := λ X Y, pempty, id := by obviously, comp := by obviously } namespace functor variables (C : Type u) [𝒞 : category.{v} C] include 𝒞 def empty : pempty ⥤ C := by tidy end functor end category_theory
4c3d6c21b8822bcf7f1f9ec7b2e996e671b45d27
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/measure/giry_monad.lean
327743800c415afd817e3e22e7253cfdd6d297bc
[ "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
8,540
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import measure_theory.integral.lebesgue /-! # The Giry monad Let X be a measurable space. The collection of all measures on X again forms a measurable space. This construction forms a monad on measurable spaces and measurable functions, called the Giry monad. Note that most sources use the term "Giry monad" for the restriction to *probability* measures. Here we include all measures on X. See also `measure_theory/category/Meas.lean`, containing an upgrade of the type-level monad to an honest monad of the functor `Measure : Meas ⥤ Meas`. ## References * <https://ncatlab.org/nlab/show/Giry+monad> ## Tags giry monad -/ noncomputable theory open_locale classical big_operators ennreal open classical set filter variables {α β γ δ ε : Type*} namespace measure_theory namespace measure variables [measurable_space α] [measurable_space β] /-- Measurability structure on `measure`: Measures are measurable w.r.t. all projections -/ instance : measurable_space (measure α) := ⨆ (s : set α) (hs : measurable_set s), (borel ℝ≥0∞).comap (λμ, μ s) lemma measurable_coe {s : set α} (hs : measurable_set s) : measurable (λμ : measure α, μ s) := measurable.of_comap_le $ le_supr_of_le s $ le_supr_of_le hs $ le_rfl lemma measurable_of_measurable_coe (f : β → measure α) (h : ∀(s : set α) (hs : measurable_set s), measurable (λb, f b s)) : measurable f := measurable.of_le_map $ bsupr_le $ assume s hs, measurable_space.comap_le_iff_le_map.2 $ by rw [measurable_space.map_comp]; exact h s hs lemma measurable_measure {μ : α → measure β} : measurable μ ↔ ∀(s : set β) (hs : measurable_set s), measurable (λb, μ b s) := ⟨λ hμ s hs, (measurable_coe hs).comp hμ, measurable_of_measurable_coe μ⟩ lemma measurable_map (f : α → β) (hf : measurable f) : measurable (λμ : measure α, map f μ) := measurable_of_measurable_coe _ $ assume s hs, suffices measurable (λ (μ : measure α), μ (f ⁻¹' s)), by simpa [map_apply, hs, hf], measurable_coe (hf hs) lemma measurable_dirac : measurable (measure.dirac : α → measure α) := measurable_of_measurable_coe _ $ assume s hs, begin simp only [dirac_apply', hs], exact measurable_one.indicator hs end lemma measurable_lintegral {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λμ : measure α, ∫⁻ x, f x ∂μ) := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, simple_func.lintegral], refine measurable_supr (λ n, finset.measurable_sum _ (λ i _, _)), refine measurable.const_mul _ _, exact measurable_coe ((simple_func.eapprox f n).measurable_set_preimage _) end /-- Monadic join on `measure` in the category of measurable spaces and measurable functions. -/ def join (m : measure (measure α)) : measure α := measure.of_measurable (λs hs, ∫⁻ μ, μ s ∂m) (by simp) begin assume f hf h, simp [measure_Union h hf], apply lintegral_tsum, assume i, exact measurable_coe (hf i) end @[simp] lemma join_apply {m : measure (measure α)} : ∀{s : set α}, measurable_set s → join m s = ∫⁻ μ, μ s ∂m := measure.of_measurable_apply @[simp] lemma join_zero : (0 : measure (measure α)).join = 0 := by { ext1 s hs, simp [hs] } lemma measurable_join : measurable (join : measure (measure α) → measure α) := measurable_of_measurable_coe _ $ assume s hs, by simp only [join_apply hs]; exact measurable_lintegral (measurable_coe hs) lemma lintegral_join {m : measure (measure α)} {f : α → ℝ≥0∞} (hf : measurable f) : ∫⁻ x, f x ∂(join m) = ∫⁻ μ, ∫⁻ x, f x ∂μ ∂m := begin rw [lintegral_eq_supr_eapprox_lintegral hf], have : ∀n x, join m (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x}) = ∫⁻ μ, μ ((⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {x})) ∂m := assume n x, join_apply (simple_func.measurable_set_preimage _ _), simp only [simple_func.lintegral, this], transitivity, have : ∀(s : ℕ → finset ℝ≥0∞) (f : ℕ → ℝ≥0∞ → measure α → ℝ≥0∞) (hf : ∀n r, measurable (f n r)) (hm : monotone (λn μ, ∑ r in s n, r * f n r μ)), (⨆n:ℕ, ∑ r in s n, r * ∫⁻ μ, f n r μ ∂m) = ∫⁻ μ, ⨆n:ℕ, ∑ r in s n, r * f n r μ ∂m, { assume s f hf hm, symmetry, transitivity, apply lintegral_supr, { assume n, exact finset.measurable_sum _ (assume r _, (hf _ _).const_mul _) }, { exact hm }, congr, funext n, transitivity, apply lintegral_finset_sum, { assume r _, exact (hf _ _).const_mul _ }, congr, funext r, apply lintegral_const_mul, exact hf _ _ }, specialize this (λn, simple_func.range (simple_func.eapprox f n)), specialize this (λn r μ, μ (⇑(simple_func.eapprox (λ (a : α), f a) n) ⁻¹' {r})), refine this _ _; clear this, { assume n r, apply measurable_coe, exact simple_func.measurable_set_preimage _ _ }, { change monotone (λn μ, (simple_func.eapprox f n).lintegral μ), assume n m h μ, refine simple_func.lintegral_mono _ le_rfl, apply simple_func.monotone_eapprox, assumption }, congr, funext μ, symmetry, apply lintegral_eq_supr_eapprox_lintegral, exact hf end /-- Monadic bind on `measure`, only works in the category of measurable spaces and measurable functions. When the function `f` is not measurable the result is not well defined. -/ def bind (m : measure α) (f : α → measure β) : measure β := join (map f m) @[simp] lemma bind_zero_left (f : α → measure β) : bind 0 f = 0 := by simp [bind] @[simp] lemma bind_zero_right (m : measure α) : bind m (0 : α → measure β) = 0 := begin ext1 s hs, simp only [bind, hs, join_apply, coe_zero, pi.zero_apply], rw [lintegral_map (measurable_coe hs) measurable_zero], simp end @[simp] lemma bind_zero_right' (m : measure α) : bind m (λ _, 0 : α → measure β) = 0 := bind_zero_right m @[simp] lemma bind_apply {m : measure α} {f : α → measure β} {s : set β} (hs : measurable_set s) (hf : measurable f) : bind m f s = ∫⁻ a, f a s ∂m := by rw [bind, join_apply hs, lintegral_map (measurable_coe hs) hf] lemma measurable_bind' {g : α → measure β} (hg : measurable g) : measurable (λm, bind m g) := measurable_join.comp (measurable_map _ hg) lemma lintegral_bind {m : measure α} {μ : α → measure β} {f : β → ℝ≥0∞} (hμ : measurable μ) (hf : measurable f) : ∫⁻ x, f x ∂ (bind m μ) = ∫⁻ a, ∫⁻ x, f x ∂(μ a) ∂m:= (lintegral_join hf).trans (lintegral_map (measurable_lintegral hf) hμ) lemma bind_bind {γ} [measurable_space γ] {m : measure α} {f : α → measure β} {g : β → measure γ} (hf : measurable f) (hg : measurable g) : bind (bind m f) g = bind m (λa, bind (f a) g) := measure.ext $ assume s hs, begin rw [bind_apply hs hg, bind_apply hs ((measurable_bind' hg).comp hf), lintegral_bind hf], { congr, funext a, exact (bind_apply hs hg).symm }, exact (measurable_coe hs).comp hg end lemma bind_dirac {f : α → measure β} (hf : measurable f) (a : α) : bind (dirac a) f = f a := measure.ext $ λ s hs, by rw [bind_apply hs hf, lintegral_dirac' a ((measurable_coe hs).comp hf)] lemma dirac_bind {m : measure α} : bind m dirac = m := measure.ext $ assume s hs, by simp [bind_apply hs measurable_dirac, dirac_apply' _ hs, lintegral_indicator 1 hs] lemma join_eq_bind (μ : measure (measure α)) : join μ = bind μ id := by rw [bind, map_id] lemma join_map_map {f : α → β} (hf : measurable f) (μ : measure (measure α)) : join (map (map f) μ) = map f (join μ) := measure.ext $ assume s hs, begin rw [join_apply hs, map_apply hf hs, join_apply, lintegral_map (measurable_coe hs) (measurable_map f hf)], { congr, funext ν, exact map_apply hf hs }, exact hf hs end lemma join_map_join (μ : measure (measure (measure α))) : join (map join μ) = join (join μ) := begin show bind μ join = join (join μ), rw [join_eq_bind, join_eq_bind, bind_bind measurable_id measurable_id], apply congr_arg (bind μ), funext ν, exact join_eq_bind ν end lemma join_map_dirac (μ : measure α) : join (map dirac μ) = μ := dirac_bind lemma join_dirac (μ : measure α) : join (dirac μ) = μ := eq.trans (join_eq_bind (dirac μ)) (bind_dirac measurable_id _) end measure end measure_theory
2d9cf3e2c90d58e6a0535f91fb071c2c3f29558b
618003631150032a5676f229d13a079ac875ff77
/src/data/nat/pairing.lean
0924de3a2bb6447a5ab2bc2a99eb62d36f387cb5
[ "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
3,579
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Elegant pairing function. -/ import data.nat.sqrt open prod decidable namespace nat /-- Pairing function for the natural numbers. -/ def mkpair (a b : ℕ) : ℕ := if a < b then b*b + a else a*a + a + b /-- Unpairing function for the natural numbers. -/ def unpair (n : ℕ) : ℕ × ℕ := let s := sqrt n in if n - s*s < s then (n - s*s, s) else (s, n - s*s - s) @[simp] theorem mkpair_unpair (n : ℕ) : mkpair (unpair n).1 (unpair n).2 = n := let s := sqrt n in begin dsimp [unpair], change sqrt n with s, have sm : s * s + (n - s * s) = n := nat.add_sub_cancel' (sqrt_le _), by_cases h : n - s * s < s; simp [h, mkpair], { exact sm }, { have hl : n - s*s - s ≤ s := nat.sub_le_left_of_le_add (nat.sub_le_left_of_le_add $ by rw ← add_assoc; apply sqrt_le_add), suffices : s * s + (s + (n - s * s - s)) = n, {simpa [not_lt_of_ge hl, add_assoc]}, rwa [nat.add_sub_cancel' (le_of_not_gt h)] } end theorem mkpair_unpair' {n a b} (H : unpair n = (a, b)) : mkpair a b = n := by simpa [H] using mkpair_unpair n @[simp] theorem unpair_mkpair (a b : ℕ) : unpair (mkpair a b) = (a, b) := begin by_cases a < b; simp [h, mkpair], { show unpair (b * b + a) = (a, b), have be : sqrt (b * b + a) = b, { rw sqrt_add_eq, exact le_trans (le_of_lt h) (le_add_left _ _) }, simp [unpair, be, nat.add_sub_cancel, h] }, { show unpair (a * a + a + b) = (a, b), have ae : sqrt (a * a + (a + b)) = a, { rw sqrt_add_eq, exact add_le_add_left (le_of_not_gt h) _ }, simp [unpair, ae, not_lt_zero, add_assoc] } end theorem unpair_lt {n : ℕ} (n1 : 1 ≤ n) : (unpair n).1 < n := let s := sqrt n in begin simp [unpair], change sqrt n with s, by_cases h : n - s * s < s; simp [h], { exact lt_of_lt_of_le h (sqrt_le_self _) }, { simp at h, have s0 : 0 < s := sqrt_pos.2 n1, exact lt_of_le_of_lt h (nat.sub_lt_self n1 (mul_pos s0 s0)) } end theorem unpair_le_left : ∀ (n : ℕ), (unpair n).1 ≤ n | 0 := dec_trivial | (n+1) := le_of_lt (unpair_lt (nat.succ_pos _)) theorem le_mkpair_left (a b : ℕ) : a ≤ mkpair a b := by simpa using unpair_le_left (mkpair a b) theorem le_mkpair_right (a b : ℕ) : b ≤ mkpair a b := begin by_cases h : a < b; simp [mkpair, h], exact le_trans (le_mul_self _) (le_add_right _ _) end theorem unpair_le_right (n : ℕ) : (unpair n).2 ≤ n := by simpa using le_mkpair_right n.unpair.1 n.unpair.2 theorem mkpair_lt_mkpair_left {a₁ a₂} (b) (h : a₁ < a₂) : mkpair a₁ b < mkpair a₂ b := begin by_cases h₁ : a₁ < b; simp [mkpair, h₁, add_assoc], { by_cases h₂ : a₂ < b; simp [mkpair, h₂, h], simp at h₂, apply add_lt_add_of_le_of_lt, exact mul_self_le_mul_self h₂, exact lt_add_right _ _ _ h }, { simp at h₁, simp [not_lt_of_gt (lt_of_le_of_lt h₁ h)], apply add_lt_add, exact mul_self_lt_mul_self h, apply add_lt_add_right; assumption } end theorem mkpair_lt_mkpair_right (a) {b₁ b₂} (h : b₁ < b₂) : mkpair a b₁ < mkpair a b₂ := begin by_cases h₁ : a < b₁; simp [mkpair, h₁, add_assoc], { simp [mkpair, lt_trans h₁ h, h], exact mul_self_lt_mul_self h }, { by_cases h₂ : a < b₂; simp [mkpair, h₂, h], simp at h₁, rw [add_comm, add_comm _ a, add_assoc, add_lt_add_iff_left], rwa [add_comm, ← sqrt_lt, sqrt_add_eq], exact le_trans h₁ (le_add_left _ _) } end end nat
82b54fcf276e8b0d09aeff21422946ec07b9896f
1ce2e14f78a7f514bae439fbbb1f7fa2932dd7dd
/src/vol1/default.lean
9777aefd140b7efde69222122796dd2ecfd8ee37
[ "MIT" ]
permissive
wudcscheme/lean-mathgirls
b88faf76d12e5ca07b83d6e5580663380b0bb45c
95b64a33ffb34f3c45e212c4adff3cc988dcbc60
refs/heads/master
1,678,994,115,961
1,585,127,877,000
1,585,127,877,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
60
lean
/- Math Girls, vol. 1 -/ import .chap1 import .chap2
acd4c7146e59c5827960359fef5c98772ffde5aa
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/linear_algebra/clifford_algebra/equivs.lean
2c5bf524e78a8e03e03e164901e38052077896c7
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
15,050
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.dual_number import algebra.quaternion_basis import data.complex.module import linear_algebra.clifford_algebra.conjugation import linear_algebra.clifford_algebra.star import linear_algebra.quadratic_form.prod /-! # Other constructions isomorphic to Clifford Algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains isomorphisms showing that other types are equivalent to some `clifford_algebra`. ## Rings * `clifford_algebra_ring.equiv`: any ring is equivalent to a `clifford_algebra` over a zero-dimensional vector space. ## Complex numbers * `clifford_algebra_complex.equiv`: the `complex` numbers are equivalent as an `ℝ`-algebra to a `clifford_algebra` over a one-dimensional vector space with a quadratic form that satisfies `Q (ι Q 1) = -1`. * `clifford_algebra_complex.to_complex`: the forward direction of this equiv * `clifford_algebra_complex.of_complex`: the reverse direction of this equiv We show additionally that this equivalence sends `complex.conj` to `clifford_algebra.involute` and vice-versa: * `clifford_algebra_complex.to_complex_involute` * `clifford_algebra_complex.of_complex_conj` Note that in this algebra `clifford_algebra.reverse` is the identity and so the clifford conjugate is the same as `clifford_algebra.involute`. ## Quaternion algebras * `clifford_algebra_quaternion.equiv`: a `quaternion_algebra` over `R` is equivalent as an `R`-algebra to a clifford algebra over `R × R`, sending `i` to `(0, 1)` and `j` to `(1, 0)`. * `clifford_algebra_quaternion.to_quaternion`: the forward direction of this equiv * `clifford_algebra_quaternion.of_quaternion`: the reverse direction of this equiv We show additionally that this equivalence sends `quaternion_algebra.conj` to the clifford conjugate and vice-versa: * `clifford_algebra_quaternion.to_quaternion_star` * `clifford_algebra_quaternion.of_quaternion_star` ## Dual numbers * `clifford_algebra_dual_number.equiv`: `R[ε]` is is equivalent as an `R`-algebra to a clifford algebra over `R` where `Q = 0`. -/ open clifford_algebra /-! ### The clifford algebra isomorphic to a ring -/ namespace clifford_algebra_ring open_locale complex_conjugate variables {R : Type*} [comm_ring R] @[simp] lemma ι_eq_zero : ι (0 : quadratic_form R unit) = 0 := subsingleton.elim _ _ /-- Since the vector space is empty the ring is commutative. -/ instance : comm_ring (clifford_algebra (0 : quadratic_form R unit)) := { mul_comm := λ x y, begin induction x using clifford_algebra.induction, case h_grade0 : r { apply algebra.commutes, }, case h_grade1 : x { simp, }, case h_add : x₁ x₂ hx₁ hx₂ { rw [mul_add, add_mul, hx₁, hx₂], }, case h_mul : x₁ x₂ hx₁ hx₂ { rw [mul_assoc, hx₂, ←mul_assoc, hx₁, ←mul_assoc], }, end, ..clifford_algebra.ring _ } lemma reverse_apply (x : clifford_algebra (0 : quadratic_form R unit)) : x.reverse = x := begin induction x using clifford_algebra.induction, case h_grade0 : r { exact reverse.commutes _}, case h_grade1 : x { rw [ι_eq_zero, linear_map.zero_apply, reverse.map_zero] }, case h_mul : x₁ x₂ hx₁ hx₂ { rw [reverse.map_mul, mul_comm, hx₁, hx₂] }, case h_add : x₁ x₂ hx₁ hx₂ { rw [reverse.map_add, hx₁, hx₂] }, end @[simp] lemma reverse_eq_id : (reverse : clifford_algebra (0 : quadratic_form R unit) →ₗ[R] _) = linear_map.id := linear_map.ext reverse_apply @[simp] lemma involute_eq_id : (involute : clifford_algebra (0 : quadratic_form R unit) →ₐ[R] _) = alg_hom.id R _ := by { ext, simp } /-- The clifford algebra over a 0-dimensional vector space is isomorphic to its scalars. -/ protected def equiv : clifford_algebra (0 : quadratic_form R unit) ≃ₐ[R] R := alg_equiv.of_alg_hom (clifford_algebra.lift (0 : quadratic_form R unit) $ ⟨0, λ m : unit, (zero_mul (0 : R)).trans (algebra_map R _).map_zero.symm⟩) (algebra.of_id R _) (by { ext x, exact (alg_hom.commutes _ x), }) (by { ext : 1, rw [ι_eq_zero, linear_map.comp_zero, linear_map.comp_zero], }) end clifford_algebra_ring /-! ### The clifford algebra isomorphic to the complex numbers -/ namespace clifford_algebra_complex open_locale complex_conjugate /-- The quadratic form sending elements to the negation of their square. -/ def Q : quadratic_form ℝ ℝ := -quadratic_form.sq @[simp] lemma Q_apply (r : ℝ) : Q r = - (r * r) := rfl /-- Intermediate result for `clifford_algebra_complex.equiv`: clifford algebras over `clifford_algebra_complex.Q` above can be converted to `ℂ`. -/ def to_complex : clifford_algebra Q →ₐ[ℝ] ℂ := clifford_algebra.lift Q ⟨linear_map.to_span_singleton _ _ complex.I, λ r, begin dsimp [linear_map.to_span_singleton, linear_map.id], rw mul_mul_mul_comm, simp, end⟩ @[simp] lemma to_complex_ι (r : ℝ) : to_complex (ι Q r) = r • complex.I := clifford_algebra.lift_ι_apply _ _ r /-- `clifford_algebra.involute` is analogous to `complex.conj`. -/ @[simp] lemma to_complex_involute (c : clifford_algebra Q) : to_complex (c.involute) = conj (to_complex c) := begin have : to_complex (involute (ι Q 1)) = conj (to_complex (ι Q 1)), { simp only [involute_ι, to_complex_ι, alg_hom.map_neg, one_smul, complex.conj_I] }, suffices : to_complex.comp involute = complex.conj_ae.to_alg_hom.comp to_complex, { exact alg_hom.congr_fun this c }, ext : 2, exact this end /-- Intermediate result for `clifford_algebra_complex.equiv`: `ℂ` can be converted to `clifford_algebra_complex.Q` above can be converted to. -/ def of_complex : ℂ →ₐ[ℝ] clifford_algebra Q := complex.lift ⟨ clifford_algebra.ι Q 1, by rw [clifford_algebra.ι_sq_scalar, Q_apply, one_mul, ring_hom.map_neg, ring_hom.map_one]⟩ @[simp] lemma of_complex_I : of_complex complex.I = ι Q 1 := complex.lift_aux_apply_I _ _ @[simp] lemma to_complex_comp_of_complex : to_complex.comp of_complex = alg_hom.id ℝ ℂ := begin ext1, dsimp only [alg_hom.comp_apply, subtype.coe_mk, alg_hom.id_apply], rw [of_complex_I, to_complex_ι, one_smul], end @[simp] lemma to_complex_of_complex (c : ℂ) : to_complex (of_complex c) = c := alg_hom.congr_fun to_complex_comp_of_complex c @[simp] lemma of_complex_comp_to_complex : of_complex.comp to_complex = alg_hom.id ℝ (clifford_algebra Q) := begin ext, dsimp only [linear_map.comp_apply, subtype.coe_mk, alg_hom.id_apply, alg_hom.to_linear_map_apply, alg_hom.comp_apply], rw [to_complex_ι, one_smul, of_complex_I], end @[simp] lemma of_complex_to_complex (c : clifford_algebra Q) : of_complex (to_complex c) = c := alg_hom.congr_fun of_complex_comp_to_complex c /-- The clifford algebras over `clifford_algebra_complex.Q` is isomorphic as an `ℝ`-algebra to `ℂ`. -/ @[simps] protected def equiv : clifford_algebra Q ≃ₐ[ℝ] ℂ := alg_equiv.of_alg_hom to_complex of_complex to_complex_comp_of_complex of_complex_comp_to_complex /-- The clifford algebra is commutative since it is isomorphic to the complex numbers. TODO: prove this is true for all `clifford_algebra`s over a 1-dimensional vector space. -/ instance : comm_ring (clifford_algebra Q) := { mul_comm := λ x y, clifford_algebra_complex.equiv.injective $ by rw [alg_equiv.map_mul, mul_comm, alg_equiv.map_mul], .. clifford_algebra.ring _ } /-- `reverse` is a no-op over `clifford_algebra_complex.Q`. -/ lemma reverse_apply (x : clifford_algebra Q) : x.reverse = x := begin induction x using clifford_algebra.induction, case h_grade0 : r { exact reverse.commutes _}, case h_grade1 : x { rw [reverse_ι] }, case h_mul : x₁ x₂ hx₁ hx₂ { rw [reverse.map_mul, mul_comm, hx₁, hx₂] }, case h_add : x₁ x₂ hx₁ hx₂ { rw [reverse.map_add, hx₁, hx₂] }, end @[simp] lemma reverse_eq_id : (reverse : clifford_algebra Q →ₗ[ℝ] _) = linear_map.id := linear_map.ext reverse_apply /-- `complex.conj` is analogous to `clifford_algebra.involute`. -/ @[simp] lemma of_complex_conj (c : ℂ) : of_complex (conj c) = (of_complex c).involute := clifford_algebra_complex.equiv.injective $ by rw [equiv_apply, equiv_apply, to_complex_involute, to_complex_of_complex, to_complex_of_complex] -- this name is too short for us to want it visible after `open clifford_algebra_complex` attribute [protected] Q end clifford_algebra_complex /-! ### The clifford algebra isomorphic to the quaternions -/ namespace clifford_algebra_quaternion open_locale quaternion open quaternion_algebra variables {R : Type*} [comm_ring R] (c₁ c₂ : R) /-- `Q c₁ c₂` is a quadratic form over `R × R` such that `clifford_algebra (Q c₁ c₂)` is isomorphic as an `R`-algebra to `ℍ[R,c₁,c₂]`. -/ def Q : quadratic_form R (R × R) := (c₁ • quadratic_form.sq).prod (c₂ • quadratic_form.sq) @[simp] lemma Q_apply (v : R × R) : Q c₁ c₂ v = c₁ * (v.1 * v.1) + c₂ * (v.2 * v.2) := rfl /-- The quaternion basis vectors within the algebra. -/ @[simps i j k] def quaternion_basis : quaternion_algebra.basis (clifford_algebra (Q c₁ c₂)) c₁ c₂ := { i := ι (Q c₁ c₂) (1, 0), j := ι (Q c₁ c₂) (0, 1), k := ι (Q c₁ c₂) (1, 0) * ι (Q c₁ c₂) (0, 1), i_mul_i := begin rw [ι_sq_scalar, Q_apply, ←algebra.algebra_map_eq_smul_one], simp, end, j_mul_j := begin rw [ι_sq_scalar, Q_apply, ←algebra.algebra_map_eq_smul_one], simp, end, i_mul_j := rfl, j_mul_i := begin rw [eq_neg_iff_add_eq_zero, ι_mul_ι_add_swap, quadratic_form.polar], simp, end } variables {c₁ c₂} /-- Intermediate result of `clifford_algebra_quaternion.equiv`: clifford algebras over `clifford_algebra_quaternion.Q` can be converted to `ℍ[R,c₁,c₂]`. -/ def to_quaternion : clifford_algebra (Q c₁ c₂) →ₐ[R] ℍ[R,c₁,c₂] := clifford_algebra.lift (Q c₁ c₂) ⟨ { to_fun := λ v, (⟨0, v.1, v.2, 0⟩ : ℍ[R,c₁,c₂]), map_add' := λ v₁ v₂, by simp, map_smul' := λ r v, by ext; simp }, λ v, begin dsimp, ext, all_goals {dsimp, ring}, end⟩ @[simp] lemma to_quaternion_ι (v : R × R) : to_quaternion (ι (Q c₁ c₂) v) = (⟨0, v.1, v.2, 0⟩ : ℍ[R,c₁,c₂]) := clifford_algebra.lift_ι_apply _ _ v /-- The "clifford conjugate" maps to the quaternion conjugate. -/ lemma to_quaternion_star (c : clifford_algebra (Q c₁ c₂)) : to_quaternion (star c) = star (to_quaternion c) := begin simp only [clifford_algebra.star_def'], induction c using clifford_algebra.induction, case h_grade0 : r { simp only [reverse.commutes, alg_hom.commutes, quaternion_algebra.coe_algebra_map, quaternion_algebra.star_coe], }, case h_grade1 : x { rw [reverse_ι, involute_ι, to_quaternion_ι, alg_hom.map_neg, to_quaternion_ι, quaternion_algebra.neg_mk, star_mk, neg_zero], }, case h_mul : x₁ x₂ hx₁ hx₂ { simp only [reverse.map_mul, alg_hom.map_mul, hx₁, hx₂, star_mul] }, case h_add : x₁ x₂ hx₁ hx₂ { simp only [reverse.map_add, alg_hom.map_add, hx₁, hx₂, star_add] }, end /-- Map a quaternion into the clifford algebra. -/ def of_quaternion : ℍ[R,c₁,c₂] →ₐ[R] clifford_algebra (Q c₁ c₂) := (quaternion_basis c₁ c₂).lift_hom @[simp] lemma of_quaternion_mk (a₁ a₂ a₃ a₄ : R) : of_quaternion (⟨a₁, a₂, a₃, a₄⟩ : ℍ[R,c₁,c₂]) = algebra_map R _ a₁ + a₂ • ι (Q c₁ c₂) (1, 0) + a₃ • ι (Q c₁ c₂) (0, 1) + a₄ • (ι (Q c₁ c₂) (1, 0) * ι (Q c₁ c₂) (0, 1)) := rfl @[simp] lemma of_quaternion_comp_to_quaternion : of_quaternion.comp to_quaternion = alg_hom.id R (clifford_algebra (Q c₁ c₂)) := begin ext : 1, dsimp, -- before we end up with two goals and have to do this twice ext, all_goals { dsimp, rw to_quaternion_ι, dsimp, simp only [to_quaternion_ι, zero_smul, one_smul, zero_add, add_zero, ring_hom.map_zero], }, end @[simp] lemma of_quaternion_to_quaternion (c : clifford_algebra (Q c₁ c₂)) : of_quaternion (to_quaternion c) = c := alg_hom.congr_fun (of_quaternion_comp_to_quaternion : _ = alg_hom.id R (clifford_algebra (Q c₁ c₂))) c @[simp] lemma to_quaternion_comp_of_quaternion : to_quaternion.comp of_quaternion = alg_hom.id R ℍ[R,c₁,c₂] := begin apply quaternion_algebra.lift.symm.injective, ext1; dsimp [quaternion_algebra.basis.lift]; simp, end @[simp] lemma to_quaternion_of_quaternion (q : ℍ[R,c₁,c₂]) : to_quaternion (of_quaternion q) = q := alg_hom.congr_fun (to_quaternion_comp_of_quaternion : _ = alg_hom.id R ℍ[R,c₁,c₂]) q /-- The clifford algebra over `clifford_algebra_quaternion.Q c₁ c₂` is isomorphic as an `R`-algebra to `ℍ[R,c₁,c₂]`. -/ @[simps] protected def equiv : clifford_algebra (Q c₁ c₂) ≃ₐ[R] ℍ[R,c₁,c₂] := alg_equiv.of_alg_hom to_quaternion of_quaternion to_quaternion_comp_of_quaternion of_quaternion_comp_to_quaternion /-- The quaternion conjugate maps to the "clifford conjugate" (aka `star`). -/ @[simp] lemma of_quaternion_star (q : ℍ[R,c₁,c₂]) : of_quaternion (star q) = star (of_quaternion q) := clifford_algebra_quaternion.equiv.injective $ by rw [equiv_apply, equiv_apply, to_quaternion_star, to_quaternion_of_quaternion, to_quaternion_of_quaternion] -- this name is too short for us to want it visible after `open clifford_algebra_quaternion` attribute [protected] Q end clifford_algebra_quaternion /-! ### The clifford algebra isomorphic to the dual numbers -/ namespace clifford_algebra_dual_number open_locale dual_number open dual_number triv_sq_zero_ext variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] lemma ι_mul_ι (r₁ r₂) : ι (0 : quadratic_form R R) r₁ * ι (0 : quadratic_form R R) r₂ = 0 := by rw [←mul_one r₁, ←mul_one r₂, ←smul_eq_mul R, ←smul_eq_mul R, linear_map.map_smul, linear_map.map_smul, smul_mul_smul, ι_sq_scalar, quadratic_form.zero_apply, ring_hom.map_zero, smul_zero] /-- The clifford algebra over a 1-dimensional vector space with 0 quadratic form is isomorphic to the dual numbers. -/ protected def equiv : clifford_algebra (0 : quadratic_form R R) ≃ₐ[R] R[ε] := alg_equiv.of_alg_hom (clifford_algebra.lift (0 : quadratic_form R R) ⟨inr_hom R _, λ m, inr_mul_inr _ m m⟩) (dual_number.lift ⟨ι _ (1 : R), ι_mul_ι (1 : R) 1⟩) (by { ext x : 1, dsimp, rw [lift_apply_eps, subtype.coe_mk, lift_ι_apply, inr_hom_apply, eps] }) (by { ext : 2, dsimp, rw [lift_ι_apply, inr_hom_apply, ←eps, lift_apply_eps, subtype.coe_mk] }) @[simp] lemma equiv_ι (r : R) : clifford_algebra_dual_number.equiv (ι _ r) = r • ε := (lift_ι_apply _ _ r).trans (inr_eq_smul_eps _) @[simp] lemma equiv_symm_eps : clifford_algebra_dual_number.equiv.symm (eps : R[ε]) = ι (0 : quadratic_form R R) 1 := dual_number.lift_apply_eps _ end clifford_algebra_dual_number
afcf0800d314c3f8292aa6f3bf1e8ee2fdec6bba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/general_linear_group.lean
4f8d9b42a5708d77084a3fbf64481b134a9fb988
[ "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,421
lean
/- Copyright (c) 2021 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import linear_algebra.matrix.nonsingular_inverse import linear_algebra.special_linear_group /-! # The General Linear group $GL(n, R)$ This file defines the elements of the General Linear group `general_linear_group n R`, consisting of all invertible `n` by `n` `R`-matrices. ## Main definitions * `matrix.general_linear_group` is the type of matrices over R which are units in the matrix ring. * `matrix.GL_pos` gives the subgroup of matrices with positive determinant (over a linear ordered ring). ## Tags matrix group, group, matrix inverse -/ namespace matrix universes u v open_locale matrix open linear_map /-- `GL n R` is the group of `n` by `n` `R`-matrices with unit determinant. Defined as a subtype of matrices-/ abbreviation general_linear_group (n : Type u) (R : Type v) [decidable_eq n] [fintype n] [comm_ring R] : Type* := (matrix n n R)ˣ notation `GL` := general_linear_group namespace general_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] /-- The determinant of a unit matrix is itself a unit. -/ @[simps] def det : GL n R →* Rˣ := { to_fun := λ A, { val := (↑A : matrix n n R).det, inv := (↑(A⁻¹) : matrix n n R).det, val_inv := by rw [←det_mul, ←mul_eq_mul, A.mul_inv, det_one], inv_val := by rw [←det_mul, ←mul_eq_mul, A.inv_mul, det_one]}, map_one' := units.ext det_one, map_mul' := λ A B, units.ext $ det_mul _ _ } /--The `GL n R` and `general_linear_group R n` groups are multiplicatively equivalent-/ def to_lin : (GL n R) ≃* (linear_map.general_linear_group R (n → R)) := units.map_equiv to_lin_alg_equiv'.to_mul_equiv /--Given a matrix with invertible determinant we get an element of `GL n R`-/ def mk' (A : matrix n n R) (h : invertible (matrix.det A)) : GL n R := unit_of_det_invertible A /--Given a matrix with unit determinant we get an element of `GL n R`-/ noncomputable def mk'' (A : matrix n n R) (h : is_unit (matrix.det A)) : GL n R := nonsing_inv_unit A h /--Given a matrix with non-zero determinant over a field, we get an element of `GL n K`-/ def mk_of_det_ne_zero {K : Type*} [field K] (A : matrix n n K) (h : matrix.det A ≠ 0) : GL n K := mk' A (invertible_of_nonzero h) instance coe_fun : has_coe_to_fun (GL n R) (λ _, n → n → R) := { coe := λ A, A.val } lemma ext_iff (A B : GL n R) : A = B ↔ (∀ i j, (A : matrix n n R) i j = (B : matrix n n R) i j) := units.ext_iff.trans matrix.ext_iff.symm /-- Not marked `@[ext]` as the `ext` tactic already solves this. -/ lemma ext ⦃A B : GL n R⦄ (h : ∀ i j, (A : matrix n n R) i j = (B : matrix n n R) i j) : A = B := units.ext $ matrix.ext h section coe_lemmas variables (A B : GL n R) @[simp] lemma coe_fn_eq_coe : ⇑A = (↑A : matrix n n R) := rfl @[simp] lemma coe_mul : ↑(A * B) = (↑A : matrix n n R) ⬝ (↑B : matrix n n R) := rfl @[simp] lemma coe_one : ↑(1 : GL n R) = (1 : matrix n n R) := rfl lemma coe_inv : ↑(A⁻¹) = (↑A : matrix n n R)⁻¹ := begin letI := A.invertible, exact inv_of_eq_nonsing_inv (↑A : matrix n n R), end /-- An element of the matrix general linear group on `(n) [fintype n]` can be considered as an element of the endomorphism general linear group on `n → R`. -/ def to_linear : general_linear_group n R ≃* linear_map.general_linear_group R (n → R) := units.map_equiv matrix.to_lin_alg_equiv'.to_ring_equiv.to_mul_equiv -- Note that without the `@` and `‹_›`, lean infers `λ a b, _inst_1 a b` instead of `_inst_1` as the -- decidability argument, which prevents `simp` from obtaining the instance by unification. -- These `λ a b, _inst a b` terms also appear in the type of `A`, but simp doesn't get confused by -- them so for now we do not care. @[simp] lemma coe_to_linear : (@to_linear n ‹_› ‹_› _ _ A : (n → R) →ₗ[R] (n → R)) = matrix.mul_vec_lin A := rfl @[simp] lemma to_linear_apply (v : n → R) : (@to_linear n ‹_› ‹_› _ _ A) v = matrix.mul_vec_lin A v := rfl end coe_lemmas end general_linear_group namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R] instance has_coe_to_general_linear_group : has_coe (special_linear_group n R) (GL n R) := ⟨λ A, ⟨↑A, ↑(A⁻¹), congr_arg coe (mul_right_inv A), congr_arg coe (mul_left_inv A)⟩⟩ end special_linear_group section variables {n : Type u} {R : Type v} [decidable_eq n] [fintype n] [linear_ordered_comm_ring R ] section variables (n R) /-- This is the subgroup of `nxn` matrices with entries over a linear ordered ring and positive determinant. -/ def GL_pos : subgroup (GL n R) := (units.pos_subgroup R).comap general_linear_group.det end @[simp] lemma mem_GL_pos (A : GL n R) : A ∈ GL_pos n R ↔ 0 < (A.det : R) := iff.rfl end section has_neg variables {n : Type u} {R : Type v} [decidable_eq n] [fintype n] [linear_ordered_comm_ring R ] [fact (even (fintype.card n))] /-- Formal operation of negation on general linear group on even cardinality `n` given by negating each element. -/ instance : has_neg (GL_pos n R) := ⟨λ g, ⟨- g, begin simp only [mem_GL_pos, general_linear_group.coe_det_apply, units.coe_neg], have := det_smul g (-1), simp only [general_linear_group.coe_fn_eq_coe, one_smul, coe_fn_coe_base', neg_smul] at this, rw this, simp [nat.neg_one_pow_of_even (fact.out (even (fintype.card n)))], have gdet := g.property, simp only [mem_GL_pos, general_linear_group.coe_det_apply, subtype.val_eq_coe] at gdet, exact gdet, end⟩⟩ @[simp] lemma GL_pos_coe_neg (g : GL_pos n R) : ↑(- g) = - (↑g : matrix n n R) := rfl @[simp]lemma GL_pos_neg_elt (g : GL_pos n R): ∀ i j, ( ↑(-g): matrix n n R) i j= - (g i j):= begin simp [coe_fn_coe_base'], end end has_neg namespace special_linear_group variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [linear_ordered_comm_ring R] /-- `special_linear_group n R` embeds into `GL_pos n R` -/ def to_GL_pos : special_linear_group n R →* GL_pos n R := { to_fun := λ A, ⟨(A : GL n R), show 0 < (↑A : matrix n n R).det, from A.prop.symm ▸ zero_lt_one⟩, map_one' := subtype.ext $ units.ext $ rfl, map_mul' := λ A₁ A₂, subtype.ext $ units.ext $ rfl } instance : has_coe (special_linear_group n R) (GL_pos n R) := ⟨to_GL_pos⟩ lemma coe_eq_to_GL_pos : (coe : special_linear_group n R → GL_pos n R) = to_GL_pos := rfl lemma to_GL_pos_injective : function.injective (to_GL_pos : special_linear_group n R → GL_pos n R) := (show function.injective ((coe : GL_pos n R → matrix n n R) ∘ to_GL_pos), from subtype.coe_injective).of_comp end special_linear_group section examples /-- The matrix [a, b; -b, a] (inspired by multiplication by a complex number); it is an element of $GL_2(R)$ if `a ^ 2 + b ^ 2` is nonzero. -/ @[simps coe {fully_applied := ff}] def plane_conformal_matrix {R} [field R] (a b : R) (hab : a ^ 2 + b ^ 2 ≠ 0) : matrix.general_linear_group (fin 2) R := general_linear_group.mk_of_det_ne_zero ![![a, -b], ![b, a]] (by simpa [det_fin_two, sq] using hab) /- TODO: Add Iwasawa matrices `n_x=![![1,x],![0,1]]`, `a_t=![![exp(t/2),0],![0,exp(-t/2)]]` and `k_θ==![![cos θ, sin θ],![-sin θ, cos θ]]` -/ end examples end matrix
57c4f45006f2a1c8d558bd9b7c8d194ce501d7d9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/ulift.lean
7635fe79241ee4ce20660b94ba970c0496247ebb
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,434
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 data.int.cast.defs import algebra.hom.equiv.basic import algebra.group_with_zero.inj_surj /-! # `ulift` instances for groups and monoids > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines instances for group, monoid, semigroup and related structures on `ulift` types. (Recall `ulift α` is just a "copy" of a type `α` in a higher universe.) We use `tactic.pi_instance_derive_field`, even though it wasn't intended for this purpose, which seems to work fine. We also provide `ulift.mul_equiv : ulift R ≃* R` (and its additive analogue). -/ universes u v variables {α : Type u} {β : Type*} {x y : ulift.{v} α} namespace ulift @[to_additive] instance has_one [has_one α] : has_one (ulift α) := ⟨⟨1⟩⟩ @[simp, to_additive] lemma one_down [has_one α] : (1 : ulift α).down = 1 := rfl @[to_additive] instance has_mul [has_mul α] : has_mul (ulift α) := ⟨λ f g, ⟨f.down * g.down⟩⟩ @[simp, to_additive] lemma mul_down [has_mul α] : (x * y).down = x.down * y.down := rfl @[to_additive] instance has_div [has_div α] : has_div (ulift α) := ⟨λ f g, ⟨f.down / g.down⟩⟩ @[simp, to_additive] lemma div_down [has_div α] : (x / y).down = x.down / y.down := rfl @[to_additive] instance has_inv [has_inv α] : has_inv (ulift α) := ⟨λ f, ⟨f.down⁻¹⟩⟩ @[simp, to_additive] lemma inv_down [has_inv α] : x⁻¹.down = (x.down)⁻¹ := rfl @[to_additive] instance has_smul [has_smul α β] : has_smul α (ulift β) := ⟨λ n x, up (n • x.down)⟩ @[simp, to_additive] lemma smul_down [has_smul α β] (a : α) (b : ulift.{v} β) : (a • b).down = a • b.down := rfl @[to_additive has_smul, to_additive_reorder 1] instance has_pow [has_pow α β] : has_pow (ulift α) β := ⟨λ x n, up (x.down ^ n)⟩ @[simp, to_additive smul_down, to_additive_reorder 1] lemma pow_down [has_pow α β] (a : ulift.{v} α) (b : β) : (a ^ b).down = a.down ^ b := rfl /-- The multiplicative equivalence between `ulift α` and `α`. -/ @[to_additive "The additive equivalence between `ulift α` and `α`."] def _root_.mul_equiv.ulift [has_mul α] : ulift α ≃* α := { map_mul' := λ x y, rfl, .. equiv.ulift } @[to_additive] instance semigroup [semigroup α] : semigroup (ulift α) := mul_equiv.ulift.injective.semigroup _ $ λ x y, rfl @[to_additive] instance comm_semigroup [comm_semigroup α] : comm_semigroup (ulift α) := equiv.ulift.injective.comm_semigroup _ $ λ x y, rfl @[to_additive] instance mul_one_class [mul_one_class α] : mul_one_class (ulift α) := equiv.ulift.injective.mul_one_class _ rfl $ λ x y, rfl instance mul_zero_one_class [mul_zero_one_class α] : mul_zero_one_class (ulift α) := equiv.ulift.injective.mul_zero_one_class _ rfl rfl $ λ x y, rfl @[to_additive] instance monoid [monoid α] : monoid (ulift α) := equiv.ulift.injective.monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance comm_monoid [comm_monoid α] : comm_monoid (ulift α) := equiv.ulift.injective.comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance [has_nat_cast α] : has_nat_cast (ulift α) := ⟨λ n, up n⟩ instance [has_int_cast α] : has_int_cast (ulift α) := ⟨λ n, up n⟩ @[simp, norm_cast] lemma up_nat_cast [has_nat_cast α] (n : ℕ) : up (n : α) = n := rfl @[simp, norm_cast] lemma up_int_cast [has_int_cast α] (n : ℤ) : up (n : α) = n := rfl @[simp, norm_cast] lemma down_nat_cast [has_nat_cast α] (n : ℕ) : down (n : ulift α) = n := rfl @[simp, norm_cast] lemma down_int_cast [has_int_cast α] (n : ℤ) : down (n : ulift α) = n := rfl instance add_monoid_with_one [add_monoid_with_one α] : add_monoid_with_one (ulift α) := { nat_cast_zero := congr_arg ulift.up nat.cast_zero, nat_cast_succ := λ n, congr_arg ulift.up (nat.cast_succ _), .. ulift.has_one, .. ulift.add_monoid, ..ulift.has_nat_cast } instance add_comm_monoid_with_one [add_comm_monoid_with_one α] : add_comm_monoid_with_one (ulift α) := { ..ulift.add_monoid_with_one, .. ulift.add_comm_monoid } instance monoid_with_zero [monoid_with_zero α] : monoid_with_zero (ulift α) := equiv.ulift.injective.monoid_with_zero _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) instance comm_monoid_with_zero [comm_monoid_with_zero α] : comm_monoid_with_zero (ulift α) := equiv.ulift.injective.comm_monoid_with_zero _ rfl rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance div_inv_monoid [div_inv_monoid α] : div_inv_monoid (ulift α) := equiv.ulift.injective.div_inv_monoid _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance group [group α] : group (ulift α) := equiv.ulift.injective.group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive] instance comm_group [comm_group α] : comm_group (ulift α) := equiv.ulift.injective.comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance add_group_with_one [add_group_with_one α] : add_group_with_one (ulift α) := { int_cast := λ n, ⟨n⟩, int_cast_of_nat := λ n, congr_arg ulift.up (int.cast_of_nat _), int_cast_neg_succ_of_nat := λ n, congr_arg ulift.up (int.cast_neg_succ_of_nat _), .. ulift.add_monoid_with_one, .. ulift.add_group } instance add_comm_group_with_one [add_comm_group_with_one α] : add_comm_group_with_one (ulift α) := { ..ulift.add_group_with_one, .. ulift.add_comm_group } instance group_with_zero [group_with_zero α] : group_with_zero (ulift α) := equiv.ulift.injective.group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) instance comm_group_with_zero [comm_group_with_zero α] : comm_group_with_zero (ulift α) := equiv.ulift.injective.comm_group_with_zero _ rfl rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [left_cancel_semigroup α] : left_cancel_semigroup (ulift α) := equiv.ulift.injective.left_cancel_semigroup _ (λ _ _, rfl) @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [right_cancel_semigroup α] : right_cancel_semigroup (ulift α) := equiv.ulift.injective.right_cancel_semigroup _ (λ _ _, rfl) @[to_additive add_left_cancel_monoid] instance left_cancel_monoid [left_cancel_monoid α] : left_cancel_monoid (ulift α) := equiv.ulift.injective.left_cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_right_cancel_monoid] instance right_cancel_monoid [right_cancel_monoid α] : right_cancel_monoid (ulift α) := equiv.ulift.injective.right_cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_cancel_monoid] instance cancel_monoid [cancel_monoid α] : cancel_monoid (ulift α) := equiv.ulift.injective.cancel_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) @[to_additive add_cancel_comm_monoid] instance cancel_comm_monoid [cancel_comm_monoid α] : cancel_comm_monoid (ulift α) := equiv.ulift.injective.cancel_comm_monoid _ rfl (λ _ _, rfl) (λ _ _, rfl) instance nontrivial [nontrivial α] : nontrivial (ulift α) := equiv.ulift.symm.injective.nontrivial -- TODO we don't do `ordered_cancel_comm_monoid` or `ordered_comm_group` -- We'd need to add instances for `ulift` in `order.basic`. end ulift
122c38ca86365826ebc1c89b7f4c19e163a5787a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/ring/semiconj.lean
8cf0538e473613a7a08f886fb041112bbf5707a5
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
2,604
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Yury Kudryashov, Neil Strickland -/ import algebra.group.semiconj import algebra.ring.defs /-! # Semirings and rings > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/751 > Any changes to this file require a corresponding PR to mathlib4. This file gives lemmas about semirings, rings and domains. This is analogous to `algebra.group.basic`, the difference being that the former is about `+` and `*` separately, while the present file is about their interaction. For the definitions of semirings and rings see `algebra.ring.defs`. -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} open function namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] section variables [has_mul R] [has_distrib_neg R] {a x y : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul, mul_neg] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul, mul_neg] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ end section variables [mul_one_class R] [has_distrib_neg R] {a x y : R} @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left end section variables [non_unital_non_assoc_ring R] {a b x y x' y' : R} @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := by simpa only [sub_eq_add_neg] using h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := by simpa only [sub_eq_add_neg] using ha.add_left hb.neg_left end end semiconj_by
d45395c26f71821942c17759cc07a96b277d3819
70f8755415fa7a17f87402cde4651e9f4db1b5bb
/src/mvqpf/cofix.lean
6dabbf543e087b3bc3235ccac140ab2b120cf32b
[ "Apache-2.0" ]
permissive
shingarov/qpf
ab935dc2298db12c87ac011a2e4d2c27e0bdef4b
debe2eacb8cf46b21aba2eaf3f2e20940da0263b
refs/heads/master
1,653,705,576,607
1,570,136,035,000
1,570,136,035,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,100
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The initial algebra of a multivariate qpf is again a qpf. -/ import ..mvpfunctor.M .basic universe u namespace mvqpf open typevec open mvfunctor (liftp liftr) variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q def corecF {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) : β → q.P.M α := q.P.M_corec (λ x, repr (g x)) theorem corecF_eq {α : typevec n} {β : Type*} (g : β → F (α.append1 β)) (x : β) : q.P.M_dest (corecF g x) = append_fun id (corecF g) <$$> repr (g x) := by rw [corecF, q.P.M_dest_corec] def is_precongr {α : typevec n} (r : q.P.M α → q.P.M α → Prop) : Prop := ∀ ⦃x y⦄, r x y → abs (append_fun id (quot.mk r) <$$> q.P.M_dest x) = abs (append_fun id (quot.mk r) <$$> q.P.M_dest y) def Mcongr {α : typevec n} : q.P.M α → q.P.M α → Prop := λ x y, ∃ r, is_precongr r ∧ r x y def cofix (F : typevec (n + 1) → Type u) [mvfunctor F] [q : mvqpf F] (α : typevec n):= quot (@Mcongr _ F _ q α) def cofix.map {α β : typevec n} (g : α ⟹ β) : cofix F α → cofix F β := quot.lift (λ x : q.P.M α, quot.mk Mcongr (g <$$> x)) begin rintros a₁ a₂ ⟨r, pr, ra₁a₂⟩, apply quot.sound, let r' := λ b₁ b₂, ∃ a₁ a₂ : q.P.M α, r a₁ a₂ ∧ b₁ = g <$$> a₁ ∧ b₂ = g <$$> a₂, use r', split, { show is_precongr r', rintros b₁ b₂ ⟨a₁, a₂, ra₁a₂, b₁eq, b₂eq⟩, let u : quot r → quot r' := quot.lift (λ x : q.P.M α, quot.mk r' (g <$$> x)) (by { intros a₁ a₂ ra₁a₂, apply quot.sound, exact ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩ }), have hu : (quot.mk r' ∘ λ x : q.P.M α, g <$$> x) = u ∘ quot.mk r, { ext x, refl }, rw [b₁eq, b₂eq, q.P.M_dest_map, q.P.M_dest_map, ←q.P.comp_map, ←q.P.comp_map], rw [←append_fun_comp, id_comp, hu, hu, ←comp_id g, append_fun_comp], rw [q.P.comp_map, q.P.comp_map, abs_map, pr ra₁a₂, ←abs_map] }, show r' (g <$$> a₁) (g <$$> a₂), from ⟨a₁, a₂, ra₁a₂, rfl, rfl⟩ end instance cofix.mvfunctor : mvfunctor (cofix F) := { map := @cofix.map _ _ _ _} def cofix.corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) : β → cofix F α := λ x, quot.mk _ (corecF g x) def cofix.dest {α : typevec n} : cofix F α → F (α.append1 (cofix F α)) := quot.lift (λ x, append_fun id (quot.mk Mcongr) <$$> (abs (q.P.M_dest x))) begin rintros x y ⟨r, pr, rxy⟩, dsimp, have : ∀ x y, r x y → Mcongr x y, { intros x y h, exact ⟨r, pr, h⟩ }, rw [←quot.factor_mk_eq _ _ this], dsimp, conv { to_lhs, rw [append_fun_comp_id, comp_map, ←abs_map, pr rxy, abs_map, ←comp_map, ←append_fun_comp_id] } end theorem cofix.dest_corec {α : typevec n} {β : Type u} (g : β → F (α.append1 β)) (x : β) : cofix.dest (cofix.corec g x) = append_fun id (cofix.corec g) <$$> g x := begin conv { to_lhs, rw [cofix.dest, cofix.corec] }, dsimp, rw [corecF_eq, abs_map, abs_repr, ←comp_map, ←append_fun_comp], reflexivity end def cofix.mk {α : typevec n} : F (α.append1 $ cofix F α) → cofix F α := cofix.corec (λ x, append_fun id (λ i : cofix F α, cofix.dest.{u} i) <$$> x) private theorem cofix.bisim_aux {α : typevec n} (r : cofix F α → cofix F α → Prop) (h' : ∀ x, r x x) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := begin intro x, apply quot.induction_on x, clear x, intros x y, apply quot.induction_on y, clear y, intros y rxy, apply quot.sound, let r' := λ x y, r (quot.mk _ x) (quot.mk _ y), have : is_precongr r', { intros a b r'ab, have h₀ : append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (q.P.M_dest a) = append_fun id (quot.mk r ∘ quot.mk Mcongr) <$$> abs (q.P.M_dest b) := by rw [append_fun_comp_id, comp_map, comp_map]; exact h _ _ r'ab, have h₁ : ∀ u v : q.P.M α, Mcongr u v → quot.mk r' u = quot.mk r' v, { intros u v cuv, apply quot.sound, dsimp [r'], rw quot.sound cuv, apply h' }, let f : quot r → quot r' := quot.lift (quot.lift (quot.mk r') h₁) begin intro c, apply quot.induction_on c, clear c, intros c d, apply quot.induction_on d, clear d, intros d rcd, apply quot.sound, apply rcd end, have : f ∘ quot.mk r ∘ quot.mk Mcongr = quot.mk r' := rfl, rw [←this, append_fun_comp_id, q.P.comp_map, q.P.comp_map, abs_map, abs_map, abs_map, abs_map, h₀] }, refine ⟨r', this, rxy⟩ end theorem cofix.bisim_rel {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → append_fun id (quot.mk r) <$$> cofix.dest x = append_fun id (quot.mk r) <$$> cofix.dest y) : ∀ x y, r x y → x = y := let r' x y := x = y ∨ r x y in begin intros x y rxy, apply cofix.bisim_aux r', { intro x, left, reflexivity }, { intros x y r'xy, cases r'xy, { rw r'xy }, have : ∀ x y, r x y → r' x y := λ x y h, or.inr h, rw ←quot.factor_mk_eq _ _ this, dsimp, rw [append_fun_comp_id, append_fun_comp_id], rw [@comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r)), @comp_map _ _ _ q _ _ _ (append_fun id (quot.mk r))], rw h _ _ r'xy }, right, exact rxy end theorem cofix.bisim {α : typevec n} (r : cofix F α → cofix F α → Prop) (h : ∀ x y, r x y → liftr (rel_last α r) (cofix.dest x) (cofix.dest y)) : ∀ x y, r x y → x = y := begin apply cofix.bisim_rel, intros x y rxy, rcases (liftr_iff (rel_last α r) _ _).mp (h x y rxy) with ⟨a, f₀, f₁, dxeq, dyeq, h'⟩, rw [dxeq, dyeq, ←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], rw [←split_drop_fun_last_fun f₀, ←split_drop_fun_last_fun f₁], rw [append_fun_comp_split_fun, append_fun_comp_split_fun], rw [id_comp, id_comp], congr' 2, ext i j, cases i with _ i; dsimp, { change f₀ _ j = f₁ _ j, apply h' _ j }, apply quot.sound, apply h' _ j end theorem cofix.bisim' {α : typevec n} {β : Type*} (Q : β → Prop) (u v : β → cofix F α) (h : ∀ x, Q x → ∃ a f' f₀ f₁, cofix.dest (u x) = abs ⟨a, q.P.append_contents f' f₀⟩ ∧ cofix.dest (v x) = abs ⟨a, q.P.append_contents f' f₁⟩ ∧ ∀ i, ∃ x', Q x' ∧ f₀ i = u x' ∧ f₁ i = v x') : ∀ x, Q x → u x = v x := λ x Qx, let R := λ w z : cofix F α, ∃ x', Q x' ∧ w = u x' ∧ z = v x' in cofix.bisim R (λ x y ⟨x', Qx', xeq, yeq⟩, begin rcases h x' Qx' with ⟨a, f', f₀, f₁, ux'eq, vx'eq, h'⟩, rw liftr_iff, refine ⟨a, q.P.append_contents f' f₀, q.P.append_contents f' f₁, xeq.symm ▸ ux'eq, yeq.symm ▸ vx'eq, _⟩, intro i, cases i, { intro j, apply eq.refl }, apply h', end) _ _ ⟨x, Qx, rfl, rfl⟩ lemma cofix.mk_dest {α : typevec n} (x : cofix F α) : cofix.mk (cofix.dest x) = x := begin apply cofix.bisim_rel (λ x y : cofix F α, x = cofix.mk (cofix.dest y)) _ _ _ rfl, dsimp, intros x y h, rw h, conv { to_lhs, congr, skip, rw [cofix.mk], rw cofix.dest_corec}, rw [←comp_map, ←append_fun_comp, id_comp], rw [←comp_map, ←append_fun_comp, id_comp, ←cofix.mk], congr' 2, ext u, apply quot.sound, refl end lemma cofix.dest_mk {α : typevec n} (x : F (α.append1 $ cofix F α)) : cofix.dest (cofix.mk x) = x := begin have : cofix.mk ∘ cofix.dest = @_root_.id (cofix F α) := funext cofix.mk_dest, rw [cofix.mk, cofix.dest_corec, ←comp_map, ←cofix.mk, ← append_fun_comp, this, id_comp, append_fun_id_id, id_map] end noncomputable instance mvqpf_cofix : mvqpf (cofix F) := { P := q.P.Mp, abs := λ α, quot.mk Mcongr, repr' := λ α, quot.out, abs_repr' := λ α, quot.out_eq, abs_map := λ α β g x, rfl } end mvqpf
e53c64f190d03ffe645ecbeef6de21ccf9b7cbaf
63abd62053d479eae5abf4951554e1064a4c45b4
/src/tactic/interval_cases.lean
67c8273eafe5745585ffcf9c3ca3d554b2beac47
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
10,923
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Scott Morrison Case bashing on variables in finite intervals. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. -/ import tactic.fin_cases import data.fintype.intervals open set namespace tactic namespace interval_cases /-- If `e` easily implies `(%%n < %%b)` for some explicit `b`, return that proof. -/ -- We use `expr.to_rat` merely to decide if an `expr` is an explicit number. -- It would be more natural to use `expr.to_int`, but that hasn't been implemented. meta def gives_upper_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' < %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b > %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' ≤ %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | `(%%b ≥ %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.lt_add_one_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.lt_add_one_iff.mpr %%e) | `(ℤ) := to_expr ``(int.lt_add_one_iff.mpr %%e) | _ := failed end | _ := failed end /-- If `e` easily implies `(%%n ≥ %%b)` for some explicit `b`, return that proof. -/ meta def gives_lower_bound (n e : expr) : tactic expr := do t ← infer_type e, match t with | `(%%n' ≥ %%b) := do guard (n = n'), b ← b.to_rat, return e | `(%%b ≤ %%n') := do guard (n = n'), b ← b.to_rat, return e | `(%%n' > %%b) := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | `(%%b < %%n') := do guard (n = n'), b ← b.to_rat, tn ← infer_type n, match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end | _ := failed end /-- Combine two upper bounds. -/ meta def combine_upper_bounds : option expr → option expr → tactic (option expr) | none none := return none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(lt_min %%prf₁ %%prf₂) /-- Combine two lower bounds. -/ meta def combine_lower_bounds : option expr → option expr → tactic (option expr) | none none := return $ none | (some prf) none := return $ some prf | none (some prf) := return $ some prf | (some prf₁) (some prf₂) := do option.some <$> to_expr ``(max_le %%prf₂ %%prf₁) /-- Inspect a given expression, using it to update a set of upper and lower bounds on `n`. -/ meta def update_bounds (n : expr) (bounds : option expr × option expr) (e : expr) : tactic (option expr × option expr) := do nlb ← try_core $ gives_lower_bound n e, nub ← try_core $ gives_upper_bound n e, clb ← combine_lower_bounds bounds.1 nlb, cub ← combine_upper_bounds bounds.2 nub, return (clb, cub) /-- Attempt to find a lower bound for the variable `n`, by evaluating `bot_le n`. -/ meta def initial_lower_bound (n : expr) : tactic expr := do e ← to_expr ``(@bot_le _ _ %%n), t ← infer_type e, match t with | `(%%b ≤ %%n) := do return e | _ := failed end /-- Attempt to find an upper bound for the variable `n`, by evaluating `le_top n`. -/ meta def initial_upper_bound (n : expr) : tactic expr := do e ← to_expr ``(@le_top _ _ %%n), match e with | `(%%n ≤ %%b) := do tn ← infer_type n, e ← match tn with | `(ℕ) := to_expr ``(nat.add_one_le_iff.mpr %%e) | `(ℕ+) := to_expr ``(pnat.add_one_le_iff.mpr %%e) | `(ℤ) := to_expr ``(int.add_one_le_iff.mpr %%e) | _ := failed end, return e | _ := failed end /-- Inspect the local hypotheses for upper and lower bounds on a variable `n`. -/ meta def get_bounds (n : expr) : tactic (expr × expr) := do hl ← try_core (initial_lower_bound n), hu ← try_core (initial_upper_bound n), lc ← local_context, r ← lc.mfoldl (update_bounds n) (hl, hu), match r with | (_, none) := fail "No upper bound located." | (none, _) := fail "No lower bound located." | (some lb_prf, some ub_prf) := return (lb_prf, ub_prf) end /-- The finset of elements of a set `s` for which we have `fintype s`. -/ def set_elems {α} [decidable_eq α] (s : set α) [fintype s] : finset α := (fintype.elems s).image subtype.val /-- Each element of `s` is a member of `set_elems s`. -/ lemma mem_set_elems {α} [decidable_eq α] (s : set α) [fintype s] {a : α} (h : a ∈ s) : a ∈ set_elems s := finset.mem_image.2 ⟨⟨a, h⟩, fintype.complete _, rfl⟩ end interval_cases open interval_cases /-- Call `fin_cases` on membership of the finset built from an `Ico` interval corresponding to a lower and an upper bound. Here `hl` should be an expression of the form `a ≤ n`, for some explicit `a`, and `hu` should be of the form `n < b`, for some explicit `b`. By default `interval_cases_using` automatically generates a name for the new hypothesis. The name can be specified via the optional argument `n`. -/ meta def interval_cases_using (hl hu : expr) (n : option name) : tactic unit := to_expr ``(mem_set_elems (Ico _ _) ⟨%%hl, %%hu⟩) >>= (if hn : n.is_some then note (option.get hn) else note_anon none) >>= fin_cases_at none setup_tactic_parser namespace interactive local postfix `?`:9001 := optional /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can specify a name `h` for the new hypothesis, as `interval_cases n with h` or `interval_cases n using hl hu with h`. -/ meta def interval_cases (n : parse texpr?) (bounds : parse (tk "using" *> (prod.mk <$> ident <*> ident))?) (lname : parse (tk "with" *> ident)?) : tactic unit := do if h : n.is_some then (do guard bounds.is_none <|> fail "Do not use the `using` keyword if specifying the variable explicitly.", n ← to_expr (option.get h), (hl, hu) ← get_bounds n, tactic.interval_cases_using hl hu lname) else if h' : bounds.is_some then (do [hl, hu] ← [(option.get h').1, (option.get h').2].mmap get_local, tactic.interval_cases_using hl hu lname) else fail "Call `interval_cases n` (specifying a variable), or `interval_cases lb ub` (specifying a lower bound and upper bound on the same variable)." /-- `interval_cases n` searches for upper and lower bounds on a variable `n`, and if bounds are found, splits into separate cases for each possible value of `n`. As an example, in ``` example (n : ℕ) (w₁ : n ≥ 3) (w₂ : n < 5) : n = 3 ∨ n = 4 := begin interval_cases n, all_goals {simp} end ``` after `interval_cases n`, the goals are `3 = 3 ∨ 3 = 4` and `4 = 3 ∨ 4 = 4`. You can also explicitly specify a lower and upper bound to use, as `interval_cases using hl hu`. The hypotheses should be in the form `hl : a ≤ n` and `hu : n < b`, in which case `interval_cases` calls `fin_cases` on the resulting fact `n ∈ set.Ico a b`. You can also explicitly specify a name to use for the hypothesis added, as `interval_cases n with hn` or `interval_cases n using hl hu with hn`. In particular, `interval_cases n` 1) inspects hypotheses looking for lower and upper bounds of the form `a ≤ n` and `n < b` (although in `ℕ`, `ℤ`, and `ℕ+` bounds of the form `a < n` and `n ≤ b` are also allowed), and also makes use of lower and upper bounds found via `le_top` and `bot_le` (so for example if `n : ℕ`, then the bound `0 ≤ n` is found automatically), then 2) calls `fin_cases` on the synthesised hypothesis `n ∈ set.Ico a b`, assuming an appropriate `fintype` instance can be found for the type of `n`. The variable `n` can belong to any type `α`, with the following restrictions: * only bounds on which `expr.to_rat` succeeds will be considered "explicit" (TODO: generalise this?) * an instance of `decidable_eq α` is available, * an explicit lower bound can be found amongst the hypotheses, or from `bot_le n`, * an explicit upper bound can be found amongst the hypotheses, or from `le_top n`, * if multiple bounds are located, an instance of `linear_order α` is available, and * an instance of `fintype set.Ico l u` is available for the relevant bounds. -/ add_tactic_doc { name := "interval_cases", category := doc_category.tactic, decl_names := [`tactic.interactive.interval_cases], tags := ["case bashing"] } end interactive end tactic
ca0ae7271ef571b21f53eb499330c1dfa2f7b652
5ee26964f602030578ef0159d46145dd2e357ba5
/src/for_mathlib/uniform_space/basic.lean
1b928a5af8993d1fe8fd3268610825a33a7c2f84
[ "Apache-2.0" ]
permissive
fpvandoorn/lean-perfectoid-spaces
569b4006fdfe491ca8b58dd817bb56138ada761f
06cec51438b168837fc6e9268945735037fd1db6
refs/heads/master
1,590,154,571,918
1,557,685,392,000
1,557,685,392,000
186,363,547
0
0
Apache-2.0
1,557,730,933,000
1,557,730,933,000
null
UTF-8
Lean
false
false
1,396
lean
import topology.uniform_space.basic import topology.uniform_space.uniform_embedding import for_mathlib.function section open uniform_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [uniform_space α] [uniform_space β] [uniform_space γ] [uniform_space δ] def uniform_continuous₂ (f : α → β → γ) := uniform_continuous (function.uncurry f) lemma uniform_continuous₂_def (f : α → β → γ) : uniform_continuous₂ f ↔ uniform_continuous (function.uncurry f) := iff.rfl lemma uniform_continuous₂_curry (f : α × β → γ) : uniform_continuous₂ (function.curry f) ↔ uniform_continuous f := by rw [←function.uncurry_curry f] {occs := occurrences.pos [2]} ; refl lemma uniform_continuous₂.comp {f : α → β → γ} {g : γ → δ} (hf : uniform_continuous₂ f)(hg : uniform_continuous g) : uniform_continuous₂ (g ∘₂ f) := begin unfold uniform_continuous₂, rw function.uncurry_comp₂, exact hf.comp hg end lemma uniform_embedding.comp {f : α → β} (hf : uniform_embedding f) {g : β → γ} (hg : uniform_embedding g) : uniform_embedding (g ∘ f) := ⟨function.injective_comp hg.1 hf.1, by rw [show (λ (x : α × α), ((g ∘ f) x.1, (g ∘ f) x.2)) = (λ y : β × β, (g y.1, g y.2)) ∘ (λ x : α × α, (f x.1, f x.2)), by ext ; simp, ← filter.comap_comap_comp, hg.2, hf.2]⟩ end
effe4626b0c2d0e911cd8065cbee70fadd634d03
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/nat/prime_auto.lean
0b0e032890073ed47d95010da2241e7c8222b885
[]
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
14,573
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.nat.sqrt import Mathlib.data.nat.gcd import Mathlib.algebra.group_power.default import Mathlib.tactic.wlog import Mathlib.tactic.norm_num import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Prime numbers This file deals with prime numbers: natural numbers `p ≥ 2` whose only divisors are `p` and `1`. ## Important declarations All the following declarations exist in the namespace `nat`. - `prime`: the predicate that expresses that a natural number `p` is prime - `primes`: the subtype of natural numbers that are prime - `min_fac n`: the minimal prime factor of a natural number `n ≠ 1` - `exists_infinite_primes`: Euclid's theorem that there exist infinitely many prime numbers - `factors n`: the prime factorization of `n` - `factors_unique`: uniqueness of the prime factorisation -/ namespace nat /-- `prime p` means that `p` is a prime number, that is, a natural number at least 2 whose only divisors are `p` and `1`. -/ def prime (p : ℕ) := bit0 1 ≤ p ∧ ∀ (m : ℕ), m ∣ p → m = 1 ∨ m = p theorem prime.two_le {p : ℕ} : prime p → bit0 1 ≤ p := and.left theorem prime.one_lt {p : ℕ} : prime p → 1 < p := prime.two_le protected instance prime.one_lt' (p : ℕ) [hp : fact (prime p)] : fact (1 < p) := prime.one_lt hp theorem prime.ne_one {p : ℕ} (hp : prime p) : p ≠ 1 := ne.symm (ne_of_lt (prime.one_lt hp)) theorem prime_def_lt {p : ℕ} : prime p ↔ bit0 1 ≤ p ∧ ∀ (m : ℕ), m < p → m ∣ p → m = 1 := sorry theorem prime_def_lt' {p : ℕ} : prime p ↔ bit0 1 ≤ p ∧ ∀ (m : ℕ), bit0 1 ≤ m → m < p → ¬m ∣ p := sorry theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ bit0 1 ≤ p ∧ ∀ (m : ℕ), bit0 1 ≤ m → m ≤ sqrt p → ¬m ∣ p := sorry /-- This instance is slower than the instance `decidable_prime` defined below, but has the advantage that it works in the kernel. If you need to prove that a particular number is prime, in any case you should not use `dec_trivial`, but rather `by norm_num`, which is much faster. -/ def decidable_prime_1 (p : ℕ) : Decidable (prime p) := decidable_of_iff' (bit0 1 ≤ p ∧ ∀ (m : ℕ), bit0 1 ≤ m → m < p → ¬m ∣ p) prime_def_lt' theorem prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 := id fun (ᾰ : n = 0) => Eq._oldrec (fun (h : prime 0) => of_as_true trivial h) (Eq.symm ᾰ) h theorem prime.pos {p : ℕ} (pp : prime p) : 0 < p := lt_of_succ_lt (prime.one_lt pp) theorem not_prime_zero : ¬prime 0 := of_as_true trivial theorem not_prime_one : ¬prime 1 := of_as_true trivial theorem prime_two : prime (bit0 1) := of_as_true trivial theorem prime_three : prime (bit1 1) := of_as_true trivial theorem prime.pred_pos {p : ℕ} (pp : prime p) : 0 < Nat.pred p := iff.mpr lt_pred_iff (prime.one_lt pp) theorem succ_pred_prime {p : ℕ} (pp : prime p) : Nat.succ (Nat.pred p) = p := succ_pred_eq_of_pos (prime.pos pp) theorem dvd_prime {p : ℕ} {m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p := sorry theorem dvd_prime_two_le {p : ℕ} {m : ℕ} (pp : prime p) (H : bit0 1 ≤ m) : m ∣ p ↔ m = p := iff.trans (dvd_prime pp) (or_iff_right_of_imp (not.elim (ne_of_gt H))) theorem prime_dvd_prime_iff_eq {p : ℕ} {q : ℕ} (pp : prime p) (qp : prime q) : p ∣ q ↔ p = q := dvd_prime_two_le qp (prime.two_le pp) theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬p ∣ 1 := fun (ᾰ : p ∣ 1) => idRhs False (not_le_of_gt (prime.one_lt pp) (le_of_dvd (of_as_true trivial) ᾰ)) theorem not_prime_mul {a : ℕ} {b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬prime (a * b) := sorry theorem not_prime_mul' {a : ℕ} {b : ℕ} {n : ℕ} (h : a * b = n) (h₁ : 1 < a) (h₂ : 1 < b) : ¬prime n := eq.mpr (id (Eq._oldrec (Eq.refl (¬prime n)) (Eq.symm h))) (not_prime_mul h₁ h₂) def min_fac_aux (n : ℕ) : ℕ → ℕ := sorry def min_fac : ℕ → ℕ := sorry @[simp] theorem min_fac_zero : min_fac 0 = bit0 1 := rfl @[simp] theorem min_fac_one : min_fac 1 = 1 := rfl theorem min_fac_eq (n : ℕ) : min_fac n = ite (bit0 1 ∣ n) (bit0 1) (min_fac_aux n (bit1 1)) := sorry theorem min_fac_aux_has_prop {n : ℕ} (n2 : bit0 1 ≤ n) (nd2 : ¬bit0 1 ∣ n) (k : ℕ) (i : ℕ) : k = bit0 1 * i + bit1 1 → (∀ (m : ℕ), bit0 1 ≤ m → m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k) := sorry theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) : min_fac_prop n (min_fac n) := sorry theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n := dite (n = 1) (fun (n1 : n = 1) => Eq.symm n1 ▸ of_as_true trivial) fun (n1 : ¬n = 1) => and.left (and.right (min_fac_has_prop n1)) theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) := sorry theorem min_fac_le_of_dvd {n : ℕ} {m : ℕ} : bit0 1 ≤ m → m ∣ n → min_fac n ≤ m := dite (n = 1) (fun (n1 : n = 1) (m : ℕ) (m2 : bit0 1 ≤ m) (d : m ∣ n) => Eq.symm n1 ▸ le_trans (of_as_true trivial) m2) fun (n1 : ¬n = 1) => and.right (and.right (min_fac_has_prop n1)) theorem min_fac_pos (n : ℕ) : 0 < min_fac n := dite (n = 1) (fun (n1 : n = 1) => Eq.symm n1 ▸ of_as_true trivial) fun (n1 : ¬n = 1) => prime.pos (min_fac_prime n1) theorem min_fac_le {n : ℕ} (H : 0 < n) : min_fac n ≤ n := le_of_dvd H (min_fac_dvd n) theorem prime_def_min_fac {p : ℕ} : prime p ↔ bit0 1 ≤ p ∧ min_fac p = p := sorry protected instance decidable_prime (p : ℕ) : Decidable (prime p) := decidable_of_iff' (bit0 1 ≤ p ∧ min_fac p = p) prime_def_min_fac theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : bit0 1 ≤ n) : ¬prime n ↔ min_fac n < n := iff.trans (not_congr (iff.trans prime_def_min_fac (and_iff_right n2))) (iff.symm (iff.trans lt_iff_le_and_ne (and_iff_right (min_fac_le (le_of_succ_le n2))))) theorem min_fac_le_div {n : ℕ} (pos : 0 < n) (np : ¬prime n) : min_fac n ≤ n / min_fac n := sorry theorem min_fac_sq_le_self {n : ℕ} (w : 0 < n) (h : ¬prime n) : min_fac n ^ bit0 1 ≤ n := sorry @[simp] theorem min_fac_eq_one_iff {n : ℕ} : min_fac n = 1 ↔ n = 1 := sorry @[simp] theorem min_fac_eq_two_iff (n : ℕ) : min_fac n = bit0 1 ↔ bit0 1 ∣ n := sorry theorem exists_dvd_of_not_prime {n : ℕ} (n2 : bit0 1 ≤ n) (np : ¬prime n) : ∃ (m : ℕ), m ∣ n ∧ m ≠ 1 ∧ m ≠ n := sorry theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : bit0 1 ≤ n) (np : ¬prime n) : ∃ (m : ℕ), m ∣ n ∧ bit0 1 ≤ m ∧ m < n := Exists.intro (min_fac n) { left := min_fac_dvd n, right := { left := prime.two_le (min_fac_prime (ne_of_gt n2)), right := iff.mp (not_prime_iff_min_fac_lt n2) np } } theorem exists_prime_and_dvd {n : ℕ} (n2 : bit0 1 ≤ n) : ∃ (p : ℕ), prime p ∧ p ∣ n := Exists.intro (min_fac n) { left := min_fac_prime (ne_of_gt n2), right := min_fac_dvd n } /-- Euclid's theorem. There exist infinitely many prime numbers. Here given in the form: for every `n`, there exists a prime number `p ≥ n`. -/ theorem exists_infinite_primes (n : ℕ) : ∃ (p : ℕ), n ≤ p ∧ prime p := sorry theorem prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = bit0 1 ∨ p % bit0 1 = 1 := sorry theorem coprime_of_dvd {m : ℕ} {n : ℕ} (H : ∀ (k : ℕ), prime k → k ∣ m → ¬k ∣ n) : coprime m n := sorry theorem coprime_of_dvd' {m : ℕ} {n : ℕ} (H : ∀ (k : ℕ), prime k → k ∣ m → k ∣ n → k ∣ 1) : coprime m n := coprime_of_dvd fun (k : ℕ) (kp : prime k) (km : k ∣ m) (kn : k ∣ n) => not_le_of_gt (prime.one_lt kp) (le_of_dvd zero_lt_one (H k kp km kn)) theorem factors_lemma {k : ℕ} : (k + bit0 1) / min_fac (k + bit0 1) < k + bit0 1 := div_lt_self (of_as_true trivial) (prime.one_lt (min_fac_prime (of_as_true trivial))) /-- `factors n` is the prime factorization of `n`, listed in increasing order. -/ def factors : ℕ → List ℕ := sorry theorem mem_factors {n : ℕ} {p : ℕ} : p ∈ factors n → prime p := sorry theorem prod_factors {n : ℕ} : 0 < n → list.prod (factors n) = n := sorry theorem factors_prime {p : ℕ} (hp : prime p) : factors p = [p] := sorry /-- `factors` can be constructed inductively by extracting `min_fac`, for sufficiently large `n`. -/ theorem factors_add_two (n : ℕ) : factors (n + bit0 1) = min_fac (n + bit0 1) :: factors ((n + bit0 1) / min_fac (n + bit0 1)) := rfl theorem prime.coprime_iff_not_dvd {p : ℕ} {n : ℕ} (pp : prime p) : coprime p n ↔ ¬p ∣ n := sorry theorem prime.dvd_iff_not_coprime {p : ℕ} {n : ℕ} (pp : prime p) : p ∣ n ↔ ¬coprime p n := iff.mpr iff_not_comm (prime.coprime_iff_not_dvd pp) theorem prime.not_coprime_iff_dvd {m : ℕ} {n : ℕ} : ¬coprime m n ↔ ∃ (p : ℕ), prime p ∧ p ∣ m ∧ p ∣ n := sorry theorem prime.dvd_mul {p : ℕ} {m : ℕ} {n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n := sorry theorem prime.not_dvd_mul {p : ℕ} {m : ℕ} {n : ℕ} (pp : prime p) (Hm : ¬p ∣ m) (Hn : ¬p ∣ n) : ¬p ∣ m * n := sorry theorem prime.dvd_of_dvd_pow {p : ℕ} {m : ℕ} {n : ℕ} (pp : prime p) (h : p ∣ m ^ n) : p ∣ m := Nat.rec (fun (h : p ∣ m ^ 0) => not.elim (prime.not_dvd_one pp) h) (fun (n : ℕ) (IH : p ∣ m ^ n → p ∣ m) (h : p ∣ m ^ Nat.succ n) => or.elim (iff.mp (prime.dvd_mul pp) h) id IH) n h theorem prime.pow_not_prime {x : ℕ} {n : ℕ} (hn : bit0 1 ≤ n) : ¬prime (x ^ n) := sorry theorem prime.mul_eq_prime_pow_two_iff {x : ℕ} {y : ℕ} {p : ℕ} (hp : prime p) (hx : x ≠ 1) (hy : y ≠ 1) : x * y = p ^ bit0 1 ↔ x = p ∧ y = p := sorry theorem prime.dvd_factorial {n : ℕ} {p : ℕ} (hp : prime p) : p ∣ factorial n ↔ p ≤ n := sorry theorem prime.coprime_pow_of_not_dvd {p : ℕ} {m : ℕ} {a : ℕ} (pp : prime p) (h : ¬p ∣ a) : coprime a (p ^ m) := coprime.pow_right m (coprime.symm (iff.mpr (prime.coprime_iff_not_dvd pp) h)) theorem coprime_primes {p : ℕ} {q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q := iff.trans (prime.coprime_iff_not_dvd pp) (not_congr (dvd_prime_two_le pq (prime.two_le pp))) theorem coprime_pow_primes {p : ℕ} {q : ℕ} (n : ℕ) (m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) : coprime (p ^ n) (q ^ m) := coprime.pow n m (iff.mpr (coprime_primes pp pq) h) theorem coprime_or_dvd_of_prime {p : ℕ} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i := eq.mpr (id (Eq._oldrec (Eq.refl (coprime p i ∨ p ∣ i)) (propext (prime.dvd_iff_not_coprime pp)))) (em (coprime p i)) theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m : ℕ} {i : ℕ} : i ∣ p ^ m ↔ ∃ (k : ℕ), ∃ (H : k ≤ m), i = p ^ k := sorry /-- If `p` is prime, and `a` doesn't divide `p^k`, but `a` does divide `p^(k+1)` then `a = p^(k+1)`. -/ theorem eq_prime_pow_of_dvd_least_prime_pow {a : ℕ} {p : ℕ} {k : ℕ} (pp : prime p) (h₁ : ¬a ∣ p ^ k) (h₂ : a ∣ p ^ (k + 1)) : a = p ^ (k + 1) := sorry theorem mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) {l : List ℕ} : (∀ (p : ℕ), p ∈ l → prime p) → p ∣ list.prod l → p ∈ l := sorry theorem mem_factors_iff_dvd {n : ℕ} {p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n := { mp := fun (h : p ∈ factors n) => prod_factors hn ▸ list.dvd_prod h, mpr := fun (h : p ∣ n) => mem_list_primes_of_dvd_prod hp mem_factors (Eq.symm (prod_factors hn) ▸ h) } theorem perm_of_prod_eq_prod {l₁ : List ℕ} {l₂ : List ℕ} : list.prod l₁ = list.prod l₂ → (∀ (p : ℕ), p ∈ l₁ → prime p) → (∀ (p : ℕ), p ∈ l₂ → prime p) → l₁ ~ l₂ := sorry theorem factors_unique {n : ℕ} {l : List ℕ} (h₁ : list.prod l = n) (h₂ : ∀ (p : ℕ), p ∈ l → prime p) : l ~ factors n := sorry theorem succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m : ℕ} {n : ℕ} {k : ℕ} {l : ℕ} (hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k + l + 1) ∣ m * n) : p ^ (k + 1) ∣ m ∨ p ^ (l + 1) ∣ n := sorry /-- The type of prime numbers -/ def primes := Subtype fun (p : ℕ) => prime p namespace primes protected instance has_repr : has_repr primes := has_repr.mk fun (p : primes) => repr (subtype.val p) protected instance inhabited : Inhabited primes := { default := { val := bit0 1, property := prime_two } } protected instance coe_nat : has_coe primes ℕ := has_coe.mk subtype.val theorem coe_nat_inj (p : primes) (q : primes) : ↑p = ↑q → p = q := fun (h : ↑p = ↑q) => subtype.eq h end primes protected instance monoid.prime_pow {α : Type u_1} [monoid α] : has_pow α primes := has_pow.mk fun (x : α) (p : primes) => x ^ subtype.val p end nat /-! ### Primality prover -/ namespace tactic namespace norm_num theorem is_prime_helper (n : ℕ) (h₁ : 1 < n) (h₂ : nat.min_fac n = n) : nat.prime n := iff.mpr nat.prime_def_min_fac { left := h₁, right := h₂ } theorem min_fac_bit0 (n : ℕ) : nat.min_fac (bit0 n) = bit0 1 := sorry /-- A predicate representing partial progress in a proof of `min_fac`. -/ def min_fac_helper (n : ℕ) (k : ℕ) := 0 < k ∧ bit1 k ≤ nat.min_fac (bit1 n) theorem min_fac_helper.n_pos {n : ℕ} {k : ℕ} (h : min_fac_helper n k) : 0 < n := sorry theorem min_fac_ne_bit0 {n : ℕ} {k : ℕ} : nat.min_fac (bit1 n) ≠ bit0 k := sorry theorem min_fac_helper_0 (n : ℕ) (h : 0 < n) : min_fac_helper n 1 := sorry theorem min_fac_helper_1 {n : ℕ} {k : ℕ} {k' : ℕ} (e : k + 1 = k') (np : nat.min_fac (bit1 n) ≠ bit1 k) (h : min_fac_helper n k) : min_fac_helper n k' := sorry theorem min_fac_helper_2 (n : ℕ) (k : ℕ) (k' : ℕ) (e : k + 1 = k') (np : ¬nat.prime (bit1 k)) (h : min_fac_helper n k) : min_fac_helper n k' := sorry theorem min_fac_helper_3 (n : ℕ) (k : ℕ) (k' : ℕ) (c : ℕ) (e : k + 1 = k') (nc : bit1 n % bit1 k = c) (c0 : 0 < c) (h : min_fac_helper n k) : min_fac_helper n k' := sorry theorem min_fac_helper_4 (n : ℕ) (k : ℕ) (hd : bit1 n % bit1 k = 0) (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 k := sorry theorem min_fac_helper_5 (n : ℕ) (k : ℕ) (k' : ℕ) (e : bit1 k * bit1 k = k') (hd : bit1 n < k') (h : min_fac_helper n k) : nat.min_fac (bit1 n) = bit1 n := sorry end Mathlib
f9fbad1fa5f75482fd5042e04fd171fe4e11fed7
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Lean/Elab/Term.lean
ebc821da7b31dc034a2683e3367c8582900e11a6
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
54,854
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Lean.Util.Sorry import Init.Lean.Structure import Init.Lean.Meta.ExprDefEq import Init.Lean.Meta.AppBuilder import Init.Lean.Meta.SynthInstance import Init.Lean.Meta.Tactic.Util import Init.Lean.Hygiene import Init.Lean.Util.RecDepth import Init.Lean.Elab.Log import Init.Lean.Elab.Alias import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Level namespace Lean namespace Elab namespace Term structure Context extends Meta.Context := (fileName : String) (fileMap : FileMap) (cmdPos : String.Pos) (currNamespace : Name) (declName? : Option Name := none) (levelNames : List Name := []) (openDecls : List OpenDecl := []) (macroStack : MacroStack := []) (currMacroScope : MacroScope := firstFrontendMacroScope) /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ (mayPostpone : Bool := true) (errToSorry : Bool := true) /- If `macroStackAtErr == true`, we include it in error messages. -/ (macroStackAtErr : Bool := true) /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind -- typeclass instance search | typeClass -- Similar to typeClass, but error messages are different, -- we use "type mismatch" or "application type mismatch" (when `f?` is some) instead of "failed to synthesize" | coe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (macroStack : MacroStack) -- type defaulting (currently: defaulting numeric literals to `Nat`) | withDefault (defaultVal : Expr) structure SyntheticMVarDecl := (mvarId : MVarId) (ref : Syntax) (kind : SyntheticMVarKind) structure State extends Meta.State := (syntheticMVars : List SyntheticMVarDecl := []) (messages : MessageLog := {}) (instImplicitIdx : Nat := 1) (anonymousIdx : Nat := 1) (nextMacroScope : Nat := firstFrontendMacroScope + 1) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _ }⟩ /- The Term elaborator monad has a special kind of exception `Exception.postpone` which is used by an elaboration function to notify the main driver that it should be tried later. Remark: `Exception.postpone` is used only when `mayPostpone == true` in the `Context`. -/ inductive Exception | ex : Elab.Exception → Exception | postpone : Exception instance Exception.inhabited : Inhabited Exception := ⟨Exception.postpone⟩ instance Exception.hasToString : HasToString Exception := ⟨fun ex => match ex with | Exception.postpone => "postponed" | Exception.ex ex => toString ex⟩ /- Term elaborator Monad. In principle, we could track statically which methods may postpone or not by having adding a Boolean parameter `mayPostpone` to `TermElabM`. This would be useful to ensure that `Exception.postpone` does not leak to `CommandElabM`, but we abandoned this design because it adds unnecessary complexity. -/ abbrev TermElabM := ReaderT Context (EStateM Exception State) abbrev TermElab := Syntax → Option Expr → TermElabM Expr instance TermElabM.inhabited {α} : Inhabited (TermElabM α) := ⟨throw $ Exception.postpone⟩ abbrev TermElabResult := EStateM.Result Message State Expr instance TermElabResult.inhabited : Inhabited TermElabResult := ⟨EStateM.Result.ok (arbitrary _) (arbitrary _)⟩ /-- Execute `x`, save resulting expression and new state. If `x` fails, then it also stores exception and new state. Remark: we do not capture `Exception.postpone`. -/ @[inline] def observing (x : TermElabM Expr) : TermElabM TermElabResult := fun ctx s => match x ctx s with | EStateM.Result.error (Exception.ex (Elab.Exception.error errMsg)) newS => EStateM.Result.ok (EStateM.Result.error errMsg newS) s | EStateM.Result.error Exception.postpone _ => EStateM.Result.error Exception.postpone s | EStateM.Result.error ex newS => EStateM.Result.error ex newS | EStateM.Result.ok e newS => EStateM.Result.ok (EStateM.Result.ok e newS) s /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult) : TermElabM Expr := match result with | EStateM.Result.ok e s => do set s; pure e | EStateM.Result.error errMsg s => do set s; throw (Exception.ex (Elab.Exception.error errMsg)) def getEnv : TermElabM Environment := do s ← get; pure s.env def getMCtx : TermElabM MetavarContext := do s ← get; pure s.mctx def getLCtx : TermElabM LocalContext := do ctx ← read; pure ctx.lctx def getLocalInsts : TermElabM LocalInstances := do ctx ← read; pure ctx.localInstances def getOptions : TermElabM Options := do ctx ← read; pure ctx.config.opts def setEnv (env : Environment) : TermElabM Unit := modify $ fun s => { env := env, .. s } def setMCtx (mctx : MetavarContext) : TermElabM Unit := modify $ fun s => { mctx := mctx, .. s } def addContext (msg : MessageData) : TermElabM MessageData := do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; pure (MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msg) instance monadLog : MonadLog TermElabM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } /-- Throws an error with the given `msgData` and extracting position information from `ref`. If `ref` does not contain position information, then use `cmdPos` -/ def throwError {α} (ref : Syntax) (msgData : MessageData) : TermElabM α := do ctx ← read; let ref := getBetterRef ref ctx.macroStack; let msgData := if ctx.macroStackAtErr then addMacroStack msgData ctx.macroStack else msgData; msg ← mkMessage msgData MessageSeverity.error ref; throw (Exception.ex (Elab.Exception.error msg)) def throwUnsupportedSyntax {α} : TermElabM α := throw (Exception.ex Elab.Exception.unsupportedSyntax) @[inline] def withIncRecDepth {α} (ref : Syntax) (x : TermElabM α) : TermElabM α := do ctx ← read; when (ctx.currRecDepth == ctx.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x protected def getCurrMacroScope : TermElabM MacroScope := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : TermElabM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : TermElabM α) : TermElabM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance monadQuotation : MonadQuotation TermElabM := { getCurrMacroScope := Term.getCurrMacroScope, getMainModule := Term.getMainModule, withFreshMacroScope := @Term.withFreshMacroScope } abbrev TermElabTable := ElabFnTable TermElab def mkBuiltinTermElabTable : IO (IO.Ref TermElabTable) := IO.mkRef {} @[init mkBuiltinTermElabTable] constant builtinTermElabTable : IO.Ref TermElabTable := arbitrary _ def addBuiltinTermElab (k : SyntaxNodeKind) (declName : Name) (elab : TermElab) : IO Unit := do m ← builtinTermElabTable.get; when (m.contains k) $ throw (IO.userError ("invalid builtin term elaborator, elaborator for '" ++ toString k ++ "' has already been defined")); builtinTermElabTable.modify $ fun m => m.insert k elab def declareBuiltinTermElab (env : Environment) (kind : SyntaxNodeKind) (declName : Name) : IO Environment := let name := `_regBuiltinTermElab ++ declName; let type := mkApp (mkConst `IO) (mkConst `Unit); let val := mkAppN (mkConst `Lean.Elab.Term.addBuiltinTermElab) #[toExpr kind, toExpr declName, mkConst declName]; let decl := Declaration.defnDecl { name := name, lparams := [], type := type, value := val, hints := ReducibilityHints.opaque, isUnsafe := false }; match env.addAndCompile {} decl with -- TODO: pretty print error | Except.error _ => throw (IO.userError ("failed to emit registration code for builtin term elaborator '" ++ toString declName ++ "'")) | Except.ok env => IO.ofExcept (setInitAttr env name) @[init] def registerBuiltinTermElabAttr : IO Unit := registerBuiltinAttribute { name := `builtinTermElab, descr := "Builtin term elaborator", add := fun env declName arg persistent => do { unless persistent $ throw (IO.userError ("invalid attribute 'builtinTermElab', must be persistent")); kind ← IO.ofExcept $ syntaxNodeKindOfAttrParam env `Lean.Parser.Term arg; match env.find? declName with | none => throw $ IO.userError "unknown declaration" | some decl => match decl.type with | Expr.const `Lean.Elab.Term.TermElab _ _ => declareBuiltinTermElab env kind declName | _ => throw (IO.userError ("unexpected term elaborator type at '" ++ toString declName ++ "' `TermElab` expected")) }, applicationTime := AttributeApplicationTime.afterCompilation } abbrev TermElabAttribute := ElabAttribute TermElab def mkTermElabAttribute : IO TermElabAttribute := mkElabAttribute TermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" builtinTermElabTable @[init mkTermElabAttribute] constant termElabAttribute : TermElabAttribute := arbitrary _ /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal | fieldIdx (i : Nat) | fieldName (name : String) | getOp (idx : Syntax) instance LVal.hasToString : HasToString LVal := ⟨fun p => match p with | LVal.fieldIdx i => toString i | LVal.fieldName n => n | LVal.getOp idx => "[" ++ toString idx ++ "]"⟩ def getDeclName? : TermElabM (Option Name) := do ctx ← read; pure ctx.declName? def getCurrNamespace : TermElabM Name := do ctx ← read; pure ctx.currNamespace def getOpenDecls : TermElabM (List OpenDecl) := do ctx ← read; pure ctx.openDecls def getTraceState : TermElabM TraceState := do s ← get; pure s.traceState def setTraceState (traceState : TraceState) : TermElabM Unit := modify $ fun s => { traceState := traceState, .. s } def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := do mctx ← getMCtx; pure $ mctx.isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := do mctx ← getMCtx; pure $ mctx.getDecl mvarId def assignExprMVar (mvarId : MVarId) (val : Expr) : TermElabM Unit := modify $ fun s => { mctx := s.mctx.assignExpr mvarId val, .. s } def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : TermElabM Unit := do ctx ← read; s ← get; logInfo ref $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } $ MessageData.tagged cls msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : TermElabM Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls ref (msg ()) @[inline] def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := trace cls Syntax.missing msg def dbgTrace {α} [HasToString α] (a : α) : TermElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () /-- Auxiliary function for `liftMetaM` -/ private def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) /-- Auxiliary function for `liftMetaM` -/ private def fromMetaException (ctx : Context) (ref : Syntax) (ex : Meta.Exception) : Exception := Exception.ex $ Elab.Exception.error $ mkMessageAux ctx ref ex.toMessageData MessageSeverity.error /-- Auxiliary function for `liftMetaM` -/ private def fromMetaState (ref : Syntax) (ctx : Context) (s : State) (newS : Meta.State) (oldTraceState : TraceState) : State := let traces := newS.traceState.traces; let messages := traces.foldl (fun (messages : MessageLog) trace => messages.add (mkMessageAux ctx ref trace MessageSeverity.information)) s.messages; { toState := { traceState := oldTraceState, .. newS }, messages := messages, .. s } @[inline] def liftMetaM {α} (ref : Syntax) (x : MetaM α) : TermElabM α := fun ctx s => let oldTraceState := s.traceState; match x ctx.toContext { traceState := {}, .. s.toState } with | EStateM.Result.ok a newS => EStateM.Result.ok a (fromMetaState ref ctx s newS oldTraceState) | EStateM.Result.error ex newS => EStateM.Result.error (fromMetaException ctx ref ex) (fromMetaState ref ctx s newS oldTraceState) def ppGoal (ref : Syntax) (mvarId : MVarId) : TermElabM Format := liftMetaM ref $ Meta.ppGoal mvarId def isType (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isType e def isTypeFormer (ref : Syntax) (e : Expr) : TermElabM Bool := liftMetaM ref $ Meta.isTypeFormer e def isDefEqNoConstantApprox (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.approxDefEq $ Meta.isDefEq t s def isDefEq (ref : Syntax) (t s : Expr) : TermElabM Bool := liftMetaM ref $ Meta.fullApproxDefEq $ Meta.isDefEq t s def inferType (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.inferType e def whnf (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnf e def whnfForall (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfForall e def whnfCore (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.whnfCore e def unfoldDefinition? (ref : Syntax) (e : Expr) : TermElabM (Option Expr) := liftMetaM ref $ Meta.unfoldDefinition? e def instantiateMVars (ref : Syntax) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.instantiateMVars e def isClass (ref : Syntax) (t : Expr) : TermElabM (Option Name) := liftMetaM ref $ Meta.isClass t def mkFreshLevelMVar (ref : Syntax) : TermElabM Level := liftMetaM ref $ Meta.mkFreshLevelMVar def mkFreshExprMVar (ref : Syntax) (type? : Option Expr := none) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := match type? with | some type => liftMetaM ref $ Meta.mkFreshExprMVar type userName? kind | none => liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; type ← Meta.mkFreshExprMVar (mkSort u); Meta.mkFreshExprMVar type userName? kind def mkFreshTypeMVar (ref : Syntax) (kind : MetavarKind := MetavarKind.natural) (userName? : Name := Name.anonymous) : TermElabM Expr := liftMetaM ref $ do u ← Meta.mkFreshLevelMVar; Meta.mkFreshExprMVar (mkSort u) userName? kind def getLevel (ref : Syntax) (type : Expr) : TermElabM Level := liftMetaM ref $ Meta.getLevel type def mkForall (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkForall xs e def mkForallUsedOnly (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM (Expr × Nat) := liftMetaM ref $ Meta.mkForallUsedOnly xs e def mkLambda (ref : Syntax) (xs : Array Expr) (e : Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkLambda xs e def mkLet (ref : Syntax) (x : Expr) (e : Expr) : TermElabM Expr := mkLambda ref #[x] e def trySynthInstance (ref : Syntax) (type : Expr) : TermElabM (LOption Expr) := liftMetaM ref $ Meta.trySynthInstance type def mkAppM (ref : Syntax) (constName : Name) (args : Array Expr) : TermElabM Expr := liftMetaM ref $ Meta.mkAppM constName args def decLevel? (ref : Syntax) (u : Level) : TermElabM (Option Level) := liftMetaM ref $ Meta.decLevel? u def decLevel (ref : Syntax) (u : Level) : TermElabM Level := do u? ← decLevel? ref u; match u? with | some u => pure u | none => throwError ref ("invalid universe level, " ++ u ++ " is not greater than 0") /- This function is useful for inferring universe level parameters for function that take arguments such as `{α : Type u}`. Recall that `Type u` is `Sort (u+1)` in Lean. Thus, given `α`, we must infer its universe level, and then decrement 1 to obtain `u`. -/ def getDecLevel (ref : Syntax) (type : Expr) : TermElabM Level := do u ← getLevel ref type; decLevel ref u @[inline] def savingMCtx {α} (x : TermElabM α) : TermElabM α := do mctx ← getMCtx; finally x (modify $ fun s => { mctx := mctx, .. s }) def liftLevelM {α} (x : LevelElabM α) : TermElabM α := fun ctx s => match (x { .. ctx }).run { .. s } with | EStateM.Result.ok a newS => EStateM.Result.ok a { mctx := newS.mctx, ngen := newS.ngen, .. s } | EStateM.Result.error ex newS => EStateM.Result.error (Exception.ex ex) s def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx @[inline] def withConfig {α} (f : Meta.Config → Meta.Config) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { config := f ctx.config, .. ctx }) x @[inline] def withTransparency {α} (mode : Meta.TransparencyMode) (x : TermElabM α) : TermElabM α := withConfig (fun config => { transparency := mode, .. config }) x @[inline] def withReducible {α} (x : TermElabM α) : TermElabM α := withTransparency Meta.TransparencyMode.reducible x /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (ref : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := modify $ fun s => { syntheticMVars := { mvarId := mvarId, ref := ref, kind := kind } :: s.syntheticMVars, .. s } /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ @[inline] def withoutPostponing {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { mayPostpone := false, .. ctx }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode `Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. -/ def levelMVarToParam (e : Expr) : TermElabM Expr := do ctx ← read; mctx ← getMCtx; let r := mctx.levelMVarToParam (fun n => ctx.levelNames.elem n) e; modify $ fun s => { mctx := r.mctx, .. s }; pure r.expr /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshAnonymousName : TermElabM Name := do s ← get; let anonymousIdx := s.anonymousIdx; modify $ fun s => { anonymousIdx := s.anonymousIdx + 1, .. s}; pure $ (`_a).appendIndexAfter anonymousIdx /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshAnonymousName`. -/ def mkFreshAnonymousIdent (ref : Syntax) : TermElabM Syntax := do n ← mkFreshAnonymousName; pure $ mkIdentFrom ref n /-- Auxiliary method for creating binder names for local instances. Users expect them to be named as `_inst_<idx>`. -/ def mkFreshInstanceName : TermElabM Name := do s ← get; let instIdx := s.instImplicitIdx; modify $ fun s => { instImplicitIdx := s.instImplicitIdx + 1, .. s}; pure $ (`_inst).appendIndexAfter instIdx private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Auxiliary function for expandind the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ private partial def expandCDot : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope $ do id ← `(a); modify $ fun s => s.push id; pure id else do args ← args.mapM expandCDot; pure $ Syntax.node k args | stx => pure stx /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := if hasCDot stx then do (newStx, binders) ← (expandCDot stx).run #[]; `(fun $binders* => $newStx) else pure none def mkFreshFVarId : TermElabM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { ngen := s.ngen.next, .. s }; pure id def withLocalDecl {α} (ref : Syntax) (n : Name) (binderInfo : BinderInfo) (type : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLocalDecl fvarId n type binderInfo; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar }, .. ctx }) $ k fvar | none => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ k fvar def withLetDecl {α} (ref : Syntax) (n : Name) (type : Expr) (val : Expr) (k : Expr → TermElabM α) : TermElabM α := do fvarId ← mkFreshFVarId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let localInsts := ctx.localInstances; let fvar := mkFVar fvarId; c? ← isClass ref type; match c? with | some c => adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts.push { className := c, fvar := fvar }, .. ctx }) $ k fvar | none => adaptReader (fun (ctx : Context) => { lctx := lctx, .. ctx }) $ k fvar def throwTypeMismatchError {α} (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; match f? with | none => let msg : MessageData := "type mismatch" ++ indentExpr e ++ Format.line ++ "has type" ++ indentExpr eType ++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType ++ extraMsg; throwError ref msg | some f => do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; throwError ref $ Meta.Exception.mkAppTypeMismatchMessage f e { env := env, mctx := mctx, lctx := lctx, opts := opts } ++ extraMsg @[inline] def withoutMacroStackAtErr {α} (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { macroStackAtErr := false, .. ctx }) x /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (ref : Syntax) (instMVar : MVarId) : TermElabM Bool := do instMVarDecl ← getMVarDecl instMVar; let type := instMVarDecl.type; type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => do condM (isExprMVarAssigned instMVar) (do oldVal ← instantiateMVars ref (mkMVar instMVar); unlessM (isDefEq ref oldVal val) $ throwError ref $ "synthesized type class instance is not definitionally equal to expression " ++ "inferred by typing rules, synthesized" ++ indentExpr val ++ Format.line ++ "inferred" ++ indentExpr oldVal) (assignExprMVar instMVar val); pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ def tryCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := condM (isDefEq ref expectedType eType) (pure e) $ do u ← getLevel ref eType; v ← getLevel ref expectedType; let coeTInstType := mkAppN (mkConst `CoeT [u, v]) #[eType, e, expectedType]; mvar ← mkFreshExprMVar ref coeTInstType MetavarKind.synthetic; let eNew := mkAppN (mkConst `coe [u, v]) #[eType, expectedType, e, mvar]; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ do unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId (SyntheticMVarKind.coe expectedType eType e f?); pure eNew) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwTypeMismatchError ref expectedType eType e f? errMsg.data | _ => throwTypeMismatchError ref expectedType eType e f?) private def isTypeApp? (ref : Syntax) (type : Expr) : TermElabM (Option (Expr × Expr)) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => pure (some (m, α)) | _ => pure none structure IsMonadResult := (m : Expr) (α : Expr) (inst : Expr) private def isMonad? (ref : Syntax) (type : Expr) : TermElabM (Option IsMonadResult) := do type ← withReducible $ whnf ref type; match type with | Expr.app m α _ => catch (do monadType ← mkAppM ref `Monad #[m]; result ← trySynthInstance ref monadType; match result with | LOption.some inst => pure (some { m := m, α := α, inst := inst }) | _ => pure none) (fun _ => pure none) | _ => pure none def synthesizeInst (ref : Syntax) (type : Expr) : TermElabM Expr := do type ← instantiateMVars ref type; result ← trySynthInstance ref type; match result with | LOption.some val => pure val | LOption.undef => throwError ref ("failed to synthesize instance" ++ indentExpr type) | LOption.none => throwError ref ("failed to synthesize instance" ++ indentExpr type) /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β` where `n` is a Monad, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β` and a given type `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we rely on `tryCoe`, and the instances ``` instance coeMethod {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] : Coe (m α) (m β) instance pureCoeDepProp {m : Type → Type v} [HasPure m] {p : Prop} [Decidable p] : CoeDep (m Prop) (pure p) (m Bool) ``` 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : HasMonadLiftT m n] {α : Type u_1}, m α → n α ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [HasMonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [HasLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[HasLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ def tryLiftAndCoe (ref : Syntax) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do some ⟨n, β, monadInst⟩ ← isMonad? ref expectedType | tryCoe ref expectedType eType e f?; some (m, α) ← isTypeApp? ref eType | tryCoe ref expectedType eType e f?; condM (isDefEq ref m n) (tryCoe ref expectedType eType e f?) $ catch (do -- Construct lift from `m` to `n` hasMonadLiftType ← mkAppM ref `HasMonadLiftT #[m, n]; hasMonadLiftVal ← synthesizeInst ref hasMonadLiftType; u_1 ← getDecLevel ref α; u_2 ← getDecLevel ref eType; u_3 ← getDecLevel ref expectedType; let eNew := mkAppN (Lean.mkConst `liftM [u_1, u_2, u_3]) #[m, n, hasMonadLiftVal, α, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 2 worked (do u ← getLevel ref α; v ← getLevel ref β; let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst `CoeT [u, v]) #[α, mkBVar 0, β]; coeTInstVal ← synthesizeInst ref coeTInstType; let eNew := mkAppN (Lean.mkConst `liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, hasMonadLiftVal, coeTInstVal, monadInst, e]; eNewType ← inferType ref eNew; condM (isDefEq ref expectedType eNewType) (pure eNew) -- approach 3 worked (throwTypeMismatchError ref expectedType eType e f?))) (fun _ => throwTypeMismatchError ref expectedType eType e f?) /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (ref : Syntax) (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) : TermElabM Expr := match expectedType? with | none => pure e | some expectedType => /- Recall that constant approximation is used to solve constraint of the form ``` ?m t =?= s ``` where `t` is an arbitrary term, by assigning `?m := fun _ => s` This approximation when not used carefully produces bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, not first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure 0; f () ``` with expected type `StateT Nat Id Nat`. In this example, the following unification contraint is generated. ``` ?m () (?n ()) =?= StateT Nat Id Nat ``` It is not a higher-order pattern, and first-order approximation fails. However, constant approximation solves it by assigning ``` ?m := fun _ => StateT Nat Id ?n := fun _ => Nat ``` Note that `f`s type is `(x : ?α) -> ?m x (?n x)`. The metavariables `?m` and `?n` may depend on `x`. The `isDefEqNoConstantApprox` fails to unify the expected and inferred types. Then, `tryLiftAndCoe` first tries the monadic extensions, and then falls back to `isDefEq` which enables all approximations. -/ condM (isDefEqNoConstantApprox ref eType expectedType) (pure e) (tryLiftAndCoe ref expectedType eType e f?) /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (ref : Syntax) (expectedType? : Option Expr) (e : Expr) : TermElabM Expr := match expectedType? with | none => pure e | _ => do eType ← inferType ref e; ensureHasTypeAux ref expectedType? eType e private def exceptionToSorry (ref : Syntax) (errMsg : Message) (expectedType? : Option Expr) : TermElabM Expr := do expectedType : Expr ← match expectedType? with | none => mkFreshTypeMVar ref | some expectedType => pure expectedType; u ← getLevel ref expectedType; -- TODO: should be `(sorryAx.{$u} $expectedType true) when we support antiquotations at that place let syntheticSorry := mkApp2 (mkConst `sorryAx [u]) expectedType (mkConst `Bool.true); unless errMsg.data.hasSyntheticSorry $ logMessage errMsg; pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do ctx ← read; when ctx.mayPostpone $ throw Exception.postpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do when e.getAppFn.isMVar $ tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace `Elab.postpone stx $ fun _ => stx ++ " : " ++ expectedType?; mvar ← mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque; ctx ← read; registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed ctx.macroStack); pure mvar /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabTermUsing (s : State) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List TermElab → TermElabM Expr | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (elabFn::elabFns) => catch (elabFn stx expectedType?) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => do ctx ← read; if ctx.errToSorry then exceptionToSorry stx errMsg expectedType? else throw ex | Exception.ex Elab.Exception.unsupportedSyntax => do set s; elabTermUsing elabFns | Exception.postpone => if catchExPostpone then do /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ set s; postponeElabTerm stx expectedType? else throw ex) instance : MonadMacroAdapter TermElabM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax} /- Main loop for `elabTerm` -/ partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone := true) : Syntax → TermElabM Expr | stx => withFreshMacroScope $ withIncRecDepth stx $ do trace `Elab.step stx $ fun _ => expectedType? ++ " " ++ stx; s ← get; stxNew? ← catch (do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => match ex with | Exception.ex Elab.Exception.unsupportedSyntax => pure none | _ => throw ex); match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabTermAux stxNew | _ => let table := (termElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabTermUsing s stx expectedType? catchExPostpone elabFns | none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented") private def isExplicit (stx : Syntax) : Bool := match_syntax stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == `Lean.Parser.Term.app && isExplicit (stx.getArg 0) /-- Return true with `expectedType` is of the form `{a : α} → β` or `[a : α] → β`, and `stx` is not `@f` nor `@f arg1 ...` -/ def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if isExplicit stx || isExplicitApp stx then pure none else match expectedType? with | some expectedType => do expectedType ← whnfForall stx expectedType; match expectedType with | Expr.forallE _ _ _ c => pure $ if c.binderInfo.isExplicit then none else some expectedType | _ => pure $ none | _ => pure $ none def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (fvars : Array Expr) : TermElabM Expr := do body ← elabTermAux expectedType catchExPostpone stx; -- body ← ensureHasType stx expectedType body; r ← mkLambda stx fvars body; trace `Elab.implicitForall stx $ fun _ => r; pure r partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) : Expr → Array Expr → TermElabM Expr | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope $ do n ← MonadQuotation.addMacroScope n; withLocalDecl stx n c.binderInfo d $ fun fvar => do type ← whnfForall stx (b.instantiate1 fvar); elabImplicitLambda type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) : TermElabM Expr := do implicit? ← useImplicitLambda? stx expectedType?; match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType #[] | none => elabTermAux expectedType? catchExPostpone stx /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do stx' ← exp stx; withMacroExpansion stx stx' $ elabTerm stx' expectedType? @[inline] def withLCtx {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : TermElabM α) : TermElabM α := adaptReader (fun (ctx : Context) => { lctx := lctx, localInstances := localInsts, .. ctx }) x def resetSynthInstanceCache : TermElabM Unit := modify $ fun s => { cache := { synthInstance := {}, .. s.cache }, .. s } @[inline] def resettingSynthInstanceCache {α} (x : TermElabM α) : TermElabM α := do s ← get; let savedSythInstance := s.cache.synthInstance; resetSynthInstanceCache; finally x (modify $ fun s => { cache := { synthInstance := savedSythInstance, .. s.cache }, .. s }) @[inline] def resettingSynthInstanceCacheWhen {α} (b : Bool) (x : TermElabM α) : TermElabM α := if b then resettingSynthInstanceCache x else x /-- Execute `x` using the given metavariable's `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ def withMVarContext {α} (mvarId : MVarId) (x : TermElabM α) : TermElabM α := do mvarDecl ← getMVarDecl mvarId; ctx ← read; let needReset := ctx.localInstances == mvarDecl.localInstances; withLCtx mvarDecl.lctx mvarDecl.localInstances $ resettingSynthInstanceCacheWhen needReset x def mkInstMVar (ref : Syntax) (type : Expr) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.synthetic; let mvarId := mvar.mvarId!; unlessM (synthesizeInstMVarCore ref mvarId) $ registerSyntheticMVar ref mvarId SyntheticMVarKind.typeClass; pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (ref : Syntax) (α : Expr) (a : Expr) : TermElabM Expr := do β ← mkFreshTypeMVar ref; u ← getLevel ref α; v ← getLevel ref β; let coeSortInstType := mkAppN (Lean.mkConst `CoeSort [u, v]) #[α, β]; mvar ← mkFreshExprMVar ref coeSortInstType MetavarKind.synthetic; let mvarId := mvar.mvarId!; catch (withoutMacroStackAtErr $ condM (synthesizeInstMVarCore ref mvarId) (pure $ mkAppN (Lean.mkConst `coeSort [u, v]) #[α, β, a, mvar]) (throwError ref "type expected")) (fun ex => match ex with | Exception.ex (Elab.Exception.error errMsg) => throwError ref ("type expected" ++ Format.line ++ errMsg.data) | _ => throwError ref "type expected") /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (ref : Syntax) (e : Expr) : TermElabM Expr := condM (isType ref e) (pure e) (do eType ← inferType ref e; u ← mkFreshLevelMVar ref; condM (isDefEq ref eType (mkSort u)) (pure e) (tryCoeSort ref eType e)) /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do u ← mkFreshLevelMVar stx; type ← elabTerm stx (mkSort u); ensureType stx type def addDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; match env.addDecl decl with | Except.ok env => setEnv env | Except.error kex => do opts ← getOptions; throwError ref (kex.toMessageData opts) def compileDecl (ref : Syntax) (decl : Declaration) : TermElabM Unit := do env ← getEnv; opts ← getOptions; match env.compileDecl opts decl with | Except.ok env => setEnv env | Except.error kex => throwError ref (kex.toMessageData opts) /- ======================================= Builtin elaboration functions ======================================= -/ @[builtinTermElab «prop»] def elabProp : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «sort»] def elabSort : TermElab := fun _ _ => pure $ mkSort levelZero @[builtinTermElab «type»] def elabTypeStx : TermElab := fun _ _ => pure $ mkSort levelOne @[builtinTermElab «hole»] def elabHole : TermElab := fun stx expectedType? => mkFreshExprMVar stx expectedType? @[builtinTermElab «namedHole»] def elabNamedHole : TermElab := fun stx expectedType? => let name := stx.getIdAt 1; mkFreshExprMVar stx expectedType? MetavarKind.syntheticOpaque name def mkTacticMVar (ref : Syntax) (type : Expr) (tacticCode : Syntax) : TermElabM Expr := do mvar ← mkFreshExprMVar ref type MetavarKind.syntheticOpaque `main; let mvarId := mvar.mvarId!; registerSyntheticMVar ref mvarId $ SyntheticMVarKind.tactic tacticCode; pure mvar @[builtinTermElab tacticBlock] def elabTacticBlock : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid tactic block, expected type has not been provided") @[builtinTermElab byTactic] def elabByTactic : TermElab := fun stx expectedType? => match expectedType? with | some expectedType => mkTacticMVar stx expectedType (stx.getArg 1) | none => throwError stx ("invalid 'by' tactic, expected type has not been provided") /-- Main loop for `mkPairs`. -/ private partial def mkPairsAux (elems : Array Syntax) : Nat → Syntax → MacroM Syntax | i, acc => if i > 0 then do let i := i - 1; let elem := elems.get! i; acc ← `(Prod.mk $elem $acc); mkPairsAux i acc else pure acc /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ def mkPairs (elems : Array Syntax) : MacroM Syntax := mkPairsAux elems (elems.size - 1) elems.back /-- Try to expand `·` notation, and if successful elaborate result. This method is used to elaborate the Lean parentheses notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ private def elabCDot (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do stx? ← liftMacroM $ expandCDot? stx; match stx? with | some stx' => withMacroExpansion stx stx' (elabTerm stx' expectedType?) | none => elabTerm stx expectedType? @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => let ref := stx; match_syntax ref with | `(()) => pure $ Lean.mkConst `Unit.unit | `(($e : $type)) => do type ← elabType type; e ← elabCDot e type; ensureHasType ref type e | `(($e)) => elabCDot e expectedType? | `(($e, $es*)) => do pairs ← liftMacroM $ mkPairs (#[e] ++ es.getEvenElems); withMacroExpansion stx pairs (elabTerm pairs expectedType?) | _ => throwError stx "unexpected parentheses notation" @[builtinTermElab «listLit»] def elabListLit : TermElab := fun stx expectedType? => do let openBkt := stx.getArg 0; let args := stx.getArg 1; let closeBkt := stx.getArg 2; let consId := mkTermIdFrom openBkt `List.cons; let nilId := mkTermIdFrom closeBkt `List.nil; let newStx := args.foldSepRevArgs (fun arg r => mkAppStx consId #[arg, r]) nilId; withMacroExpansion stx newStx $ elabTerm newStx expectedType? @[builtinTermElab «arrayLit»] def elabArrayLit : TermElab := fun stx expectedType? => do match_syntax stx with | `(#[$args*]) => do newStx ← `(List.toArray [$args*]); withMacroExpansion stx newStx (elabTerm newStx expectedType?) | _ => throwError stx "unexpected array literal syntax" private partial def resolveLocalNameAux (lctx : LocalContext) : Name → List String → Option (Expr × List String) | n, projs => match lctx.findFromUserName? n with | some decl => some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => resolveLocalNameAux pre (s::projs) | _ => none private def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do lctx ← getLCtx; pure $ resolveLocalNameAux lctx n [] /- Return true iff `stx` is a `Term.id`, and it is local variable. -/ def isLocalTermId? (stx : Syntax) (relaxed : Bool := false) : TermElabM (Option Expr) := match stx.isTermId? relaxed with | some (Syntax.ident _ _ val _, _) => do r? ← resolveLocalName val; match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none private def mkFreshLevelMVars (ref : Syntax) (num : Nat) : TermElabM (List Level) := num.foldM (fun _ us => do u ← mkFreshLevelMVar ref; pure $ u::us) [] /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (ref : Syntax) (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do env ← getEnv; match env.find? constName with | none => throwError ref ("unknown constant '" ++ constName ++ "'") | some cinfo => if explicitLevels.length > cinfo.lparams.length then throwError ref ("too many explicit universe levels") else do let numMissingLevels := cinfo.lparams.length - explicitLevels.length; us ← mkFreshLevelMVars ref numMissingLevels; pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (ref : Syntax) (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do env ← getEnv; candidates.foldlM (fun result ⟨constName, projs⟩ => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. const ← mkConst ref constName explicitLevels; pure $ (const, projs) :: result) [] def resolveGlobalName (n : Name) : TermElabM (List (Name × List String)) := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; pure (Lean.Elab.resolveGlobalName env currNamespace openDecls n) def resolveName (ref : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do result? ← resolveLocalName n; match result? with | some (e, projs) => do unless explicitLevels.isEmpty $ throwError ref ("invalid use of explicit universe parameters, '" ++ toString e.fvarId! ++ "' is a local"); pure [(e, projs)] | none => let process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do { when candidates.isEmpty $ do { mainModule ← getMainModule; let view := extractMacroScopes n; throwError ref ("unknown identifier '" ++ view.format mainModule ++ "'") }; mkConsts ref candidates explicitLevels }; if preresolved.isEmpty then do r ← resolveGlobalName n; process r else process preresolved @[builtinTermElab cdot] def elabBadCDot : TermElab := fun stx _ => throwError stx "invalid occurrence of `·` notation, it must be surrounded by parentheses (e.g. `(· + 1)`)" /- A raw literal is not a valid term, but it is nice to have a handler for them because it allows `macros` to insert them into terms. TODO: check whether we still need wrapper nodes around literals. -/ @[builtinTermElab strLit] def elabRawStrLit : TermElab := fun stx _ => do match stx.isStrLit? with | some val => pure $ mkStrLit val | none => throwError stx "ill-formed syntax" @[builtinTermElab str] def elabStr : TermElab := fun stx expectedType? => elabRawStrLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab numLit] def elabRawNumLit : TermElab := fun stx expectedType? => do let ref := stx; val ← match stx.isNatLit? with | some val => pure (mkNatLit val) | none => throwError stx "ill-formed syntax"; typeMVar ← mkFreshTypeMVar ref MetavarKind.synthetic; registerSyntheticMVar ref typeMVar.mvarId! (SyntheticMVarKind.withDefault (Lean.mkConst `Nat)); match expectedType? with | some expectedType => do isDefEq ref expectedType typeMVar; pure () | _ => pure (); u ← getLevel ref typeMVar; u ← decLevel ref u; mvar ← mkInstMVar ref (mkApp (Lean.mkConst `HasOfNat [u]) typeMVar); pure $ mkApp3 (Lean.mkConst `HasOfNat.ofNat [u]) typeMVar mvar val @[builtinTermElab num] def elabNum : TermElab := fun stx expectedType? => elabRawNumLit (stx.getArg 0) expectedType? /- See `elabRawStrLit` -/ @[builtinTermElab charLit] def elabRawCharLit : TermElab := fun stx _ => do match stx.isCharLit? with | some val => pure $ mkApp (Lean.mkConst `Char.ofNat) (mkNatLit val.toNat) | none => throwError stx "ill-formed syntax" @[builtinTermElab char] def elabChar : TermElab := fun stx expectedType? => elabRawCharLit (stx.getArg 0) expectedType? @[builtinTermElab quotedName] def elabQuotedName : TermElab := fun stx _ => match (stx.getArg 0).isNameLit? with | some val => pure $ toExpr val | none => throwError stx "ill-formed syntax" end Term @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Elab.postpone; registerTraceClass `Elab.coe; pure () export Term (TermElabM) end Elab end Lean
d95228f3adf2ff69816b26f3af48e275906b1ff0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/algebra/hom.lean
d2338f7e7720cf712d16c76ca51164b0ac49ff5e
[ "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
14,112
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Yury Kudryashov -/ import algebra.algebra.basic /-! # Homomorphisms of `R`-algebras > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines bundled homomorphisms of `R`-algebras. ## Main definitions * `alg_hom R A B`: the type of `R`-algebra morphisms from `A` to `B`. * `algebra.of_id R A : R →ₐ[R] A`: the canonical map from `R` to `A`, as an `alg_hom`. ## Notations * `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`. -/ open_locale big_operators universes u v w u₁ v₁ set_option old_structure_cmd true /-- Defining the homomorphism in the category R-Alg. -/ @[nolint has_nonempty_instance] structure alg_hom (R : Type u) (A : Type v) (B : Type w) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B := (commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r) run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`" infixr ` →ₐ `:25 := alg_hom _ notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B /-- `alg_hom_class F R A B` asserts `F` is a type of bundled algebra homomorphisms from `A` to `B`. -/ class alg_hom_class (F : Type*) (R : out_param Type*) (A : out_param Type*) (B : out_param Type*) [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom_class F A B := (commutes : ∀ (f : F) (r : R), f (algebra_map R A r) = algebra_map R B r) -- `R` becomes a metavariable but that's fine because it's an `out_param` attribute [nolint dangerous_instance] alg_hom_class.to_ring_hom_class attribute [simp] alg_hom_class.commutes namespace alg_hom_class variables {R : Type*} {A : Type*} {B : Type*} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] @[priority 100] -- see Note [lower instance priority] instance {F : Type*} [alg_hom_class F R A B] : linear_map_class F R A B := { map_smulₛₗ := λ f r x, by simp only [algebra.smul_def, map_mul, commutes, ring_hom.id_apply], ..‹alg_hom_class F R A B› } instance {F : Type*} [alg_hom_class F R A B] : has_coe_t F (A →ₐ[R] B) := { coe := λ f, { to_fun := f, commutes' := alg_hom_class.commutes f, .. (f : A →+* B) } } end alg_hom_class namespace alg_hom variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁} section semiring variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D] variables [algebra R A] [algebra R B] [algebra R C] [algebra R D] instance : has_coe_to_fun (A →ₐ[R] B) (λ _, A → B) := ⟨alg_hom.to_fun⟩ initialize_simps_projections alg_hom (to_fun → apply) @[simp, protected] lemma coe_coe {F : Type*} [alg_hom_class F R A B] (f : F) : ⇑(f : A →ₐ[R] B) = f := rfl @[simp] lemma to_fun_eq_coe (f : A →ₐ[R] B) : f.to_fun = f := rfl instance : alg_hom_class (A →ₐ[R] B) R A B := { coe := to_fun, coe_injective' := λ f g h, by { cases f, cases g, congr' }, map_add := map_add', map_zero := map_zero', map_mul := map_mul', map_one := map_one', commutes := λ f, f.commutes' } instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩ instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩ instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩ @[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) : ⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl -- make the coercion the simp-normal form @[simp] lemma to_ring_hom_eq_coe (f : A →ₐ[R] B) : f.to_ring_hom = f := rfl @[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl @[simp, norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl @[simp, norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl variables (φ : A →ₐ[R] B) theorem coe_fn_injective : @function.injective (A →ₐ[R] B) (A → B) coe_fn := fun_like.coe_injective theorem coe_fn_inj {φ₁ φ₂ : A →ₐ[R] B} : (φ₁ : A → B) = φ₂ ↔ φ₁ = φ₂ := fun_like.coe_fn_eq theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) := λ φ₁ φ₂ H, coe_fn_injective $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B), from congr_arg _ H theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) := ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) := ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective protected lemma congr_fun {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁ = φ₂) (x : A) : φ₁ x = φ₂ x := fun_like.congr_fun H x protected lemma congr_arg (φ : A →ₐ[R] B) {x y : A} (h : x = y) : φ x = φ y := fun_like.congr_arg φ h @[ext] theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ := fun_like.ext _ _ H theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x := fun_like.ext_iff @[simp] theorem mk_coe {f : A →ₐ[R] B} (h₁ h₂ h₃ h₄ h₅) : (⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := ext $ λ _, rfl @[simp] theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext $ φ.commutes protected lemma map_add (r s : A) : φ (r + s) = φ r + φ s := map_add _ _ _ protected lemma map_zero : φ 0 = 0 := map_zero _ protected lemma map_mul (x y) : φ (x * y) = φ x * φ y := map_mul _ _ _ protected lemma map_one : φ 1 = 1 := map_one _ protected lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n := map_pow _ _ _ @[simp] protected lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x := map_smul _ _ _ protected lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) : φ (∑ x in s, f x) = ∑ x in s, φ (f x) := map_sum _ _ _ protected lemma map_finsupp_sum {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.sum g) = f.sum (λ i a, φ (g i a)) := map_finsupp_sum _ _ _ protected lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) := map_bit0 _ _ protected lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) := map_bit1 _ _ /-- If a `ring_hom` is `R`-linear, then it is an `alg_hom`. -/ def mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : A →ₐ[R] B := { to_fun := f, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, h, f.map_one], .. f } @[simp] lemma coe_mk' (f : A →+* B) (h : ∀ (c : R) x, f (c • x) = c • f x) : ⇑(mk' f h) = f := rfl section variables (R A) /-- Identity map as an `alg_hom`. -/ protected def id : A →ₐ[R] A := { commutes' := λ _, rfl, ..ring_hom.id A } @[simp] lemma coe_id : ⇑(alg_hom.id R A) = id := rfl @[simp] lemma id_to_ring_hom : (alg_hom.id R A : A →+* A) = ring_hom.id _ := rfl end lemma id_apply (p : A) : alg_hom.id R A p = p := rfl /-- Composition of algebra homeomorphisms. -/ def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C := { commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl, .. φ₁.to_ring_hom.comp ↑φ₂ } @[simp] lemma coe_comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : ⇑(φ₁.comp φ₂) = φ₁ ∘ φ₂ := rfl lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) : φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl lemma comp_to_ring_hom (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : (φ₁.comp φ₂ : A →+* C) = (φ₁ : B →+* C).comp ↑φ₂ := rfl @[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ := ext $ λ x, rfl @[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ := ext $ λ x, rfl theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) : (φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) := ext $ λ x, rfl /-- R-Alg ⥤ R-Mod -/ def to_linear_map : A →ₗ[R] B := { to_fun := φ, map_add' := map_add _, map_smul' := map_smul _ } @[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl theorem to_linear_map_injective : function.injective (to_linear_map : _ → (A →ₗ[R] B)) := λ φ₁ φ₂ h, ext $ linear_map.congr_fun h @[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) : (g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl @[simp] lemma to_linear_map_id : to_linear_map (alg_hom.id R A) = linear_map.id := linear_map.ext $ λ _, rfl /-- Promote a `linear_map` to an `alg_hom` by supplying proofs about the behavior on `1` and `*`. -/ @[simps] def of_linear_map (f : A →ₗ[R] B) (map_one : f 1 = 1) (map_mul : ∀ x y, f (x * y) = f x * f y) : A →ₐ[R] B := { to_fun := f, map_one' := map_one, map_mul' := map_mul, commutes' := λ c, by simp only [algebra.algebra_map_eq_smul_one, f.map_smul, map_one], .. f.to_add_monoid_hom } @[simp] lemma of_linear_map_to_linear_map (map_one) (map_mul) : of_linear_map φ.to_linear_map map_one map_mul = φ := by { ext, refl } @[simp] lemma to_linear_map_of_linear_map (f : A →ₗ[R] B) (map_one) (map_mul) : to_linear_map (of_linear_map f map_one map_mul) = f := by { ext, refl } @[simp] lemma of_linear_map_id (map_one) (map_mul) : of_linear_map linear_map.id map_one map_mul = alg_hom.id R A := ext $ λ _, rfl lemma map_smul_of_tower {R'} [has_smul R' A] [has_smul R' B] [linear_map.compatible_smul A B R' R] (r : R') (x : A) : φ (r • x) = r • φ x := φ.to_linear_map.map_smul_of_tower r x lemma map_list_prod (s : list A) : φ s.prod = (s.map φ).prod := φ.to_ring_hom.map_list_prod s @[simps mul one {attrs := []}] instance End : monoid (A →ₐ[R] A) := { mul := comp, mul_assoc := λ ϕ ψ χ, rfl, one := alg_hom.id R A, one_mul := λ ϕ, ext $ λ x, rfl, mul_one := λ ϕ, ext $ λ x, rfl } @[simp] lemma one_apply (x : A) : (1 : A →ₐ[R] A) x = x := rfl @[simp] lemma mul_apply (φ ψ : A →ₐ[R] A) (x : A) : (φ * ψ) x = φ (ψ x) := rfl lemma algebra_map_eq_apply (f : A →ₐ[R] B) {y : R} {x : A} (h : algebra_map R A y = x) : algebra_map R B y = f x := h ▸ (f.commutes _).symm end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) protected lemma map_multiset_prod (s : multiset A) : φ s.prod = (s.map φ).prod := map_multiset_prod _ _ protected lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) : φ (∏ x in s, f x) = ∏ x in s, φ (f x) := map_prod _ _ _ protected lemma map_finsupp_prod {α : Type*} [has_zero α] {ι : Type*} (f : ι →₀ α) (g : ι → α → A) : φ (f.prod g) = f.prod (λ i a, φ (g i a)) := map_finsupp_prod _ _ _ end comm_semiring section ring variables [comm_semiring R] [ring A] [ring B] variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B) protected lemma map_neg (x) : φ (-x) = -φ x := map_neg _ _ protected lemma map_sub (x y) : φ (x - y) = φ x - φ y := map_sub _ _ _ end ring end alg_hom namespace ring_hom variables {R S : Type*} /-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/ def to_nat_alg_hom [semiring R] [semiring S] (f : R →+* S) : R →ₐ[ℕ] S := { to_fun := f, commutes' := λ n, by simp, .. f } /-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/ def to_int_alg_hom [ring R] [ring S] [algebra ℤ R] [algebra ℤ S] (f : R →+* S) : R →ₐ[ℤ] S := { commutes' := λ n, by simp, .. f } /-- Reinterpret a `ring_hom` as a `ℚ`-algebra homomorphism. This actually yields an equivalence, see `ring_hom.equiv_rat_alg_hom`. -/ def to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : R →ₐ[ℚ] S := { commutes' := f.map_rat_algebra_map, .. f } @[simp] lemma to_rat_alg_hom_to_ring_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →+* S) : ↑f.to_rat_alg_hom = f := ring_hom.ext $ λ x, rfl end ring_hom section variables {R S : Type*} @[simp] lemma alg_hom.to_ring_hom_to_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] (f : R →ₐ[ℚ] S) : (f : R →+* S).to_rat_alg_hom = f := alg_hom.ext $ λ x, rfl /-- The equivalence between `ring_hom` and `ℚ`-algebra homomorphisms. -/ @[simps] def ring_hom.equiv_rat_alg_hom [ring R] [ring S] [algebra ℚ R] [algebra ℚ S] : (R →+* S) ≃ (R →ₐ[ℚ] S) := { to_fun := ring_hom.to_rat_alg_hom, inv_fun := alg_hom.to_ring_hom, left_inv := ring_hom.to_rat_alg_hom_to_ring_hom, right_inv := alg_hom.to_ring_hom_to_rat_alg_hom, } end namespace algebra variables (R : Type u) (A : Type v) variables [comm_semiring R] [semiring A] [algebra R A] /-- `algebra_map` as an `alg_hom`. -/ def of_id : R →ₐ[R] A := { commutes' := λ _, rfl, .. algebra_map R A } variables {R} theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl end algebra namespace mul_semiring_action variables {M G : Type*} (R A : Type*) [comm_semiring R] [semiring A] [algebra R A] variables [monoid M] [mul_semiring_action M A] [smul_comm_class M R A] /-- Each element of the monoid defines a algebra homomorphism. This is a stronger version of `mul_semiring_action.to_ring_hom` and `distrib_mul_action.to_linear_map`. -/ @[simps] def to_alg_hom (m : M) : A →ₐ[R] A := { to_fun := λ a, m • a, commutes' := smul_algebra_map _, ..mul_semiring_action.to_ring_hom _ _ m } theorem to_alg_hom_injective [has_faithful_smul M A] : function.injective (mul_semiring_action.to_alg_hom R A : M → A →ₐ[R] A) := λ m₁ m₂ h, eq_of_smul_eq_smul $ λ r, alg_hom.ext_iff.1 h r end mul_semiring_action
a3bcedcfdc302305cef3564a6c7ed08b70f71c81
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/complex/arg.lean
6c1e42e0fa2aae6601ee6b0f95d470486f933472
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
24,440
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.angle import analysis.special_functions.trigonometric.inverse /-! # The argument of a complex number. We define `arg : ℂ → ℝ`, returing a real number in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, while `arg 0` defaults to `0` -/ noncomputable theory namespace complex open_locale complex_conjugate real topological_space open filter set /-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`, `sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`, `arg 0` defaults to `0` -/ noncomputable def arg (x : ℂ) : ℝ := if 0 ≤ x.re then real.arcsin (x.im / x.abs) else if 0 ≤ x.im then real.arcsin ((-x).im / x.abs) + π else real.arcsin ((-x).im / x.abs) - π lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs := by unfold arg; split_ifs; simp [sub_eq_add_neg, arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1 (abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg, real.sin_neg] lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs := begin have habs : 0 < abs x := abs_pos.2 hx, have him : |im x / abs x| ≤ 1, { rw [_root_.abs_div, abs_abs], exact div_le_one_of_le x.abs_im_le_abs x.abs_nonneg }, rw abs_le at him, rw arg, split_ifs with h₁ h₂ h₂, { rw [real.cos_arcsin]; field_simp [real.sqrt_sq, habs.le, *] }, { rw [real.cos_add_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } }, { rw [real.cos_sub_pi, real.cos_arcsin], { field_simp [real.sqrt_div (sq_nonneg _), real.sqrt_sq_eq_abs, _root_.abs_of_neg (not_le.1 h₁), *] }, { simpa [neg_div] using him.2 }, { simpa [neg_div, neg_le] using him.1 } } end @[simp] lemma abs_mul_exp_arg_mul_I (x : ℂ) : ↑(abs x) * exp (arg x * I) = x := begin rcases eq_or_ne x 0 with (rfl|hx), { simp }, { have : abs x ≠ 0 := abs_ne_zero.2 hx, ext; field_simp [sin_arg, cos_arg hx, this, mul_comm (abs x)] } end @[simp] lemma abs_mul_cos_add_sin_mul_I (x : ℂ) : (abs x * (cos (arg x) + sin (arg x) * I) : ℂ) = x := by rw [← exp_mul_I, abs_mul_exp_arg_mul_I] @[simp] lemma range_exp_mul_I : range (λ x : ℝ, exp (x * I)) = metric.sphere 0 1 := begin simp only [metric.sphere, dist_eq, sub_zero], refine (range_subset_iff.2 $ λ x, _).antisymm (λ z (hz : abs z = 1), _), { exact abs_exp_of_real_mul_I _ }, { refine ⟨arg z, _⟩, calc exp (arg z * I) = abs z * exp (arg z * I) : by rw [hz, of_real_one, one_mul] ... = z : abs_mul_exp_arg_mul_I z } end lemma arg_mul_cos_add_sin_mul_I {r : ℝ} (hr : 0 < r) {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (r * (cos θ + sin θ * I)) = θ := begin have hπ := real.pi_pos, simp only [arg, abs_mul, abs_cos_add_sin_mul_I, abs_of_nonneg hr.le, mul_one], simp only [of_real_mul_re, of_real_mul_im, neg_im, ← of_real_cos, ← of_real_sin, ← mk_eq_add_mul_I, neg_div, mul_div_cancel_left _ hr.ne', mul_nonneg_iff_right_nonneg_of_pos hr], by_cases h₁ : θ ∈ Icc (-(π / 2)) (π / 2), { rw if_pos, exacts [real.arcsin_sin' h₁, real.cos_nonneg_of_mem_Icc h₁] }, { rw [mem_Icc, not_and_distrib, not_le, not_le] at h₁, cases h₁, { replace hθ := hθ.1, have hcos : real.cos θ < 0, { rw [← neg_pos, ← real.cos_add_pi], refine real.cos_pos_of_mem_Ioo ⟨_, _⟩; linarith }, have hsin : real.sin θ < 0 := real.sin_neg_of_neg_of_neg_pi_lt (by linarith) hθ, rw [if_neg, if_neg, ← real.sin_add_pi, real.arcsin_sin, add_sub_cancel]; [linarith, linarith, exact hsin.not_le, exact hcos.not_le] }, { replace hθ := hθ.2, have hcos : real.cos θ < 0 := real.cos_neg_of_pi_div_two_lt_of_lt h₁ (by linarith), have hsin : 0 ≤ real.sin θ := real.sin_nonneg_of_mem_Icc ⟨by linarith, hθ⟩, rw [if_neg, if_pos, ← real.sin_sub_pi, real.arcsin_sin, sub_add_cancel]; [linarith, linarith, exact hsin, exact hcos.not_le] } } end lemma arg_cos_add_sin_mul_I {θ : ℝ} (hθ : θ ∈ Ioc (-π) π) : arg (cos θ + sin θ * I) = θ := by rw [← one_mul (_ + _), ← of_real_one, arg_mul_cos_add_sin_mul_I zero_lt_one hθ] @[simp] lemma arg_zero : arg 0 = 0 := by simp [arg, le_refl] lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y := by rw [← abs_mul_exp_arg_mul_I x, ← abs_mul_exp_arg_mul_I y, h₁, h₂] lemma ext_abs_arg_iff {x y : ℂ} : x = y ↔ abs x = abs y ∧ arg x = arg y := ⟨λ h, h ▸ ⟨rfl, rfl⟩, and_imp.2 ext_abs_arg⟩ lemma arg_mem_Ioc (z : ℂ) : arg z ∈ Ioc (-π) π := begin have hπ : 0 < π := real.pi_pos, rcases eq_or_ne z 0 with (rfl|hz), simp [hπ, hπ.le], rcases exists_unique_add_zsmul_mem_Ioc real.two_pi_pos (arg z) (-π) with ⟨N, hN, -⟩, rw [two_mul, neg_add_cancel_left, ← two_mul, zsmul_eq_mul] at hN, rw [← abs_mul_cos_add_sin_mul_I z, ← cos_add_int_mul_two_pi _ N, ← sin_add_int_mul_two_pi _ N], simp only [← of_real_one, ← of_real_bit0, ← of_real_mul, ← of_real_add, ← of_real_int_cast], rwa [arg_mul_cos_add_sin_mul_I (abs_pos.2 hz) hN] end @[simp] lemma range_arg : range arg = Ioc (-π) π := (range_subset_iff.2 arg_mem_Ioc).antisymm (λ x hx, ⟨_, arg_cos_add_sin_mul_I hx⟩) lemma arg_le_pi (x : ℂ) : arg x ≤ π := (arg_mem_Ioc x).2 lemma neg_pi_lt_arg (x : ℂ) : -π < arg x := (arg_mem_Ioc x).1 @[simp] lemma arg_nonneg_iff {z : ℂ} : 0 ≤ arg z ↔ 0 ≤ z.im := begin rcases eq_or_ne z 0 with (rfl|h₀), { simp }, calc 0 ≤ arg z ↔ 0 ≤ real.sin (arg z) : ⟨λ h, real.sin_nonneg_of_mem_Icc ⟨h, arg_le_pi z⟩, by { contrapose!, intro h, exact real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_arg _) }⟩ ... ↔ _ : by rw [sin_arg, le_div_iff (abs_pos.2 h₀), zero_mul] end @[simp] lemma arg_neg_iff {z : ℂ} : arg z < 0 ↔ z.im < 0 := lt_iff_lt_of_le_iff_le arg_nonneg_iff lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x := begin rcases eq_or_ne x 0 with (rfl|hx), { rw mul_zero }, conv_lhs { rw [← abs_mul_cos_add_sin_mul_I x, ← mul_assoc, ← of_real_mul, arg_mul_cos_add_sin_mul_I (mul_pos hr (abs_pos.2 hx)) x.arg_mem_Ioc] } end lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : arg x = arg y ↔ (abs y / abs x : ℂ) * x = y := begin simp only [ext_abs_arg_iff, abs_mul, abs_div, abs_of_real, abs_abs, div_mul_cancel _ (abs_ne_zero.2 hx), eq_self_iff_true, true_and], rw [← of_real_div, arg_real_mul], exact div_pos (abs_pos.2 hy) (abs_pos.2 hx) end @[simp] lemma arg_one : arg 1 = 0 := by simp [arg, zero_le_one] @[simp] lemma arg_neg_one : arg (-1) = π := by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _ _)] @[simp] lemma arg_I : arg I = π / 2 := by simp [arg, le_refl] @[simp] lemma arg_neg_I : arg (-I) = -(π / 2) := by simp [arg, le_refl] @[simp] lemma tan_arg (x : ℂ) : real.tan (arg x) = x.im / x.re := begin by_cases h : x = 0, { simp only [h, zero_div, complex.zero_im, complex.arg_zero, real.tan_zero, complex.zero_re] }, rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg h, div_div_div_cancel_right _ (abs_ne_zero.2 h)] end lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 := by simp [arg, hx] lemma arg_eq_zero_iff {z : ℂ} : arg z = 0 ↔ 0 ≤ z.re ∧ z.im = 0 := begin refine ⟨λ h, _, _⟩, { rw [←abs_mul_cos_add_sin_mul_I z, h], simp [abs_nonneg] }, { cases z with x y, rintro ⟨h, rfl : y = 0⟩, exact arg_of_real_of_nonneg h } end lemma arg_eq_pi_iff {z : ℂ} : arg z = π ↔ z.re < 0 ∧ z.im = 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero.symm] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨h : x < 0, rfl : y = 0⟩, rw [← arg_neg_one, ← arg_real_mul (-1) (neg_pos.2 h)], simp [← of_real_def] } end lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π := arg_eq_pi_iff.2 ⟨hx, rfl⟩ lemma arg_eq_pi_div_two_iff {z : ℂ} : arg z = π / 2 ↔ z.re = 0 ∧ 0 < z.im := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_div_two_pos.ne] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : 0 < y⟩, rw [← arg_I, ← arg_real_mul I hy, of_real_mul', I_re, I_im, mul_zero, mul_one] } end lemma arg_eq_neg_pi_div_two_iff {z : ℂ} : arg z = - (π / 2) ↔ z.re = 0 ∧ z.im < 0 := begin by_cases h₀ : z = 0, { simp [h₀, lt_irrefl, real.pi_ne_zero] }, split, { intro h, rw [← abs_mul_cos_add_sin_mul_I z, h], simp [h₀] }, { cases z with x y, rintro ⟨rfl : x = 0, hy : y < 0⟩, rw [← arg_neg_I, ← arg_real_mul (-I) (neg_pos.2 hy), mk_eq_add_mul_I], simp } end lemma arg_of_re_nonneg {x : ℂ} (hx : 0 ≤ x.re) : arg x = real.arcsin (x.im / x.abs) := if_pos hx lemma arg_of_re_neg_of_im_nonneg {x : ℂ} (hx_re : x.re < 0) (hx_im : 0 ≤ x.im) : arg x = real.arcsin ((-x).im / x.abs) + π := by simp only [arg, hx_re.not_le, hx_im, if_true, if_false] lemma arg_of_re_neg_of_im_neg {x : ℂ} (hx_re : x.re < 0) (hx_im : x.im < 0) : arg x = real.arcsin ((-x).im / x.abs) - π := by simp only [arg, hx_re.not_le, hx_im.not_le, if_false] lemma arg_of_im_nonneg_of_ne_zero {z : ℂ} (h₁ : 0 ≤ z.im) (h₂ : z ≠ 0) : arg z = real.arccos (z.re / abs z) := by rw [← cos_arg h₂, real.arccos_cos (arg_nonneg_iff.2 h₁) (arg_le_pi _)] lemma arg_of_im_pos {z : ℂ} (hz : 0 < z.im) : arg z = real.arccos (z.re / abs z) := arg_of_im_nonneg_of_ne_zero hz.le (λ h, hz.ne' $ h.symm ▸ rfl) lemma arg_of_im_neg {z : ℂ} (hz : z.im < 0) : arg z = -real.arccos (z.re / abs z) := begin have h₀ : z ≠ 0, from mt (congr_arg im) hz.ne, rw [← cos_arg h₀, ← real.cos_neg, real.arccos_cos, neg_neg], exacts [neg_nonneg.2 (arg_neg_iff.2 hz).le, neg_le.2 (neg_pi_lt_arg z).le] end lemma arg_conj (x : ℂ) : arg (conj x) = if arg x = π then π else -arg x := begin simp_rw [arg_eq_pi_iff, arg, neg_im, conj_im, conj_re, abs_conj, neg_div, neg_neg, real.arcsin_neg, apply_ite has_neg.neg, neg_add, neg_sub, neg_neg, ←sub_eq_add_neg, sub_neg_eq_add, add_comm π], rcases lt_trichotomy x.re 0 with (hr|hr|hr); rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hr, hr.not_le, hi.le, hi.ne, not_le.2 hi] }, { simp [hr, hr.not_le, hi] }, { simp [hr, hr.not_le, hi.ne.symm, hi.le, not_le.2 hi] }, { simp [hr] }, { simp [hr] }, { simp [hr] }, { simp [hr, hr.le, hi.ne] }, { simp [hr, hr.le, hr.le.not_lt] }, { simp [hr, hr.le, hr.le.not_lt] }, end lemma arg_inv (x : ℂ) : arg x⁻¹ = if arg x = π then π else -arg x := begin rw [←arg_conj, inv_def, mul_comm], by_cases hx : x = 0, { simp [hx] }, { exact arg_real_mul (conj x) (by simp [hx]) } end lemma arg_le_pi_div_two_iff {z : ℂ} : arg z ≤ π / 2 ↔ 0 ≤ re z ∨ im z < 0 := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.arcsin_le_pi_div_two, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him.not_lt], rw [iff_false, not_le, arg_of_re_neg_of_im_nonneg hre him, ← sub_lt_iff_lt_add, half_sub, real.neg_pi_div_two_lt_arcsin, neg_im, neg_div, neg_lt_neg_iff, div_lt_one, ← _root_.abs_of_nonneg him, abs_im_lt_abs], exacts [hre.ne, abs_pos.2 $ ne_of_apply_ne re hre.ne] }, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_neg hre him], exact (sub_le_self _ real.pi_pos.le).trans (real.arcsin_le_pi_div_two _) } end lemma neg_pi_div_two_le_arg_iff {z : ℂ} : -(π / 2) ≤ arg z ↔ 0 ≤ re z ∨ 0 ≤ im z := begin cases le_or_lt 0 (re z) with hre hre, { simp only [hre, arg_of_re_nonneg hre, real.neg_pi_div_two_le_arcsin, true_or] }, simp only [hre.not_le, false_or], cases le_or_lt 0 (im z) with him him, { simp only [him], rw [iff_true, arg_of_re_neg_of_im_nonneg hre him], exact (real.neg_pi_div_two_le_arcsin _).trans (le_add_of_nonneg_right real.pi_pos.le) }, { simp only [him.not_le], rw [iff_false, not_le, arg_of_re_neg_of_im_neg hre him, sub_lt_iff_lt_add', ← sub_eq_add_neg, sub_half, real.arcsin_lt_pi_div_two, div_lt_one, neg_im, ← abs_of_neg him, abs_im_lt_abs], exacts [hre.ne, abs_pos.2 $ ne_of_apply_ne re hre.ne] } end @[simp] lemma abs_arg_le_pi_div_two_iff {z : ℂ} : |arg z| ≤ π / 2 ↔ 0 ≤ re z := by rw [abs_le, arg_le_pi_div_two_iff, neg_pi_div_two_le_arg_iff, ← or_and_distrib_left, ← not_le, and_not_self, or_false] @[simp] lemma arg_conj_coe_angle (x : ℂ) : (arg (conj x) : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_conj, h] end @[simp] lemma arg_inv_coe_angle (x : ℂ) : (arg x⁻¹ : real.angle) = -arg x := begin by_cases h : arg x = π; simp [arg_inv, h] end lemma arg_neg_eq_arg_sub_pi_of_im_pos {x : ℂ} (hi : 0 < x.im) : arg (-x) = arg x - π := begin rw [arg_of_im_pos hi, arg_of_im_neg (show (-x).im < 0, from left.neg_neg_iff.2 hi)], simp [neg_div, real.arccos_neg] end lemma arg_neg_eq_arg_add_pi_of_im_neg {x : ℂ} (hi : x.im < 0) : arg (-x) = arg x + π := begin rw [arg_of_im_neg hi, arg_of_im_pos (show 0 < (-x).im, from left.neg_pos_iff.2 hi)], simp [neg_div, real.arccos_neg, add_comm, ←sub_eq_add_neg] end lemma arg_neg_eq_arg_sub_pi_iff {x : ℂ} : arg (-x) = arg x - π ↔ (0 < x.im ∨ x.im = 0 ∧ x.re < 0) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, hi.ne, hi.not_lt, arg_neg_eq_arg_add_pi_of_im_neg, sub_eq_add_neg, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr] }, { simp [hr, hi, real.pi_ne_zero] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr.not_lt, ←add_eq_zero_iff_eq_neg, real.pi_ne_zero] } }, { simp [hi, arg_neg_eq_arg_sub_pi_of_im_pos] } end lemma arg_neg_eq_arg_add_pi_iff {x : ℂ} : arg (-x) = arg x + π ↔ (x.im < 0 ∨ x.im = 0 ∧ 0 < x.re) := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { simp [hi, arg_neg_eq_arg_add_pi_of_im_neg] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le], simp [hr.not_lt, ←two_mul, real.pi_ne_zero] }, { simp [hr, hi, real.pi_ne_zero.symm] }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr)], simp [hr] } }, { simp [hi, hi.ne.symm, hi.not_lt, arg_neg_eq_arg_sub_pi_of_im_pos, sub_eq_add_neg, ←add_eq_zero_iff_neg_eq, real.pi_ne_zero] } end lemma arg_neg_coe_angle {x : ℂ} (hx : x ≠ 0) : (arg (-x) : real.angle) = arg x + π := begin rcases lt_trichotomy x.im 0 with (hi|hi|hi), { rw [arg_neg_eq_arg_add_pi_of_im_neg hi, real.angle.coe_add] }, { rw (ext rfl hi : x = x.re), rcases lt_trichotomy x.re 0 with (hr|hr|hr), { rw [arg_of_real_of_neg hr, ←of_real_neg, arg_of_real_of_nonneg (left.neg_pos_iff.2 hr).le, ←real.angle.coe_add, ←two_mul, real.angle.coe_two_pi, real.angle.coe_zero] }, { exact false.elim (hx (ext hr hi)) }, { rw [arg_of_real_of_nonneg hr.le, ←of_real_neg, arg_of_real_of_neg (left.neg_neg_iff.2 hr), real.angle.coe_zero, zero_add] } }, { rw [arg_neg_eq_arg_sub_pi_of_im_pos hi, real.angle.coe_sub, real.angle.sub_coe_pi_eq_add_coe_pi] } end lemma arg_mul_cos_add_sin_mul_I_eq_mul_fract {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) = π - 2 * π * int.fract ((π - θ) / (2 * π)) := begin have hi : π - 2 * π * int.fract ((π - θ) / (2 * π)) ∈ Ioc (-π) π, { rw [←mem_preimage, preimage_const_sub_Ioc, ←mem_preimage, preimage_const_mul_Ico _ _ real.two_pi_pos, sub_self, zero_div, sub_neg_eq_add, ←two_mul, div_self real.two_pi_pos.ne.symm], refine set.mem_of_mem_of_subset (set.mem_range_self _) _, rw [←image_univ, int.image_fract], simp }, have hs : π - 2 * π * int.fract ((π - θ) / (2 * π)) = 2 * π * ⌊(π - θ) / (2 * π)⌋ + θ, { rw [int.fract, mul_sub, mul_div_cancel' _ real.two_pi_pos.ne.symm], abel }, convert arg_mul_cos_add_sin_mul_I hr hi using 3, simp_rw [hs, mul_comm (2 * π), add_comm _ θ, ←of_real_cos, ←of_real_sin, real.cos_add_int_mul_two_pi, real.sin_add_int_mul_two_pi] end lemma arg_cos_add_sin_mul_I_eq_mul_fract (θ : ℝ) : arg (cos θ + sin θ * I) = π - 2 * π * int.fract ((π - θ) / (2 * π)) := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_eq_mul_fract zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_sub {r : ℝ} (hr : 0 < r) (θ : ℝ) : arg (r * (cos θ + sin θ * I)) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := begin rw [arg_mul_cos_add_sin_mul_I_eq_mul_fract hr, int.fract, mul_sub, mul_div_cancel' _ real.two_pi_pos.ne.symm], abel end lemma arg_cos_add_sin_mul_I_sub (θ : ℝ) : arg (cos θ + sin θ * I) - θ = 2 * π * ⌊(π - θ) / (2 * π)⌋ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_sub zero_lt_one] lemma arg_mul_cos_add_sin_mul_I_coe_angle {r : ℝ} (hr : 0 < r) (θ : real.angle) : (arg (r * (real.angle.cos θ + real.angle.sin θ * I)) : real.angle) = θ := begin induction θ using real.angle.induction_on, rw [real.angle.cos_coe, real.angle.sin_coe, real.angle.angle_eq_iff_two_pi_dvd_sub], use ⌊(π - θ) / (2 * π)⌋, exact_mod_cast arg_mul_cos_add_sin_mul_I_sub hr θ end lemma arg_cos_add_sin_mul_I_coe_angle (θ : real.angle) : (arg (real.angle.cos θ + real.angle.sin θ * I) : real.angle) = θ := by rw [←one_mul (_ + _), ←of_real_one, arg_mul_cos_add_sin_mul_I_coe_angle zero_lt_one] lemma arg_mul_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x * y) : real.angle) = arg x + arg y := begin convert arg_mul_cos_add_sin_mul_I_coe_angle (mul_pos (abs_pos.2 hx) (abs_pos.2 hy)) (arg x + arg y : real.angle) using 3, simp_rw [←real.angle.coe_add, real.angle.sin_coe, real.angle.cos_coe, of_real_cos, of_real_sin, cos_add_sin_I, of_real_add, add_mul, exp_add, of_real_mul], rw [mul_assoc, mul_comm (exp _), ←mul_assoc (abs y : ℂ), abs_mul_exp_arg_mul_I, mul_comm y, ←mul_assoc, abs_mul_exp_arg_mul_I] end lemma arg_div_coe_angle {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) : (arg (x / y) : real.angle) = arg x - arg y := by rw [div_eq_mul_inv, arg_mul_coe_angle hx (inv_ne_zero hy), arg_inv_coe_angle, sub_eq_add_neg] @[simp] lemma arg_coe_angle_eq_iff {x y : ℂ} : (arg x : real.angle) = arg y ↔ arg x = arg y := begin split, { intro h, rw real.angle.angle_eq_iff_two_pi_dvd_sub at h, rcases h with ⟨k, hk⟩, rw ←sub_eq_zero, have ha : -(2 * π) < arg x - arg y, { linarith only [neg_pi_lt_arg x, arg_le_pi y] }, have hb : arg x - arg y < 2 * π, { linarith only [arg_le_pi x, neg_pi_lt_arg y] }, rw [hk, neg_lt, neg_mul_eq_mul_neg, mul_lt_iff_lt_one_right real.two_pi_pos, neg_lt, ←int.cast_one, ←int.cast_neg, int.cast_lt] at ha, rw [hk, mul_lt_iff_lt_one_right real.two_pi_pos, ←int.cast_one, int.cast_lt] at hb, have hk' : k = 0, { linarith only [ha, hb] }, rw hk' at hk, simpa using hk }, { intro h, rw h } end section continuity variables {x z : ℂ} lemma arg_eq_nhds_of_re_pos (hx : 0 < x.re) : arg =ᶠ[𝓝 x] λ x, real.arcsin (x.im / x.abs) := ((continuous_re.tendsto _).eventually (lt_mem_nhds hx)).mono $ λ y hy, arg_of_re_nonneg hy.le lemma arg_eq_nhds_of_re_neg_of_im_pos (hx_re : x.re < 0) (hx_im : 0 < x.im) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) + π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ 0 < y.im, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_nonneg hy.1 hy.2.le), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ 0 < x.im), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_zero continuous_im), end lemma arg_eq_nhds_of_re_neg_of_im_neg (hx_re : x.re < 0) (hx_im : x.im < 0) : arg =ᶠ[𝓝 x] λ x, real.arcsin ((-x).im / x.abs) - π := begin suffices h_forall_nhds : ∀ᶠ (y : ℂ) in (𝓝 x), y.re < 0 ∧ y.im < 0, from h_forall_nhds.mono (λ y hy, arg_of_re_neg_of_im_neg hy.1 hy.2), refine is_open.eventually_mem _ (⟨hx_re, hx_im⟩ : x.re < 0 ∧ x.im < 0), exact is_open.and (is_open_lt continuous_re continuous_zero) (is_open_lt continuous_im continuous_zero), end lemma arg_eq_nhds_of_im_pos (hz : 0 < im z) : arg =ᶠ[𝓝 z] λ x, real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (lt_mem_nhds hz)).mono $ λ x, arg_of_im_pos lemma arg_eq_nhds_of_im_neg (hz : im z < 0) : arg =ᶠ[𝓝 z] λ x, -real.arccos (x.re / abs x) := ((continuous_im.tendsto _).eventually (gt_mem_nhds hz)).mono $ λ x, arg_of_im_neg lemma continuous_at_arg (h : 0 < x.re ∨ x.im ≠ 0) : continuous_at arg x := begin have h₀ : abs x ≠ 0, { rw abs_ne_zero, rintro rfl, simpa using h }, rw [← lt_or_lt_iff_ne] at h, rcases h with (hx_re|hx_im|hx_im), exacts [(real.continuous_at_arcsin.comp (continuous_im.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_re_pos hx_re).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).neg.congr (arg_eq_nhds_of_im_neg hx_im).symm, (real.continuous_arccos.continuous_at.comp (continuous_re.continuous_at.div continuous_abs.continuous_at h₀)).congr (arg_eq_nhds_of_im_pos hx_im).symm] end lemma tendsto_arg_nhds_within_im_neg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)) := begin suffices H : tendsto (λ x : ℂ, real.arcsin ((-x).im / x.abs) - π) (𝓝[{z : ℂ | z.im < 0}] z) (𝓝 (-π)), { refine H.congr' _, have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_neg him.not_le], }, convert (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).sub tendsto_const_nhds, { simp [him] }, { lift z to ℝ using him, simpa using hre.ne } end lemma continuous_within_at_arg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : continuous_within_at arg {z : ℂ | 0 ≤ z.im} z := begin have : arg =ᶠ[𝓝[{z : ℂ | 0 ≤ z.im}] z] λ x, real.arcsin ((-x).im / x.abs) + π, { have : ∀ᶠ x : ℂ in 𝓝 z, x.re < 0, from continuous_re.tendsto z (gt_mem_nhds hre), filter_upwards [self_mem_nhds_within, mem_nhds_within_of_mem_nhds this] with _ him hre, rw [arg, if_neg hre.not_le, if_pos him] }, refine continuous_within_at.congr_of_eventually_eq _ this _, { refine (real.continuous_at_arcsin.comp_continuous_within_at ((continuous_im.continuous_at.comp_continuous_within_at continuous_within_at_neg).div continuous_abs.continuous_within_at _)).add tendsto_const_nhds, lift z to ℝ using him, simpa using hre.ne }, { rw [arg, if_neg hre.not_le, if_pos him.ge] } end lemma tendsto_arg_nhds_within_im_nonneg_of_re_neg_of_im_zero {z : ℂ} (hre : z.re < 0) (him : z.im = 0) : tendsto arg (𝓝[{z : ℂ | 0 ≤ z.im}] z) (𝓝 π) := by simpa only [arg_eq_pi_iff.2 ⟨hre, him⟩] using (continuous_within_at_arg_of_re_neg_of_im_zero hre him).tendsto end continuity end complex
36de72b68b133dd0e5ee37034d5be37fd74dd1d2
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/polynomial/opposites.lean
63f16474e19bfea4425704cc04c9d05264a22a99
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,168
lean
/- Copyright (c) 2022 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.induction import data.polynomial.degree.definitions /-! # Interactions between `R[X]` and `Rᵐᵒᵖ[X]` This file contains the basic API for "pushing through" the isomorphism `op_ring_equiv : R[X]ᵐᵒᵖ ≃+* Rᵐᵒᵖ[X]`. It allows going back and forth between a polynomial ring over a semiring and the polynomial ring over the opposite semiring. -/ open_locale polynomial open polynomial mul_opposite variables {R : Type*} [semiring R] {p q : R[X]} noncomputable theory namespace polynomial /-- Ring isomorphism between `R[X]ᵐᵒᵖ` and `Rᵐᵒᵖ[X]` sending each coefficient of a polynomial to the corresponding element of the opposite ring. -/ def op_ring_equiv (R : Type*) [semiring R] : R[X]ᵐᵒᵖ ≃+* Rᵐᵒᵖ[X] := ((to_finsupp_iso R).op.trans add_monoid_algebra.op_ring_equiv).trans (to_finsupp_iso _).symm -- for maintenance purposes: `by simp [op_ring_equiv]` proves this lemma /-! Lemmas to get started, using `op_ring_equiv R` on the various expressions of `finsupp.single`: `monomial`, `C a`, `X`, `C a * X ^ n`. -/ @[simp] lemma op_ring_equiv_op_monomial (n : ℕ) (r : R) : op_ring_equiv R (op (monomial n r : R[X])) = monomial n (op r) := by simp only [op_ring_equiv, ring_equiv.trans_apply, ring_equiv.op_apply_apply, ring_equiv.to_add_equiv_eq_coe, add_equiv.mul_op_apply, add_equiv.to_fun_eq_coe, add_equiv.coe_trans, op_add_equiv_apply, ring_equiv.coe_to_add_equiv, op_add_equiv_symm_apply, function.comp_app, unop_op, to_finsupp_iso_apply, to_finsupp_monomial, add_monoid_algebra.op_ring_equiv_single, to_finsupp_iso_symm_apply, of_finsupp_single] @[simp] lemma op_ring_equiv_op_C (a : R) : op_ring_equiv R (op (C a)) = C (op a) := op_ring_equiv_op_monomial 0 a @[simp] lemma op_ring_equiv_op_X : op_ring_equiv R (op (X : R[X])) = X := op_ring_equiv_op_monomial 1 1 lemma op_ring_equiv_op_C_mul_X_pow (r : R) (n : ℕ) : op_ring_equiv R (op (C r * X ^ n : R[X])) = C (op r) * X ^ n := by simp only [X_pow_mul, op_mul, op_pow, map_mul, map_pow, op_ring_equiv_op_X, op_ring_equiv_op_C] /-! Lemmas to get started, using `(op_ring_equiv R).symm` on the various expressions of `finsupp.single`: `monomial`, `C a`, `X`, `C a * X ^ n`. -/ @[simp] lemma op_ring_equiv_symm_monomial (n : ℕ) (r : Rᵐᵒᵖ) : (op_ring_equiv R).symm (monomial n r) = op (monomial n (unop r)) := (op_ring_equiv R).injective (by simp) @[simp] lemma op_ring_equiv_symm_C (a : Rᵐᵒᵖ) : (op_ring_equiv R).symm (C a) = op (C (unop a)) := op_ring_equiv_symm_monomial 0 a @[simp] lemma op_ring_equiv_symm_X : (op_ring_equiv R).symm (X : Rᵐᵒᵖ[X]) = op X := op_ring_equiv_symm_monomial 1 1 lemma op_ring_equiv_symm_C_mul_X_pow (r : Rᵐᵒᵖ) (n : ℕ) : (op_ring_equiv R).symm (C r * X ^ n : Rᵐᵒᵖ[X]) = op (C (unop r) * X ^ n) := by rw [← monomial_eq_C_mul_X, op_ring_equiv_symm_monomial, monomial_eq_C_mul_X] /-! Lemmas about more global properties of polynomials and opposites. -/ @[simp] lemma coeff_op_ring_equiv (p : R[X]ᵐᵒᵖ) (n : ℕ) : (op_ring_equiv R p).coeff n = op ((unop p).coeff n) := begin induction p using mul_opposite.rec, cases p, refl end @[simp] lemma support_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).support = (unop p).support := begin induction p using mul_opposite.rec, cases p, exact finsupp.support_map_range_of_injective _ _ op_injective end @[simp] lemma nat_degree_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).nat_degree = (unop p).nat_degree := begin by_cases p0 : p = 0, { simp only [p0, _root_.map_zero, nat_degree_zero, unop_zero] }, { simp only [p0, nat_degree_eq_support_max', ne.def, add_equiv_class.map_eq_zero_iff, not_false_iff, support_op_ring_equiv, unop_eq_zero_iff] } end @[simp] lemma leading_coeff_op_ring_equiv (p : R[X]ᵐᵒᵖ) : (op_ring_equiv R p).leading_coeff = op (unop p).leading_coeff := by rw [leading_coeff, coeff_op_ring_equiv, nat_degree_op_ring_equiv, leading_coeff] end polynomial
a012a1553545975cbe8919526ad4fd25b28b0640
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1891.lean
3eaa57cc029e175e889f05105cff27f8b3795880
[ "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
507
lean
namespace Ex1 class FunLike (F : Sort _) (β : outParam <| Nat → Sort _) where coe : F → ∀ a, β a inductive Secret def Wrapper := Secret inductive Bla | z instance : FunLike Bla (fun _ => Wrapper) := sorry instance (priority := 100) {F β} [FunLike F β] : CoeFun F fun _ => ∀ a : Nat, β a where coe := FunLike.coe #check Bla.z ∘ id end Ex1 namespace Ex2 structure Secret def Wrapper := Secret def f (a : Nat) : (fun _ => Wrapper) a := ⟨⟩ #check f ∘ id end Ex2
7f22fd6e09c8d6dbd8d8f8ff507d04c9c1b7564b
92b50235facfbc08dfe7f334827d47281471333b
/tests/lean/empty.lean
d0e7e2f80d4463a49e70320c34ab6537881b1c25
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
173
lean
import logic logic.axioms.hilbert open inhabited nonempty definition v1 : Prop := epsilon (λ x, true) inductive Empty : Type definition v2 : Empty := epsilon (λ x, true)
dfc18e7e7c44f85dd82ae82b0044a2ea8ab32b25
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Data/Lsp/LanguageFeatures.lean
f47f9cce7d8612167b0b3ec21e62ef08d213835d
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,627
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic namespace Lean namespace Lsp open Json structure Hover where /- NOTE we should also accept MarkedString/MarkedString[] here but they are deprecated, so maybe can get away without. -/ contents : MarkupContent range? : Option Range := none deriving ToJson, FromJson structure HoverParams extends TextDocumentPositionParams instance : FromJson HoverParams := ⟨fun j => do let tdpp ← @fromJson? TextDocumentPositionParams _ j pure ⟨tdpp⟩⟩ instance : ToJson HoverParams := ⟨fun o => toJson o.toTextDocumentPositionParams⟩ structure DocumentSymbolParams where textDocument : TextDocumentIdentifier deriving FromJson, ToJson inductive SymbolKind where | file | module | «namespace» | package | «class» | method | property | field | constructor | enum | interface | function | «variable» | «constant» | string | number | boolean | array | object | key | null | enumMember | struct | event | operator | typeParameter instance : ToJson SymbolKind where toJson | SymbolKind.file => 1 | SymbolKind.module => 2 | SymbolKind.namespace => 3 | SymbolKind.package => 4 | SymbolKind.class => 5 | SymbolKind.method => 6 | SymbolKind.property => 7 | SymbolKind.field => 8 | SymbolKind.constructor => 9 | SymbolKind.enum => 10 | SymbolKind.interface => 11 | SymbolKind.function => 12 | SymbolKind.variable => 13 | SymbolKind.constant => 14 | SymbolKind.string => 15 | SymbolKind.number => 16 | SymbolKind.boolean => 17 | SymbolKind.array => 18 | SymbolKind.object => 19 | SymbolKind.key => 20 | SymbolKind.null => 21 | SymbolKind.enumMember => 22 | SymbolKind.struct => 23 | SymbolKind.event => 24 | SymbolKind.operator => 25 | SymbolKind.typeParameter => 26 structure DocumentSymbolAux (Self : Type) where name : String detail? : Option String := none kind : SymbolKind -- tags? : Array SymbolTag range : Range selectionRange : Range children? : Option (Array Self) := none deriving ToJson inductive DocumentSymbol where | mk (sym : DocumentSymbolAux DocumentSymbol) partial instance : ToJson DocumentSymbol where toJson := let rec go | DocumentSymbol.mk sym => have ToJson DocumentSymbol := ⟨go⟩ toJson sym go structure DocumentSymbolResult where syms : Array DocumentSymbol instance : ToJson DocumentSymbolResult where toJson dsr := toJson dsr.syms end Lsp end Lean
1f709b3f2f848f7be88bf2b01ffab7d54c7090b3
46125763b4dbf50619e8846a1371029346f4c3db
/src/data/equiv/basic.lean
4db654b503732cb16964eb6e62458916befcafb8
[ "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
43,188
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import tactic.split_ifs logic.function logic.unique data.set.function data.bool data.quot open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv def function.involutive.to_equiv {f : α → α} (h : involutive f) : α ≃ α := ⟨f, f, h.left_inverse, h.right_inverse⟩ namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by { subst f₂, exact this }, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * @[ext] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[ext] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext _ _ H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem injective : ∀ f : α ≃ β, injective f | ⟨f, g, h₁, h₂⟩ := injective_of_left_inverse h₁ protected theorem surjective : ∀ f : α ≃ β, surjective f | ⟨f, g, h₁, h₂⟩ := surjective_of_has_right_inverse ⟨_, h₂⟩ protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.injective (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.injective.eq_iff lemma nonempty_iff_nonempty : α ≃ β → (nonempty α ↔ nonempty β) | ⟨f, g, _, _⟩ := nonempty.congr f g protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw r₁ } @[simp] theorem symm_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by { simp [equiv.symm], rw l₁ } @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem symm_symm_apply (e : α ≃ β) (a : α) : e.symm.symm a = e a := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by { rw [← set.image_comp], simp } protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply symm_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.symm_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_symm_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂.to_fun ∘ f ∘ e₁.inv_fun, inv_fun := λ f, e₂.inv_fun ∘ f ∘ e₁.to_fun, left_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.left_inv, e₁.left_inv] }, right_inv := λ f, funext $ λ x, by { dsimp, rw [e₂.right_inv, e₁.right_inv] } } @[simp] lemma arrow_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (f : α₁ → β₁) (x : α₂) : arrow_congr e₁ e₂ f x = (e₂ $ f $ e₁.symm x) := rfl lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_apply (e : α ≃ β) (f : α → α) (x : β) : e.conj f x = (e $ f $ e.symm x) := rfl @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section @[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by { funext x, cases x, refl }, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by { cases u, refl }⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2), λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [symm_apply_apply, symm_apply_apply], λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_symm_apply, apply_symm_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := rfl @[simp] def prod_comm (α β : Sort*) : α × β ≃ β × α := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : α × empty ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : empty × α ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : α × pempty ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : pempty × α ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by { cases e₁, cases e₂, refl } @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by { cases e₁, cases e₂, refl } @[simp] lemma sum_congr_symm {α β γ δ : Type u} (e : α ≃ β) (f : γ ≃ δ) (x) : (equiv.sum_congr e f).symm x = (equiv.sum_congr (e.symm) (f.symm)) x := by { cases e, cases f, cases x; refl } def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : α ⊕ empty ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : empty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : α ⊕ pempty ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by { rcases s with _ | ⟨⟨⟩⟩, refl }, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : pempty ⊕ α ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def sigma_preimage_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, x.2.1, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : sigma β, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := λ f x y, f ⟨x,y⟩, inv_fun := λ f x, f x.1 x.2, left_inv := λ f, funext $ λ ⟨x,y⟩, rfl, right_inv := λ f, funext $ λ x, funext $ λ y, rfl } end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ α × β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by { funext p, cases p, refl }⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by { funext s, cases s; refl }, λ p, by { cases p, refl }⟩ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ α × (unit ⊕ unit) : prod_comm _ _ ... ≃ (α × unit) ⊕ (α × unit) : prod_sum_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α := unique.of_surjective e.symm.surjective def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype def subtype_congr {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x.1, (h _).1 x.2⟩, λ y, ⟨e.symm y.1, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.eq' $ by simp, λ ⟨y, h⟩, subtype.eq' $ by simp⟩ def subtype_congr_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : subtype p ≃ subtype q := subtype_congr (equiv.refl _) e @[simp] lemma subtype_congr_right_mk {p q : α → Prop} (e : ∀x, p x ↔ q x) {x : α} (h : p x) : subtype_congr_right e ⟨x, h⟩ = ⟨x, (e x).1 h⟩ := rfl def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := subtype_congr e $ by simp def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl α) (assume a, h ▸ iff.rfl) def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr_prop h def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_congr_right $ λ x, exists_prop /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_congr_right $ assume x, ⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩ /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_preimage_equiv f def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_congr_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.eq' rfl }⟩ end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ @[simp] lemma univ_apply {α : Type u} (x : @univ α) : equiv.set.univ α x = x := rfl @[simp] lemma univ_symm_apply {α : Type u} (x : α) : (equiv.set.univ α).symm x = ⟨x, trivial⟩ := rfl protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x.1 then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x.1, or.inl x.2⟩ | (sum.inr x) := ⟨x.1, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg (show ↑a ∉ s, by finish [set.ext_iff]) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x.1, h ▸ x.2⟩, inv_fun := λ x, ⟨x.1, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } @[simp] lemma of_eq_apply {α : Type u} {s t : set α} (h : s = t) (a : s) : equiv.set.of_eq h a = ⟨a, h ▸ a.2⟩ := rfl @[simp] lemma of_eq_symm_apply {α : Type u} {s t : set α} (h : s = t) (a : t) : (equiv.set.of_eq h).symm a = ⟨a, h.symm ▸ a.2⟩ := rfl protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.ext_iff]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) protected def sum_compl {α} (s : set α) [decidable_pred s] : s ⊕ (-s : set α) ≃ α := calc s ⊕ (-s : set α) ≃ ↥(s ∪ -s) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred s] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred s] (x : -s) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ -s : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred s] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ -s : set α)) ∈ -s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := ⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem f h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (λ x y hx hy hxy, H hxy) @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := { to_fun := λ x, ⟨f x, mem_range_self _⟩, inv_fun := λ x, classical.some x.2, left_inv := λ x, H (classical.some_spec (show f x ∈ range f, from mem_range_self _)), right_inv := λ x, subtype.eq $ classical.some_spec x.2 } @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := rfl protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x.1 } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases b = a; simp [swap_apply_def, *] } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique α) ≃ unique α := { to_fun := λ h, h.default, inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient
8487f85fd1d6edf7f29ac4420cd23b18c045983e
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/normed_space/basic.lean
4219b578c00fc7b66bc95c4d1172bbebd7fceeee
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
88,663
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.algebra.subalgebra import order.liminf_limsup import topology.algebra.group_completion import topology.instances.nnreal import topology.metric_space.completion import topology.sequences import topology.locally_constant.algebra import topology.continuous_function.algebra /-! # Normed spaces Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory of `semi_normed_group` and we specialize to `normed_group` at the end. -/ variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} noncomputable theory open filter metric open_locale topological_space big_operators nnreal ennreal uniformity /-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to be extended in more interesting classes specifying the properties of the norm. -/ class has_norm (α : Type*) := (norm : α → ℝ) export has_norm (norm) notation `∥` e `∥` := norm e /-- A seminormed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a pseudometric space structure. -/ class semi_normed_group (α : Type*) extends has_norm α, add_comm_group α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines a metric space structure. -/ class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) /-- A normed group is a seminormed group. -/ @[priority 100] -- see Note [lower instance priority] instance normed_group.to_semi_normed_group [β : normed_group α] : semi_normed_group α := { ..β } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- Construct a seminormed group from a translation invariant pseudodistance -/ def semi_normed_group.of_add_dist' [has_norm α] [add_comm_group α] [pseudo_metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : semi_normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 } end } /-- A seminormed group can be built from a seminorm that satisfies algebraic properties. This is formalised in this structure. -/ structure semi_normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_zero : ∥(0 : α)∥ = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- Constructing a seminormed group from core properties of a seminorm, i.e., registering the pseudodistance and the pseudometric space structure from the seminorm properties. -/ noncomputable def semi_normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : semi_normed_group.core α) : semi_normed_group α := { dist := λ x y, ∥x - y∥, dist_eq := assume x y, by refl, dist_self := assume x, by simp [C.norm_zero], dist_triangle := assume x y z, calc ∥x - z∥ = ∥x - y + (y - z)∥ : by rw sub_add_sub_cancel ... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _, dist_comm := assume x y, calc ∥x - y∥ = ∥ -(y - x)∥ : by simp ... = ∥y - x∥ : by { rw [C.norm_neg] } } instance : normed_group punit := { norm := function.const _ 0, dist_eq := λ _ _, rfl, } @[simp] lemma punit.norm_eq_zero (r : punit) : ∥r∥ = 0 := rfl instance : normed_group ℝ := { norm := λ x, abs x, dist_eq := assume x y, rfl } lemma real.norm_eq_abs (r : ℝ) : ∥r∥ = abs r := rfl section semi_normed_group variables [semi_normed_group α] [semi_normed_group β] lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ := semi_normed_group.dist_eq _ _ lemma dist_eq_norm' (g h : α) : dist g h = ∥h - g∥ := by rw [dist_comm, dist_eq_norm] @[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ := by rw [dist_eq_norm, sub_zero] @[simp] lemma dist_zero_left : dist (0:α) = norm := funext $ λ g, by rw [dist_comm, dist_zero_right] lemma tendsto_norm_cocompact_at_top [proper_space α] : tendsto norm (cocompact α) at_top := by simpa only [dist_zero_right] using tendsto_dist_right_cocompact_at_top (0:α) lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ := by simpa only [dist_eq_norm] using dist_comm g h @[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ := by simpa using norm_sub_rev 0 g @[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ := by simp [dist_eq_norm] @[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ := by simp [dist_eq_norm] @[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h := by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev] @[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ := by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg] @[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ := by simpa only [sub_eq_add_neg] using dist_add_right _ _ _ /-- **Triangle inequality** for the norm. -/ lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 (-h) lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ + g₂∥ ≤ n₁ + n₂ := le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂) lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ := le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) : dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ := by simpa only [sub_eq_add_neg, dist_neg_neg] using dist_add_add_le g₁ (-g₂) h₁ (-h₂) lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ} (H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) : dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ := le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂) lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) : abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) := by simpa only [dist_add_left, dist_add_right, dist_comm h₂] using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂) @[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ := by { rw[←dist_zero_right], exact dist_nonneg } @[simp] lemma norm_zero : ∥(0:α)∥ = 0 := by rw [← dist_zero_right, dist_self] @[nontriviality] lemma norm_of_subsingleton [subsingleton α] (x : α) : ∥x∥ = 0 := by rw [subsingleton.elim x 0, norm_zero] lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥ ≤ ∑ a in s, ∥ f a ∥ := finset.le_sum_of_subadditive norm norm_zero norm_add_le lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) : ∥∑ b in s, f b∥ ≤ ∑ b in s, n b := le_trans (norm_sum_le s f) (finset.sum_le_sum h) lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ := by simpa [dist_eq_norm] using dist_triangle g 0 h lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) : ∥g₁ - g₂∥ ≤ n₁ + n₂ := le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂) lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ := by { rw dist_eq_norm, apply norm_sub_le } lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ := by simpa [dist_eq_norm] using abs_dist_sub_le g h 0 lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ := le_trans (le_abs_self _) (abs_norm_sub_norm_le g h) lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ := abs_norm_sub_norm_le g h lemma norm_le_insert (u v : α) : ∥v∥ ≤ ∥u∥ + ∥u - v∥ := calc ∥v∥ = ∥u - (u - v)∥ : by abel ... ≤ ∥u∥ + ∥u - v∥ : norm_sub_le u _ lemma norm_le_insert' (u v : α) : ∥u∥ ≤ ∥v∥ + ∥u - v∥ := by { rw norm_sub_rev, exact norm_le_insert v u } lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} := set.ext $ assume a, by simp lemma mem_ball_iff_norm {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥h - g∥ < r := by rw [mem_ball, dist_eq_norm] lemma add_mem_ball_iff_norm {g h : α} {r : ℝ} : g + h ∈ ball g r ↔ ∥h∥ < r := by rw [mem_ball_iff_norm, add_sub_cancel'] lemma mem_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ ball g r ↔ ∥g - h∥ < r := by rw [mem_ball', dist_eq_norm] @[simp] lemma mem_ball_0_iff {ε : ℝ} {x : α} : x ∈ ball (0 : α) ε ↔ ∥x∥ < ε := by rw [mem_ball, dist_zero_right] lemma mem_closed_ball_iff_norm {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥h - g∥ ≤ r := by rw [mem_closed_ball, dist_eq_norm] lemma add_mem_closed_ball_iff_norm {g h : α} {r : ℝ} : g + h ∈ closed_ball g r ↔ ∥h∥ ≤ r := by rw [mem_closed_ball_iff_norm, add_sub_cancel'] lemma mem_closed_ball_iff_norm' {g h : α} {r : ℝ} : h ∈ closed_ball g r ↔ ∥g - h∥ ≤ r := by rw [mem_closed_ball', dist_eq_norm] lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) : ∥h∥ ≤ ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H } lemma norm_le_norm_add_const_of_dist_le {a b : α} {c : ℝ} (h : dist a b ≤ c) : ∥a∥ ≤ ∥b∥ + c := norm_le_of_mem_closed_ball h lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) : ∥h∥ < ∥g∥ + r := calc ∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right] ... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _ ... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H } lemma norm_lt_norm_add_const_of_dist_lt {a b : α} {c : ℝ} (h : dist a b < c) : ∥a∥ < ∥b∥ + c := norm_lt_of_mem_ball h lemma bounded_iff_forall_norm_le {s : set α} : bounded s ↔ ∃ C, ∀ x ∈ s, ∥x∥ ≤ C := begin rw bounded_iff_subset_ball (0 : α), exact exists_congr (λ r, by simp [(⊆), set.subset]), end @[simp] lemma mem_sphere_iff_norm (v w : α) (r : ℝ) : w ∈ sphere v r ↔ ∥w - v∥ = r := by simp [dist_eq_norm] @[simp] lemma mem_sphere_zero_iff_norm {w : α} {r : ℝ} : w ∈ sphere (0:α) r ↔ ∥w∥ = r := by simp [dist_eq_norm] @[simp] lemma norm_eq_of_mem_sphere {r : ℝ} (x : sphere (0:α) r) : ∥(x:α)∥ = r := mem_sphere_zero_iff_norm.mp x.2 lemma ne_zero_of_norm_pos {g : α} : 0 < ∥ g ∥ → g ≠ 0 := begin intros hpos hzero, rw [hzero, norm_zero] at hpos, exact lt_irrefl 0 hpos, end lemma nonzero_of_mem_sphere {r : ℝ} (hr : 0 < r) (x : sphere (0:α) r) : (x:α) ≠ 0 := begin refine ne_zero_of_norm_pos _, rwa norm_eq_of_mem_sphere x, end lemma nonzero_of_mem_unit_sphere (x : sphere (0:α) 1) : (x:α) ≠ 0 := by { apply nonzero_of_mem_sphere, norm_num } /-- We equip the sphere, in a seminormed group, with a formal operation of negation, namely the antipodal map. -/ instance {r : ℝ} : has_neg (sphere (0:α) r) := { neg := λ w, ⟨-↑w, by simp⟩ } @[simp] lemma coe_neg_sphere {r : ℝ} (v : sphere (0:α) r) : (((-v) : sphere _ _) : α) = - (v:α) := rfl namespace isometric /-- Addition `y ↦ y + x` as an `isometry`. -/ protected def add_right (x : α) : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _, .. equiv.add_right x } @[simp] lemma add_right_to_equiv (x : α) : (isometric.add_right x).to_equiv = equiv.add_right x := rfl @[simp] lemma coe_add_right (x : α) : (isometric.add_right x : α → α) = λ y, y + x := rfl lemma add_right_apply (x y : α) : (isometric.add_right x : α → α) y = y + x := rfl @[simp] lemma add_right_symm (x : α) : (isometric.add_right x).symm = isometric.add_right (-x) := ext $ λ y, rfl /-- Addition `y ↦ x + y` as an `isometry`. -/ protected def add_left (x : α) : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _, to_equiv := equiv.add_left x } @[simp] lemma add_left_to_equiv (x : α) : (isometric.add_left x).to_equiv = equiv.add_left x := rfl @[simp] lemma coe_add_left (x : α) : ⇑(isometric.add_left x) = (+) x := rfl @[simp] lemma add_left_symm (x : α) : (isometric.add_left x).symm = isometric.add_left (-x) := ext $ λ y, rfl variable (α) /-- Negation `x ↦ -x` as an `isometry`. -/ protected def neg : α ≃ᵢ α := { isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _, to_equiv := equiv.neg α } variable {α} @[simp] lemma neg_symm : (isometric.neg α).symm = isometric.neg α := rfl @[simp] lemma neg_to_equiv : (isometric.neg α).to_equiv = equiv.neg α := rfl @[simp] lemma coe_neg : ⇑(isometric.neg α) = has_neg.neg := rfl end isometric theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} : tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε := metric.tendsto_nhds.trans $ by simp only [dist_zero_right] lemma normed_group.tendsto_nhds_nhds {f : α → β} {x : α} {y : β} : tendsto f (𝓝 x) (𝓝 y) ↔ ∀ ε > 0, ∃ δ > 0, ∀ x', ∥x' - x∥ < δ → ∥f x' - y∥ < ε := by simp_rw [metric.tendsto_nhds_nhds, dist_eq_norm] lemma normed_group.cauchy_seq_iff {u : ℕ → α} : cauchy_seq u ↔ ∀ ε > 0, ∃ N, ∀ m n, N ≤ m → N ≤ n → ∥u m - u n∥ < ε := by simp [metric.cauchy_seq_iff, dist_eq_norm] lemma cauchy_seq.add {u v : ℕ → α} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u + v) := begin rw normed_group.cauchy_seq_iff at *, intros ε ε_pos, rcases hu (ε/2) (half_pos ε_pos) with ⟨Nu, hNu⟩, rcases hv (ε/2) (half_pos ε_pos) with ⟨Nv, hNv⟩, use max Nu Nv, intros m n hm hn, replace hm := max_le_iff.mp hm, replace hn := max_le_iff.mp hn, calc ∥(u + v) m - (u + v) n∥ = ∥u m + v m - (u n + v n)∥ : rfl ... = ∥(u m - u n) + (v m - v n)∥ : by abel ... ≤ ∥u m - u n∥ + ∥v m - v n∥ : norm_add_le _ _ ... < ε : by linarith only [hNu m n hm.1 hn.1, hNv m n hm.2 hn.2] end open finset lemma cauchy_seq_sum_of_eventually_eq {u v : ℕ → α} {N : ℕ} (huv : ∀ n ≥ N, u n = v n) (hv : cauchy_seq (λ n, ∑ k in range (n+1), v k)) : cauchy_seq (λ n, ∑ k in range (n + 1), u k) := begin let d : ℕ → α := λ n, ∑ k in range (n + 1), (u k - v k), rw show (λ n, ∑ k in range (n + 1), u k) = d + (λ n, ∑ k in range (n + 1), v k), by { ext n, simp [d] }, have : ∀ n ≥ N, d n = d N, { intros n hn, dsimp [d], rw eventually_constant_sum _ hn, intros m hm, simp [huv m hm] }, exact (tendsto_at_top_of_eventually_const this).cauchy_seq.add hv end /-- A homomorphism `f` of seminormed groups is Lipschitz, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of (semi)normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.lipschitz_of_bound (f : α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := lipschitz_with.of_dist_le' $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma lipschitz_on_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} : lipschitz_on_with C f s ↔ ∀ (x ∈ s) (y ∈ s), ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_on_with_iff_dist_le_mul, dist_eq_norm] lemma lipschitz_on_with.norm_sub_le {f : α → β} {C : ℝ≥0} {s : set α} (h : lipschitz_on_with C f s) {x y : α} (x_in : x ∈ s) (y_in : y ∈ s) : ∥f x - f y∥ ≤ C * ∥x - y∥ := lipschitz_on_with_iff_norm_sub_le.mp h x x_in y y_in lemma lipschitz_with_iff_norm_sub_le {f : α → β} {C : ℝ≥0} : lipschitz_with C f ↔ ∀ x y, ∥f x - f y∥ ≤ C * ∥x - y∥ := by simp only [lipschitz_with_iff_dist_le_mul, dist_eq_norm] /-- A homomorphism `f` of seminormed groups is continuous, if there exists a constant `C` such that for all `x`, one has `∥f x∥ ≤ C * ∥x∥`. The analogous condition for a linear map of normed spaces is in `normed_space.operator_norm`. -/ lemma add_monoid_hom.continuous_of_bound (f : α →+ β) (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous lemma is_compact.exists_bound_of_continuous_on {γ : Type*} [topological_space γ] {s : set γ} (hs : is_compact s) {f : γ → α} (hf : continuous_on f s) : ∃ C, ∀ x ∈ s, ∥f x∥ ≤ C := begin have : bounded (f '' s) := (hs.image_of_continuous_on hf).bounded, rcases bounded_iff_forall_norm_le.1 this with ⟨C, hC⟩, exact ⟨C, λ x hx, hC _ (set.mem_image_of_mem _ hx)⟩, end lemma add_monoid_hom.isometry_iff_norm (f : α →+ β) : isometry f ↔ ∀ x, ∥f x∥ = ∥x∥ := begin simp only [isometry_emetric_iff_metric, dist_eq_norm, ← f.map_sub], refine ⟨λ h x, _, λ h x y, h _⟩, simpa using h x 0 end lemma add_monoid_hom.isometry_of_norm (f : α →+ β) (hf : ∀ x, ∥f x∥ = ∥x∥) : isometry f := f.isometry_iff_norm.2 hf lemma controlled_sum_of_mem_closure {s : add_subgroup α} {g : α} (hg : g ∈ closure (s : set α)) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ v : ℕ → α, tendsto (λ n, ∑ i in range (n+1), v i) at_top (𝓝 g) ∧ (∀ n, v n ∈ s) ∧ ∥v 0 - g∥ < b 0 ∧ ∀ n > 0, ∥v n∥ < b n := begin obtain ⟨u : ℕ → α, u_in : ∀ n, u n ∈ s, lim_u : tendsto u at_top (𝓝 g)⟩ := mem_closure_iff_seq_limit.mp hg, obtain ⟨n₀, hn₀⟩ : ∃ n₀, ∀ n ≥ n₀, ∥u n - g∥ < b 0, { have : {x | ∥x - g∥ < b 0} ∈ 𝓝 g, { simp_rw ← dist_eq_norm, exact metric.ball_mem_nhds _ (b_pos _) }, exact filter.tendsto_at_top'.mp lim_u _ this }, set z : ℕ → α := λ n, u (n + n₀), have lim_z : tendsto z at_top (𝓝 g) := lim_u.comp (tendsto_add_at_top_nat n₀), have mem_𝓤 : ∀ n, {p : α × α | ∥p.1 - p.2∥ < b (n + 1)} ∈ 𝓤 α := λ n, by simpa [← dist_eq_norm] using metric.dist_mem_uniformity (b_pos $ n+1), obtain ⟨φ : ℕ → ℕ, φ_extr : strict_mono φ, hφ : ∀ n, ∥z (φ $ n + 1) - z (φ n)∥ < b (n + 1)⟩ := lim_z.cauchy_seq.subseq_mem mem_𝓤, set w : ℕ → α := z ∘ φ, have hw : tendsto w at_top (𝓝 g), from lim_z.comp φ_extr.tendsto_at_top, set v : ℕ → α := λ i, if i = 0 then w 0 else w i - w (i - 1), refine ⟨v, tendsto.congr (finset.eq_sum_range_sub' w) hw , _, hn₀ _ (n₀.le_add_left _), _⟩, { rintro ⟨⟩, { change w 0 ∈ s, apply u_in }, { apply s.sub_mem ; apply u_in }, }, { intros l hl, obtain ⟨k, rfl⟩ : ∃ k, l = k+1, exact nat.exists_eq_succ_of_ne_zero (ne_of_gt hl), apply hφ }, end lemma controlled_sum_of_mem_closure_range {j : α →+ β} {h : β} (Hh : h ∈ (closure $ (j.range : set β))) {b : ℕ → ℝ} (b_pos : ∀ n, 0 < b n) : ∃ g : ℕ → α, tendsto (λ n, ∑ i in range (n+1), j (g i)) at_top (𝓝 h) ∧ ∥j (g 0) - h∥ < b 0 ∧ ∀ n > 0, ∥j (g n)∥ < b n := begin rcases controlled_sum_of_mem_closure Hh b_pos with ⟨v, sum_v, v_in, hv₀, hv_pos⟩, choose g hg using v_in, change ∀ (n : ℕ), j (g n) = v n at hg, refine ⟨g, by simpa [← hg] using sum_v, by simpa [hg 0] using hv₀, λ n hn, by simpa [hg] using hv_pos n hn⟩ end section nnnorm /-- Auxiliary class, endowing a type `α` with a function `nnnorm : α → ℝ≥0`. -/ class has_nnnorm (α : Type*) := (nnnorm : α → ℝ≥0) export has_nnnorm (nnnorm) notation `∥`e`∥₊` := nnnorm e @[priority 100] -- see Note [lower instance priority] instance semi_normed_group.to_has_nnnorm : has_nnnorm α := ⟨λ a, ⟨norm a, norm_nonneg a⟩⟩ @[simp, norm_cast] lemma coe_nnnorm (a : α) : (∥a∥₊ : ℝ) = norm a := rfl lemma nndist_eq_nnnorm (a b : α) : nndist a b = ∥a - b∥₊ := nnreal.eq $ dist_eq_norm _ _ @[simp] lemma nnnorm_zero : ∥(0 : α)∥₊ = 0 := nnreal.eq norm_zero lemma nnnorm_add_le (g h : α) : ∥g + h∥₊ ≤ ∥g∥₊ + ∥h∥₊ := nnreal.coe_le_coe.2 $ norm_add_le g h @[simp] lemma nnnorm_neg (g : α) : ∥-g∥₊ = ∥g∥₊ := nnreal.eq $ norm_neg g lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist ∥g∥₊ ∥h∥₊ ≤ ∥g - h∥₊ := nnreal.coe_le_coe.2 $ dist_norm_norm_le g h lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (∥x∥₊ : ℝ≥0∞) := ennreal.of_real_eq_coe_nnreal _ lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (∥x - y∥₊ : ℝ≥0∞) := by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm] lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (∥x∥₊ : ℝ≥0∞) := by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero] lemma mem_emetric_ball_0_iff {x : β} {r : ℝ≥0∞} : x ∈ emetric.ball (0 : β) r ↔ ↑∥x∥₊ < r := by rw [emetric.mem_ball, edist_eq_coe_nnnorm] lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) : nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ := nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂ lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) : edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ := by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le } lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥∑ a in s, f a∥₊ ≤ ∑ a in s, ∥f a∥₊ := finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le lemma add_monoid_hom.lipschitz_of_bound_nnnorm (f : α →+ β) (C : ℝ≥0) (h : ∀ x, ∥f x∥₊ ≤ C * ∥x∥₊) : lipschitz_with C f := @real.to_nnreal_coe C ▸ f.lipschitz_of_bound C h end nnnorm lemma lipschitz_with.neg {α : Type*} [pseudo_emetric_space α] {K : ℝ≥0} {f : α → β} (hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) := λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y lemma lipschitz_with.add {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x + g x) := λ x y, calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_add_add_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.sub {α : Type*} [pseudo_emetric_space α] {Kf : ℝ≥0} {f : α → β} (hf : lipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (λ x, f x - g x) := by simpa only [sub_eq_add_neg] using hf.add hg.neg lemma antilipschitz_with.add_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg g) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) := begin refine antilipschitz_with.of_le_mul_dist (λ x y, _), rw [nnreal.coe_inv, ← div_eq_inv_mul], rw le_div_iff (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK), rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul], calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) : sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y) ... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _) end lemma antilipschitz_with.add_sub_lipschitz_with {α : Type*} [pseudo_metric_space α] {Kf : ℝ≥0} {f : α → β} (hf : antilipschitz_with Kf f) {Kg : ℝ≥0} {g : α → β} (hg : lipschitz_with Kg (g - f)) (hK : Kg < Kf⁻¹) : antilipschitz_with (Kf⁻¹ - Kg)⁻¹ g := by simpa only [pi.sub_apply, add_sub_cancel'_right] using hf.add_lipschitz_with hg hK /-- A group homomorphism from an `add_comm_group` to a `semi_normed_group` induces a `semi_normed_group` structure on the domain. See note [reducible non-instances] -/ @[reducible] def semi_normed_group.induced [add_comm_group γ] (f : γ →+ α) : semi_normed_group γ := { norm := λ x, ∥f x∥, dist_eq := λ x y, by simpa only [add_monoid_hom.map_sub, ← dist_eq_norm], .. pseudo_metric_space.induced f semi_normed_group.to_pseudo_metric_space, } /-- A subgroup of a seminormed group is also a seminormed group, with the restriction of the norm. -/ instance add_subgroup.semi_normed_group (s : add_subgroup α) : semi_normed_group s := semi_normed_group.induced s.subtype /-- If `x` is an element of a subgroup `s` of a seminormed group `E`, its norm in `s` is equal to its norm in `E`. -/ @[simp] lemma coe_norm_subgroup {E : Type*} [semi_normed_group E] {s : add_subgroup E} (x : s) : ∥x∥ = ∥(x:E)∥ := rfl /-- A submodule of a seminormed group is also a seminormed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.semi_normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : semi_normed_group s := { norm := λx, norm (x : E), dist_eq := λx y, dist_eq_norm (x : E) (y : E) } /-- If `x` is an element of a submodule `s` of a normed group `E`, its norm in `E` is equal to its norm in `s`. See note [implicit instance arguments]. -/ @[simp, norm_cast] lemma submodule.norm_coe {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : s) : ∥(x : E)∥ = ∥x∥ := rfl @[simp] lemma submodule.norm_mk {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [semi_normed_group E] {_ : module 𝕜 E} {s : submodule 𝕜 E} (x : E) (hx : x ∈ s) : ∥(⟨x, hx⟩ : s)∥ = ∥x∥ := rfl /-- seminormed group instance on the product of two seminormed groups, using the sup norm. -/ instance prod.semi_normed_group : semi_normed_group (α × β) := { norm := λx, max ∥x.1∥ ∥x.2∥, dist_eq := assume (x y : α × β), show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] } lemma prod.semi_norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnsemi_norm_def (x : α × β) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.semi_norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma semi_norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma semi_norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma semi_norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- seminormed group instance on the product of finitely many seminormed groups, using the sup norm. -/ instance pi.semi_normed_group {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] : semi_normed_group (Πi, π i) := { norm := λf, ((finset.sup finset.univ (λ b, ∥f b∥₊) : ℝ≥0) : ℝ), dist_eq := assume x y, congr_arg (coe : ℝ≥0 → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a, show nndist (x a) (y a) = ∥x a - y a∥₊, from nndist_eq_nnnorm _ _ } /-- The seminorm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_semi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The seminorm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_semi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma semi_norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, semi_normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_semi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_semi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnsemi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_semi_norm_const a lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} : tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥f e - b∥) a (𝓝 0) := by { convert tendsto_iff_dist_tendsto_zero, simp [dist_eq_norm] } lemma is_bounded_under_of_tendsto {l : filter ι} {f : ι → α} {c : α} (h : filter.tendsto f l (𝓝 c)) : is_bounded_under (≤) l (λ x, ∥f x∥) := ⟨∥c∥ + 1, @tendsto.eventually ι α f _ _ (λ k, ∥k∥ ≤ ∥c∥ + 1) h (filter.eventually_iff_exists_mem.mpr ⟨metric.closed_ball c 1, metric.closed_ball_mem_nhds c zero_lt_one, λ y hy, norm_le_norm_add_const_of_dist_le hy⟩)⟩ lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} : tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥f e∥) a (𝓝 0) := by { rw [tendsto_iff_norm_tendsto_zero], simp only [sub_zero] } /-- Special case of the sandwich theorem: if the norm of `f` is eventually bounded by a real function `g` which tends to `0`, then `f` tends to `0`. In this pair of lemmas (`squeeze_zero_norm'` and `squeeze_zero_norm`), following a convention of similar lemmas in `topology.metric_space.basic` and `topology.algebra.ordered`, the `'` version is phrased using "eventually" and the non-`'` version is phrased absolutely. -/ lemma squeeze_zero_norm' {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ᶠ n in t₀, ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := tendsto_zero_iff_norm_tendsto_zero.mpr (squeeze_zero' (eventually_of_forall (λ n, norm_nonneg _)) h h') /-- Special case of the sandwich theorem: if the norm of `f` is bounded by a real function `g` which tends to `0`, then `f` tends to `0`. -/ lemma squeeze_zero_norm {f : γ → α} {g : γ → ℝ} {t₀ : filter γ} (h : ∀ (n:γ), ∥f n∥ ≤ g n) (h' : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero_norm' (eventually_of_forall h) h' lemma tendsto_norm_sub_self (x : α) : tendsto (λ g : α, ∥g - x∥) (𝓝 x) (𝓝 0) := by simpa [dist_eq_norm] using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (x:α)) (𝓝 x) _) lemma tendsto_norm {x : α} : tendsto (λg : α, ∥g∥) (𝓝 x) (𝓝 ∥x∥) := by simpa using tendsto_id.dist (tendsto_const_nhds : tendsto (λ g, (0:α)) _ _) lemma tendsto_norm_zero : tendsto (λg : α, ∥g∥) (𝓝 0) (𝓝 0) := by simpa using tendsto_norm_sub_self (0:α) @[continuity] lemma continuous_norm : continuous (λg:α, ∥g∥) := by simpa using continuous_id.dist (continuous_const : continuous (λ g, (0:α))) @[continuity] lemma continuous_nnnorm : continuous (λ (a : α), ∥a∥₊) := continuous_subtype_mk _ continuous_norm lemma lipschitz_with_one_norm : lipschitz_with 1 (norm : α → ℝ) := by simpa only [dist_zero_left] using lipschitz_with.dist_right (0 : α) lemma uniform_continuous_norm : uniform_continuous (norm : α → ℝ) := lipschitz_with_one_norm.uniform_continuous lemma uniform_continuous_nnnorm : uniform_continuous (λ (a : α), ∥a∥₊) := uniform_continuous_subtype_mk uniform_continuous_norm _ section variables {l : filter γ} {f : γ → α} {a : α} lemma filter.tendsto.norm {a : α} (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) := tendsto_norm.comp h lemma filter.tendsto.nnnorm (h : tendsto f l (𝓝 a)) : tendsto (λ x, ∥f x∥₊) l (𝓝 (∥a∥₊)) := tendsto.comp continuous_nnnorm.continuous_at h end section variables [topological_space γ] {f : γ → α} {s : set γ} {a : γ} {b : α} lemma continuous.norm (h : continuous f) : continuous (λ x, ∥f x∥) := continuous_norm.comp h lemma continuous.nnnorm (h : continuous f) : continuous (λ x, ∥f x∥₊) := continuous_nnnorm.comp h lemma continuous_at.norm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥) a := h.norm lemma continuous_at.nnnorm (h : continuous_at f a) : continuous_at (λ x, ∥f x∥₊) a := h.nnnorm lemma continuous_within_at.norm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥) s a := h.norm lemma continuous_within_at.nnnorm (h : continuous_within_at f s a) : continuous_within_at (λ x, ∥f x∥₊) s a := h.nnnorm lemma continuous_on.norm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥) s := λ x hx, (h x hx).norm lemma continuous_on.nnnorm (h : continuous_on f s) : continuous_on (λ x, ∥f x∥₊) s := λ x hx, (h x hx).nnnorm end /-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/ lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α} (h : tendsto (λ y, ∥f y∥) l at_top) (x : α) : ∀ᶠ y in l, f y ≠ x := begin have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)), refine this.mono (λ y hy hxy, _), subst x, exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy) end /-- A seminormed group is a uniform additive group, i.e., addition and subtraction are uniformly continuous. -/ @[priority 100] -- see Note [lower instance priority] instance normed_uniform_group : uniform_add_group α := ⟨(lipschitz_with.prod_fst.sub lipschitz_with.prod_snd).uniform_continuous⟩ @[priority 100] -- see Note [lower instance priority] instance normed_top_monoid : has_continuous_add α := by apply_instance -- short-circuit type class inference @[priority 100] -- see Note [lower instance priority] instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference lemma nat.norm_cast_le [has_one α] : ∀ n : ℕ, ∥(n : α)∥ ≤ n * ∥(1 : α)∥ | 0 := by simp | (n + 1) := by { rw [n.cast_succ, n.cast_succ, add_mul, one_mul], exact norm_add_le_of_le (nat.norm_cast_le n) le_rfl } lemma semi_normed_group.mem_closure_iff {s : set α} {x : α} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, ∥x - y∥ < ε := by simp [metric.mem_closure_iff, dist_eq_norm] lemma norm_le_zero_iff' [separated_space α] {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := begin have : g = 0 ↔ g ∈ closure ({0} : set α), by simpa only [separated_space.out, mem_id_rel, sub_zero] using group_separation_rel g (0 : α), rw [this, semi_normed_group.mem_closure_iff], simp [forall_lt_iff_le'] end lemma norm_eq_zero_iff' [separated_space α] {g : α} : ∥g∥ = 0 ↔ g = 0 := begin conv_rhs { rw ← norm_le_zero_iff' }, split ; intro h, { rw h }, { exact le_antisymm h (norm_nonneg g) } end lemma norm_pos_iff' [separated_space α] {g : α} : 0 < ∥g∥ ↔ g ≠ 0 := begin rw lt_iff_le_and_ne, simp only [norm_nonneg, true_and], rw [ne_comm], exact not_iff_not_of_iff (norm_eq_zero_iff'), end end semi_normed_group section normed_group /-- Construct a normed group from a translation invariant distance -/ def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α] (H1 : ∀ x:α, ∥x∥ = dist x 0) (H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α := { dist_eq := λ x y, begin rw H1, apply le_antisymm, { rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }, { have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this } end } /-- A normed group can be built from a norm that satisfies algebraic properties. This is formalised in this structure. -/ structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop := (norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0) (triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥) (norm_neg : ∀ x : α, ∥-x∥ = ∥x∥) /-- The `semi_normed_group.core` induced by a `normed_group.core`. -/ lemma normed_group.core.to_semi_normed_group.core {α : Type*} [add_comm_group α] [has_norm α] (C : normed_group.core α) : semi_normed_group.core α := { norm_zero := (C.norm_eq_zero_iff 0).2 rfl, triangle := C.triangle, norm_neg := C.norm_neg } /-- Constructing a normed group from core properties of a norm, i.e., registering the distance and the metric space structure from the norm properties. -/ noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α] (C : normed_group.core α) : normed_group α := { eq_of_dist_eq_zero := λ x y h, begin rw [dist_eq_norm] at h, exact sub_eq_zero.mp ((C.norm_eq_zero_iff _).1 h) end ..semi_normed_group.of_core α (normed_group.core.to_semi_normed_group.core C) } variables [normed_group α] [normed_group β] @[simp] lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 := dist_zero_right g ▸ dist_eq_zero @[simp] lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 := dist_zero_right g ▸ dist_pos @[simp] lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 := by { rw [← dist_zero_right], exact dist_le_zero } lemma eq_of_norm_sub_le_zero {g h : α} (a : ∥g - h∥ ≤ 0) : g = h := by rwa [← sub_eq_zero, ← norm_le_zero_iff] lemma eq_of_norm_sub_eq_zero {u v : α} (h : ∥u - v∥ = 0) : u = v := begin apply eq_of_dist_eq_zero, rwa dist_eq_norm end lemma norm_sub_eq_zero_iff {u v : α} : ∥u - v∥ = 0 ↔ u = v := begin convert dist_eq_zero, rwa dist_eq_norm end @[simp] lemma nnnorm_eq_zero {a : α} : ∥a∥₊ = 0 ↔ a = 0 := by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero] /-- An injective group homomorphism from an `add_comm_group` to a `normed_group` induces a `normed_group` structure on the domain. See note [reducible non-instances]. -/ @[reducible] def normed_group.induced [add_comm_group γ] (f : γ →+ α) (h : function.injective f) : normed_group γ := { .. semi_normed_group.induced f, .. metric_space.induced f h normed_group.to_metric_space, } /-- A subgroup of a normed group is also a normed group, with the restriction of the norm. -/ instance add_subgroup.normed_group (s : add_subgroup α) : normed_group s := normed_group.induced s.subtype subtype.coe_injective /-- A submodule of a normed group is also a normed group, with the restriction of the norm. See note [implicit instance arguments]. -/ instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜} {E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s := { ..submodule.semi_normed_group s } /-- normed group instance on the product of two normed groups, using the sup norm. -/ instance prod.normed_group : normed_group (α × β) := { ..prod.semi_normed_group } lemma prod.norm_def (x : α × β) : ∥x∥ = (max ∥x.1∥ ∥x.2∥) := rfl lemma prod.nnnorm_def (x : α × β) : ∥x∥₊ = max (∥x.1∥₊) (∥x.2∥₊) := by { have := x.norm_def, simp only [← coe_nnnorm] at this, exact_mod_cast this } lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ := le_max_left _ _ lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ := le_max_right _ _ lemma norm_prod_le_iff {x : α × β} {r : ℝ} : ∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r := max_le_iff /-- normed group instance on the product of finitely many normed groups, using the sup norm. -/ instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] : normed_group (Πi, π i) := { ..pi.semi_normed_group } /-- The norm of an element in a product space is `≤ r` if and only if the norm of each component is. -/ lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r) {x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r := by simp only [← dist_zero_right, dist_pi_le_iff hr, pi.zero_apply] /-- The norm of an element in a product space is `< r` if and only if the norm of each component is. -/ lemma pi_norm_lt_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 < r) {x : Πi, π i} : ∥x∥ < r ↔ ∀i, ∥x i∥ < r := by simp only [← dist_zero_right, dist_pi_lt_iff hr, pi.zero_apply] lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) : ∥x i∥ ≤ ∥x∥ := (pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i @[simp] lemma pi_norm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥ = ∥a∥ := by simpa only [← dist_zero_right] using dist_pi_const a 0 @[simp] lemma pi_nnnorm_const [nonempty ι] [fintype ι] (a : α) : ∥(λ i : ι, a)∥₊ = ∥a∥₊ := nnreal.eq $ pi_norm_const a lemma tendsto_norm_nhds_within_zero : tendsto (norm : α → ℝ) (𝓝[{0}ᶜ] 0) (𝓝[set.Ioi 0] 0) := (continuous_norm.tendsto' (0 : α) 0 norm_zero).inf $ tendsto_principal_principal.2 $ λ x, norm_pos_iff.2 end normed_group section semi_normed_ring /-- A seminormed ring is a ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_ring (α : Type*) extends has_norm α, ring α, pseudo_metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b) /-- A normed ring is a seminormed ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_semi_normed_ring [β : normed_ring α] : semi_normed_ring α := { ..β } /-- A seminormed commutative ring is a commutative ring endowed with a seminorm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class semi_normed_comm_ring (α : Type*) extends semi_normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a commutative ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/ class normed_comm_ring (α : Type*) extends normed_ring α := (mul_comm : ∀ x y : α, x * y = y * x) /-- A normed commutative ring is a seminormed commutative ring. -/ @[priority 100] -- see Note [lower instance priority] instance normed_comm_ring.to_semi_normed_comm_ring [β : normed_comm_ring α] : semi_normed_comm_ring α := { ..β } instance : normed_comm_ring punit := { norm_mul := λ _ _, by simp, ..punit.normed_group, ..punit.comm_ring, } /-- A mixin class with the axiom `∥1∥ = 1`. Many `normed_ring`s and all `normed_field`s satisfy this axiom. -/ class norm_one_class (α : Type*) [has_norm α] [has_one α] : Prop := (norm_one : ∥(1:α)∥ = 1) export norm_one_class (norm_one) attribute [simp] norm_one @[simp] lemma nnnorm_one [semi_normed_group α] [has_one α] [norm_one_class α] : ∥(1 : α)∥₊ = 1 := nnreal.eq norm_one @[priority 100] -- see Note [lower instance priority] instance semi_normed_comm_ring.to_comm_ring [β : semi_normed_comm_ring α] : comm_ring α := { ..β } @[priority 100] -- see Note [lower instance priority] instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β } @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring.to_semi_normed_group [β : semi_normed_ring α] : semi_normed_group α := { ..β } instance prod.norm_one_class [normed_group α] [has_one α] [norm_one_class α] [normed_group β] [has_one β] [norm_one_class β] : norm_one_class (α × β) := ⟨by simp [prod.norm_def]⟩ variables [semi_normed_ring α] lemma norm_mul_le (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) := semi_normed_ring.norm_mul _ _ /-- A subalgebra of a seminormed ring is also a seminormed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.semi_normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [semi_normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : semi_normed_ring s := { norm_mul := λ a b, norm_mul_le a.1 b.1, ..s.to_submodule.semi_normed_group } /-- A subalgebra of a normed ring is also a normed ring, with the restriction of the norm. See note [implicit instance arguments]. -/ instance subalgebra.normed_ring {𝕜 : Type*} {_ : comm_ring 𝕜} {E : Type*} [normed_ring E] {_ : algebra 𝕜 E} (s : subalgebra 𝕜 E) : normed_ring s := { ..s.semi_normed_ring } lemma list.norm_prod_le' : ∀ {l : list α}, l ≠ [] → ∥l.prod∥ ≤ (l.map norm).prod | [] h := (h rfl).elim | [a] _ := by simp | (a :: b :: l) _ := begin rw [list.map_cons, list.prod_cons, @list.prod_cons _ _ _ ∥a∥], refine le_trans (norm_mul_le _ _) (mul_le_mul_of_nonneg_left _ (norm_nonneg _)), exact list.norm_prod_le' (list.cons_ne_nil b l) end lemma list.norm_prod_le [norm_one_class α] : ∀ l : list α, ∥l.prod∥ ≤ (l.map norm).prod | [] := by simp | (a::l) := list.norm_prod_le' (list.cons_ne_nil a l) lemma finset.norm_prod_le' {α : Type*} [normed_comm_ring α] (s : finset ι) (hs : s.nonempty) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, have : l.map f ≠ [], by simpa using hs, simpa using list.norm_prod_le' this end lemma finset.norm_prod_le {α : Type*} [normed_comm_ring α] [norm_one_class α] (s : finset ι) (f : ι → α) : ∥∏ i in s, f i∥ ≤ ∏ i in s, ∥f i∥ := begin rcases s with ⟨⟨l⟩, hl⟩, simpa using (l.map f).norm_prod_le end /-- If `α` is a seminormed ring, then `∥a^n∥≤ ∥a∥^n` for `n > 0`. See also `norm_pow_le`. -/ lemma norm_pow_le' (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n | 1 h := by simp | (n+2) h := by { rw [pow_succ _ (n+1), pow_succ _ (n+1)], exact le_trans (norm_mul_le a (a^(n+1))) (mul_le_mul (le_refl _) (norm_pow_le' (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _)) } /-- If `α` is a seminormed ring with `∥1∥=1`, then `∥a^n∥≤ ∥a∥^n`. See also `norm_pow_le'`. -/ lemma norm_pow_le [norm_one_class α] (a : α) : ∀ (n : ℕ), ∥a^n∥ ≤ ∥a∥^n | 0 := by simp | (n+1) := norm_pow_le' a n.zero_lt_succ lemma eventually_norm_pow_le (a : α) : ∀ᶠ (n:ℕ) in at_top, ∥a ^ n∥ ≤ ∥a∥ ^ n := eventually_at_top.mpr ⟨1, λ b h, norm_pow_le' a (nat.succ_le_iff.mp h)⟩ /-- In a seminormed ring, the left-multiplication `add_monoid_hom` is bounded. -/ lemma mul_left_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_left x y∥ ≤ ∥x∥ * ∥y∥ := norm_mul_le x /-- In a seminormed ring, the right-multiplication `add_monoid_hom` is bounded. -/ lemma mul_right_bound (x : α) : ∀ (y:α), ∥add_monoid_hom.mul_right x y∥ ≤ ∥x∥ * ∥y∥ := λ y, by {rw mul_comm, convert norm_mul_le y x} /-- Seminormed ring structure on the product of two seminormed rings, using the sup norm. -/ instance prod.semi_normed_ring [semi_normed_ring β] : semi_normed_ring (α × β) := { norm_mul := assume x y, calc ∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl ... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl ... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) : max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2)) ... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm] ... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] ... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp [max_comm] ... = (∥x∥*∥y∥) : rfl, ..prod.semi_normed_group } end semi_normed_ring section normed_ring variables [normed_ring α] lemma units.norm_pos [nontrivial α] (x : units α) : 0 < ∥(x:α)∥ := norm_pos_iff.mpr (units.ne_zero x) /-- Normed ring structure on the product of two normed rings, using the sup norm. -/ instance prod.normed_ring [normed_ring β] : normed_ring (α × β) := { norm_mul := norm_mul_le, ..prod.semi_normed_group } end normed_ring @[priority 100] -- see Note [lower instance priority] instance semi_normed_ring_top_monoid [semi_normed_ring α] : has_continuous_mul α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ begin have : ∀ e : α × α, ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥, { intro e, calc ∥e.1 * e.2 - x.1 * x.2∥ ≤ ∥e.1 * (e.2 - x.2) + (e.1 - x.1) * x.2∥ : by rw [mul_sub, sub_mul, sub_add_sub_cancel] ... ≤ ∥e.1∥ * ∥e.2 - x.2∥ + ∥e.1 - x.1∥ * ∥x.2∥ : norm_add_le_of_le (norm_mul_le _ _) (norm_mul_le _ _) }, refine squeeze_zero (λ e, norm_nonneg _) this _, convert ((continuous_fst.tendsto x).norm.mul ((continuous_snd.tendsto x).sub tendsto_const_nhds).norm).add (((continuous_fst.tendsto x).sub tendsto_const_nhds).norm.mul _), show tendsto _ _ _, from tendsto_const_nhds, simp end ⟩ /-- A seminormed ring is a topological ring. -/ @[priority 100] -- see Note [lower instance priority] instance semi_normed_top_ring [semi_normed_ring α] : topological_ring α := ⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $ have ∀ e : α, -e - -x = -(e - x), by intro; simp, by simp only [this, norm_neg]; apply tendsto_norm_sub_self ⟩ /-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/ class normed_field (α : Type*) extends has_norm α, field α, metric_space α := (dist_eq : ∀ x y, dist x y = norm (x - y)) (norm_mul' : ∀ a b, norm (a * b) = norm a * norm b) /-- A nondiscrete normed field is a normed field in which there is an element of norm different from `0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication by the powers of any element, and thus to relate algebra and topology. -/ class nondiscrete_normed_field (α : Type*) extends normed_field α := (non_trivial : ∃x:α, 1<∥x∥) namespace normed_field section normed_field variables [normed_field α] @[simp] lemma norm_mul (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ := normed_field.norm_mul' a b @[priority 100] -- see Note [lower instance priority] instance to_normed_comm_ring : normed_comm_ring α := { norm_mul := λ a b, (norm_mul a b).le, ..‹normed_field α› } @[priority 900] instance to_norm_one_class : norm_one_class α := ⟨mul_left_cancel' (mt norm_eq_zero.1 (@one_ne_zero α _ _)) $ by rw [← norm_mul, mul_one, mul_one]⟩ @[simp] lemma nnnorm_mul (a b : α) : ∥a * b∥₊ = ∥a∥₊ * ∥b∥₊ := nnreal.eq $ norm_mul a b /-- `norm` as a `monoid_hom`. -/ @[simps] def norm_hom : monoid_with_zero_hom α ℝ := ⟨norm, norm_zero, norm_one, norm_mul⟩ /-- `nnnorm` as a `monoid_hom`. -/ @[simps] def nnnorm_hom : monoid_with_zero_hom α ℝ≥0 := ⟨nnnorm, nnnorm_zero, nnnorm_one, nnnorm_mul⟩ @[simp] lemma norm_pow (a : α) : ∀ (n : ℕ), ∥a ^ n∥ = ∥a∥ ^ n := (norm_hom.to_monoid_hom : α →* ℝ).map_pow a @[simp] lemma nnnorm_pow (a : α) (n : ℕ) : ∥a ^ n∥₊ = ∥a∥₊ ^ n := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_pow a n @[simp] lemma norm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥ = ∏ b in s, ∥f b∥ := (norm_hom.to_monoid_hom : α →* ℝ).map_prod f s @[simp] lemma nnnorm_prod (s : finset β) (f : β → α) : ∥∏ b in s, f b∥₊ = ∏ b in s, ∥f b∥₊ := (nnnorm_hom.to_monoid_hom : α →* ℝ≥0).map_prod f s @[simp] lemma norm_div (a b : α) : ∥a / b∥ = ∥a∥ / ∥b∥ := (norm_hom : monoid_with_zero_hom α ℝ).map_div a b @[simp] lemma nnnorm_div (a b : α) : ∥a / b∥₊ = ∥a∥₊ / ∥b∥₊ := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_div a b @[simp] lemma norm_inv (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ := (norm_hom : monoid_with_zero_hom α ℝ).map_inv' a @[simp] lemma nnnorm_inv (a : α) : ∥a⁻¹∥₊ = ∥a∥₊⁻¹ := nnreal.eq $ by simp @[simp] lemma norm_fpow : ∀ (a : α) (n : ℤ), ∥a^n∥ = ∥a∥^n := (norm_hom : monoid_with_zero_hom α ℝ).map_fpow @[simp] lemma nnnorm_fpow : ∀ (a : α) (n : ℤ), ∥a ^ n∥₊ = ∥a∥₊ ^ n := (nnnorm_hom : monoid_with_zero_hom α ℝ≥0).map_fpow @[priority 100] -- see Note [lower instance priority] instance : has_continuous_inv' α := begin refine ⟨λ r r0, tendsto_iff_norm_tendsto_zero.2 _⟩, have r0' : 0 < ∥r∥ := norm_pos_iff.2 r0, rcases exists_between r0' with ⟨ε, ε0, εr⟩, have : ∀ᶠ e in 𝓝 r, ∥e⁻¹ - r⁻¹∥ ≤ ∥r - e∥ / ∥r∥ / ε, { filter_upwards [(is_open_lt continuous_const continuous_norm).eventually_mem εr], intros e he, have e0 : e ≠ 0 := norm_pos_iff.1 (ε0.trans he), calc ∥e⁻¹ - r⁻¹∥ = ∥r - e∥ / ∥r∥ / ∥e∥ : by field_simp [mul_comm] ... ≤ ∥r - e∥ / ∥r∥ / ε : div_le_div_of_le_left (div_nonneg (norm_nonneg _) (norm_nonneg _)) ε0 he.le }, refine squeeze_zero' (eventually_of_forall $ λ _, norm_nonneg _) this _, refine (continuous_const.sub continuous_id).norm.div_const.div_const.tendsto' _ _ _, simp end end normed_field variables (α) [nondiscrete_normed_field α] lemma exists_one_lt_norm : ∃x : α, 1 < ∥x∥ := ‹nondiscrete_normed_field α›.non_trivial lemma exists_norm_lt_one : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 := begin rcases exists_one_lt_norm α with ⟨y, hy⟩, refine ⟨y⁻¹, _, _⟩, { simp only [inv_eq_zero, ne.def, norm_pos_iff], rintro rfl, rw norm_zero at hy, exact lt_asymm zero_lt_one hy }, { simp [inv_lt_one hy] } end lemma exists_lt_norm (r : ℝ) : ∃ x : α, r < ∥x∥ := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in ⟨w^n, by rwa norm_pow⟩ lemma exists_norm_lt {r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r := let ⟨w, hw⟩ := exists_one_lt_norm α in let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in ⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _}, by rwa norm_fpow⟩ variable {α} @[instance] lemma punctured_nhds_ne_bot (x : α) : ne_bot (𝓝[{x}ᶜ] x) := begin rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff], rintros ε ε0, rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩, refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩, rwa [dist_comm, dist_eq_norm, add_sub_cancel'], end @[instance] lemma nhds_within_is_unit_ne_bot : ne_bot (𝓝[{x : α | is_unit x}] 0) := by simpa only [is_unit_iff_ne_zero] using punctured_nhds_ne_bot (0:α) end normed_field instance : normed_field ℝ := { norm_mul' := abs_mul, .. real.normed_group } instance : nondiscrete_normed_field ℝ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } namespace real lemma norm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥ = x := abs_of_nonneg hx lemma norm_of_nonpos {x : ℝ} (hx : x ≤ 0) : ∥x∥ = -x := abs_of_nonpos hx @[simp] lemma norm_coe_nat (n : ℕ) : ∥(n : ℝ)∥ = n := abs_of_nonneg n.cast_nonneg @[simp] lemma nnnorm_coe_nat (n : ℕ) : ∥(n : ℝ)∥₊ = n := nnreal.eq $ by simp @[simp] lemma norm_two : ∥(2 : ℝ)∥ = 2 := abs_of_pos (@zero_lt_two ℝ _ _) @[simp] lemma nnnorm_two : ∥(2 : ℝ)∥₊ = 2 := nnreal.eq $ by simp lemma nnnorm_of_nonneg {x : ℝ} (hx : 0 ≤ x) : ∥x∥₊ = ⟨x, hx⟩ := nnreal.eq $ norm_of_nonneg hx lemma ennnorm_eq_of_real {x : ℝ} (hx : 0 ≤ x) : (∥x∥₊ : ℝ≥0∞) = ennreal.of_real x := by { rw [← of_real_norm_eq_coe_nnnorm, norm_of_nonneg hx] } end real namespace nnreal open_locale nnreal @[simp] lemma norm_eq (x : ℝ≥0) : ∥(x : ℝ)∥ = x := by rw [real.norm_eq_abs, x.abs_eq] @[simp] lemma nnnorm_eq (x : ℝ≥0) : ∥(x : ℝ)∥₊ = x := nnreal.eq $ real.norm_of_nonneg x.2 end nnreal @[simp] lemma norm_norm [semi_normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ := real.norm_of_nonneg (norm_nonneg _) @[simp] lemma nnnorm_norm [semi_normed_group α] (a : α) : ∥∥a∥∥₊ = ∥a∥₊ := by simpa [real.nnnorm_of_nonneg (norm_nonneg a)] /-- A restatement of `metric_space.tendsto_at_top` in terms of the norm. -/ lemma normed_group.tendsto_at_top [nonempty α] [semilattice_sup α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N ≤ n → ∥f n - b∥ < ε := (at_top_basis.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) /-- A variant of `normed_group.tendsto_at_top` that uses `∃ N, ∀ n > N, ...` rather than `∃ N, ∀ n ≥ N, ...` -/ lemma normed_group.tendsto_at_top' [nonempty α] [semilattice_sup α] [no_top_order α] {β : Type*} [semi_normed_group β] {f : α → β} {b : β} : tendsto f at_top (𝓝 b) ↔ ∀ ε, 0 < ε → ∃ N, ∀ n, N < n → ∥f n - b∥ < ε := (at_top_basis_Ioi.tendsto_iff metric.nhds_basis_ball).trans (by simp [dist_eq_norm]) instance : normed_comm_ring ℤ := { norm := λ n, ∥(n : ℝ)∥, norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul], dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub], mul_comm := mul_comm } @[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl lemma int.norm_eq_abs (n : ℤ) : ∥n∥ = abs n := rfl lemma nnreal.coe_nat_abs (n : ℤ) : (n.nat_abs : ℝ≥0) = ∥n∥₊ := nnreal.eq $ calc ((n.nat_abs : ℝ≥0) : ℝ) = (n.nat_abs : ℤ) : by simp only [int.cast_coe_nat, nnreal.coe_nat_cast] ... = abs n : by simp only [← int.abs_eq_nat_abs, int.cast_abs] ... = ∥n∥ : rfl instance : norm_one_class ℤ := ⟨by simp [← int.norm_cast_real]⟩ instance : normed_field ℚ := { norm := λ r, ∥(r : ℝ)∥, norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul], dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] } instance : nondiscrete_normed_field ℚ := { non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ } @[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl @[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ := by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast -- Now that we've installed the norm on `ℤ`, -- we can state some lemmas about `nsmul` and `gsmul`. section variables [semi_normed_group α] lemma norm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥ ≤ n * ∥a∥ := begin induction n with n ih, { simp only [norm_zero, nat.cast_zero, zero_mul, zero_smul] }, simp only [nat.succ_eq_add_one, add_smul, add_mul, one_mul, nat.cast_add, nat.cast_one, one_nsmul], exact norm_add_le_of_le ih le_rfl end lemma norm_gsmul_le (n : ℤ) (a : α) : ∥n • a∥ ≤ ∥n∥ * ∥a∥ := begin induction n with n n, { simp only [int.of_nat_eq_coe, gsmul_coe_nat], convert norm_nsmul_le n a, exact nat.abs_cast n }, { simp only [int.neg_succ_of_nat_coe, neg_smul, norm_neg, gsmul_coe_nat], convert norm_nsmul_le n.succ a, exact nat.abs_cast n.succ, } end lemma nnnorm_nsmul_le (n : ℕ) (a : α) : ∥n • a∥₊ ≤ n * ∥a∥₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul, nnreal.coe_nat_cast] using norm_nsmul_le n a lemma nnnorm_gsmul_le (n : ℤ) (a : α) : ∥n • a∥₊ ≤ ∥n∥₊ * ∥a∥₊ := by simpa only [←nnreal.coe_le_coe, nnreal.coe_mul] using norm_gsmul_le n a end section semi_normed_space section prio set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[semi_normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A seminormed space over a normed field is a vector space endowed with a seminorm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class semi_normed_space (α : Type*) (β : Type*) [normed_field α] [semi_normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) set_option extends_priority 920 -- Here, we set a rather high priority for the instance `[normed_space α β] : module α β` -- to take precedence over `semiring.to_module` as this leads to instance paths with better -- unification properties. /-- A normed space over a normed field is a vector space endowed with a norm which satisfies the equality `∥c • x∥ = ∥c∥ ∥x∥`. We require only `∥c • x∥ ≤ ∥c∥ ∥x∥` in the definition, then prove `∥c • x∥ = ∥c∥ ∥x∥` in `norm_smul`. -/ class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β] extends module α β := (norm_smul_le : ∀ (a:α) (b:β), ∥a • b∥ ≤ ∥a∥ * ∥b∥) /-- A normed space is a seminormed space. -/ @[priority 100] -- see Note [lower instance priority] instance normed_space.to_semi_normed_space [normed_field α] [normed_group β] [γ : normed_space α β] : semi_normed_space α β := { ..γ } end prio variables [normed_field α] [semi_normed_group β] instance normed_field.to_normed_space : normed_space α α := { norm_smul_le := λ a b, le_of_eq (normed_field.norm_mul a b) } lemma norm_smul [semi_normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ := begin by_cases h : s = 0, { simp [h] }, { refine le_antisymm (semi_normed_space.norm_smul_le s x) _, calc ∥s∥ * ∥x∥ = ∥s∥ * ∥s⁻¹ • s • x∥ : by rw [inv_smul_smul' h] ... ≤ ∥s∥ * (∥s⁻¹∥ * ∥s • x∥) : mul_le_mul_of_nonneg_left (semi_normed_space.norm_smul_le _ _) (norm_nonneg _) ... = ∥s • x∥ : by rw [normed_field.norm_inv, ← mul_assoc, mul_inv_cancel (mt norm_eq_zero.1 h), one_mul] } end @[simp] lemma abs_norm_eq_norm (z : β) : abs ∥z∥ = ∥z∥ := (abs_eq (norm_nonneg z)).mpr (or.inl rfl) lemma dist_smul [semi_normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y := by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub] lemma nnnorm_smul [semi_normed_space α β] (s : α) (x : β) : ∥s • x∥₊ = ∥s∥₊ * ∥x∥₊ := nnreal.eq $ norm_smul s x lemma nndist_smul [semi_normed_space α β] (s : α) (x y : β) : nndist (s • x) (s • y) = ∥s∥₊ * nndist x y := nnreal.eq $ dist_smul s x y lemma norm_smul_of_nonneg [semi_normed_space ℝ β] {t : ℝ} (ht : 0 ≤ t) (x : β) : ∥t • x∥ = t * ∥x∥ := by rw [norm_smul, real.norm_eq_abs, abs_of_nonneg ht] variables {E : Type*} [semi_normed_group E] [semi_normed_space α E] variables {F : Type*} [semi_normed_group F] [semi_normed_space α F] @[priority 100] -- see Note [lower instance priority] instance semi_normed_space.has_continuous_smul : has_continuous_smul α E := begin refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ }, refine squeeze_zero (λ _, norm_nonneg _) _ _, { exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ }, { intro q, rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul], exact norm_add_le _ _ }, { conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr, rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] }, exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add (tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) } end theorem eventually_nhds_norm_smul_sub_lt (c : α) (x : E) {ε : ℝ} (h : 0 < ε) : ∀ᶠ y in 𝓝 x, ∥c • (y - x)∥ < ε := have tendsto (λ y, ∥c • (y - x)∥) (𝓝 x) (𝓝 0), from (continuous_const.smul (continuous_id.sub continuous_const)).norm.tendsto' _ _ (by simp), this.eventually (gt_mem_nhds h) theorem closure_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : closure (ball x r) = closed_ball x r := begin refine set.subset.antisymm closure_ball_subset_closed_ball (λ y hy, _), have : continuous_within_at (λ c : ℝ, c • (y - x) + x) (set.Ico 0 1) 1 := ((continuous_id.smul continuous_const).add continuous_const).continuous_within_at, convert this.mem_closure _ _, { rw [one_smul, sub_add_cancel] }, { simp [closure_Ico (@zero_lt_one ℝ _ _), zero_le_one] }, { rintros c ⟨hc0, hc1⟩, rw [set.mem_preimage, mem_ball, dist_eq_norm, add_sub_cancel, norm_smul, real.norm_eq_abs, abs_of_nonneg hc0, mul_comm, ← mul_one r], rw [mem_closed_ball, dist_eq_norm] at hy, apply mul_lt_mul'; assumption } end theorem frontier_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (ball x r) = sphere x r := begin rw [frontier, closure_ball x hr, is_open_ball.interior_eq], ext x, exact (@eq_iff_le_not_lt ℝ _ _ _).symm end theorem interior_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : interior (closed_ball x r) = ball x r := begin refine set.subset.antisymm _ ball_subset_interior_closed_ball, intros y hy, rcases le_iff_lt_or_eq.1 (mem_closed_ball.1 $ interior_subset hy) with hr|rfl, { exact hr }, set f : ℝ → E := λ c : ℝ, c • (y - x) + x, suffices : f ⁻¹' closed_ball x (dist y x) ⊆ set.Icc (-1) 1, { have hfc : continuous f := (continuous_id.smul continuous_const).add continuous_const, have hf1 : (1:ℝ) ∈ f ⁻¹' (interior (closed_ball x $ dist y x)), by simpa [f], have h1 : (1:ℝ) ∈ interior (set.Icc (-1:ℝ) 1) := interior_mono this (preimage_interior_subset_interior_preimage hfc hf1), contrapose h1, simp }, intros c hc, rw [set.mem_Icc, ← abs_le, ← real.norm_eq_abs, ← mul_le_mul_right hr], simpa [f, dist_eq_norm, norm_smul] using hc end theorem frontier_closed_ball [semi_normed_space ℝ E] (x : E) {r : ℝ} (hr : 0 < r) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball x hr, closed_ball_diff_ball] variables (α) lemma ne_neg_of_mem_sphere [char_zero α] {r : ℝ} (hr : 0 < r) (x : sphere (0:E) r) : x ≠ - x := λ h, nonzero_of_mem_sphere hr x (eq_zero_of_eq_neg α (by { conv_lhs {rw h}, simp })) lemma ne_neg_of_mem_unit_sphere [char_zero α] (x : sphere (0:E) 1) : x ≠ - x := ne_neg_of_mem_sphere α (by norm_num) x variables {α} open normed_field /-- The product of two seminormed spaces is a seminormed space, with the sup norm. -/ instance prod.semi_normed_space : semi_normed_space α (E × F) := { norm_smul_le := λ s x, le_of_eq $ by simp [prod.semi_norm_def, norm_smul, mul_max_of_nonneg], ..prod.normed_group, ..prod.module } /-- The product of finitely many seminormed spaces is a seminormed space, with the sup norm. -/ instance pi.semi_normed_space {E : ι → Type*} [fintype ι] [∀i, semi_normed_group (E i)] [∀i, semi_normed_space α (E i)] : semi_normed_space α (Πi, E i) := { norm_smul_le := λ a f, le_of_eq $ show (↑(finset.sup finset.univ (λ (b : ι), ∥a • f b∥₊)) : ℝ) = ∥a∥₊ * ↑(finset.sup finset.univ (λ (b : ι), ∥f b∥₊)), by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] } /-- A subspace of a seminormed space is also a normed space, with the restriction of the norm. -/ instance submodule.semi_normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [semi_normed_group E] [semi_normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : semi_normed_space 𝕜 s := { norm_smul_le := λc x, le_of_eq $ norm_smul c (x : E) } /-- If there is a scalar `c` with `∥c∥>1`, then any element of with norm different from `0` can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell_semi_normed {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : ∥x∥ ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := begin have xεpos : 0 < ∥x∥/ε := div_pos ((ne.symm hx).le_iff_lt.1 (norm_nonneg x)) εpos, rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩, have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc, have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 }, refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩, show (c ^ (n + 1))⁻¹ ≠ 0, by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff], show ∥(c ^ (n + 1))⁻¹ • x∥ < ε, { rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_lt_iff cnpos, mul_comm, norm_fpow], exact (div_lt_iff εpos).1 (hn.2) }, show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥, { rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, mul_inv_rev', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos), one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm], exact (le_div_iff εpos).1 hn.1 }, show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥, { have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring, rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), gpow_one, this, ← div_eq_inv_mul], exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) } end end semi_normed_space section normed_space variables [normed_field α] variables {E : Type*} [normed_group E] [normed_space α E] variables {F : Type*} [normed_group F] [normed_space α F] open normed_field theorem interior_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : interior (closed_ball x r) = ball x r := begin rcases lt_trichotomy r 0 with hr|rfl|hr, { simp [closed_ball_eq_empty_iff_neg.2 hr, ball_eq_empty_iff_nonpos.2 (le_of_lt hr)] }, { suffices : x ∉ interior {x}, { rw [ball_zero, closed_ball_zero, ← set.subset_empty_iff], intros y hy, obtain rfl : y = x := set.mem_singleton_iff.1 (interior_subset hy), exact this hy }, rw [← set.mem_compl_iff, ← closure_compl], rcases exists_ne (0 : E) with ⟨z, hz⟩, suffices : (λ c : ℝ, x + c • z) 0 ∈ closure ({x}ᶜ : set E), by simpa only [zero_smul, add_zero] using this, have : (0:ℝ) ∈ closure (set.Ioi (0:ℝ)), by simp [closure_Ioi], refine (continuous_const.add (continuous_id.smul continuous_const)).continuous_within_at.mem_closure this _, intros c hc, simp [smul_eq_zero, hz, ne_of_gt hc] }, { exact interior_closed_ball x hr } end theorem frontier_closed_ball' [normed_space ℝ E] [nontrivial E] (x : E) (r : ℝ) : frontier (closed_ball x r) = sphere x r := by rw [frontier, closure_closed_ball, interior_closed_ball' x r, closed_ball_diff_ball] variables {α} /-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows up in applications. -/ lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) : ∃d:α, d ≠ 0 ∧ ∥d • x∥ < ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) := rescale_to_shell_semi_normed hc εpos (ne_of_lt (norm_pos_iff.2 hx)).symm /-- The product of two normed spaces is a normed space, with the sup norm. -/ instance : normed_space α (E × F) := { ..prod.semi_normed_space } /-- The product of finitely many normed spaces is a normed space, with the sup norm. -/ instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)] [∀i, normed_space α (E i)] : normed_space α (Πi, E i) := { ..pi.semi_normed_space } /-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/ instance submodule.normed_space {𝕜 R : Type*} [has_scalar 𝕜 R] [normed_field 𝕜] [ring R] {E : Type*} [normed_group E] [normed_space 𝕜 E] [module R E] [is_scalar_tower 𝕜 R E] (s : submodule R E) : normed_space 𝕜 s := { ..submodule.semi_normed_space s } end normed_space section normed_algebra /-- A seminormed algebra `𝕜'` over `𝕜` is an algebra endowed with a seminorm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of `𝕜` in `𝕜'` is an isometry. -/ class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] extends algebra 𝕜 𝕜' := (norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥) /-- A normed algebra is a seminormed algebra. -/ @[priority 100] -- see Note [lower instance priority] instance normed_algebra.to_semi_normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] : semi_normed_algebra 𝕜 𝕜' := { norm_algebra_map_eq := normed_algebra.norm_algebra_map_eq } @[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [h : semi_normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ := semi_normed_algebra.norm_algebra_map_eq _ /-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/ lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [semi_normed_ring 𝕜'] [semi_normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') := begin refine isometry_emetric_iff_metric.2 (λx y, _), rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq], end variables (𝕜 : Type*) [normed_field 𝕜] variables (𝕜' : Type*) [semi_normed_ring 𝕜'] @[priority 100] instance semi_normed_algebra.to_semi_normed_space [h : semi_normed_algebra 𝕜 𝕜'] : semi_normed_space 𝕜 𝕜' := { norm_smul_le := λ s x, calc ∥s • x∥ = ∥((algebra_map 𝕜 𝕜') s) * x∥ : by { rw h.smul_def', refl } ... ≤ ∥algebra_map 𝕜 𝕜' s∥ * ∥x∥ : semi_normed_ring.norm_mul _ _ ... = ∥s∥ * ∥x∥ : by rw norm_algebra_map_eq, ..h } @[priority 100] instance normed_algebra.to_normed_space (𝕜 : Type*) [normed_field 𝕜] (𝕜' : Type*) [normed_ring 𝕜'] [h : normed_algebra 𝕜 𝕜'] : normed_space 𝕜 𝕜' := { norm_smul_le := semi_normed_space.norm_smul_le, ..h } instance normed_algebra.id : normed_algebra 𝕜 𝕜 := { norm_algebra_map_eq := by simp, .. algebra.id 𝕜} variables (𝕜') [semi_normed_algebra 𝕜 𝕜'] include 𝕜 lemma normed_algebra.norm_one : ∥(1:𝕜')∥ = 1 := by simpa using (norm_algebra_map_eq 𝕜' (1:𝕜)) lemma normed_algebra.norm_one_class : norm_one_class 𝕜' := ⟨normed_algebra.norm_one 𝕜 𝕜'⟩ lemma normed_algebra.zero_ne_one : (0:𝕜') ≠ 1 := begin refine (ne_zero_of_norm_pos _).symm, rw normed_algebra.norm_one 𝕜 𝕜', norm_num, end lemma normed_algebra.nontrivial : nontrivial 𝕜' := ⟨⟨0, 1, normed_algebra.zero_ne_one 𝕜 𝕜'⟩⟩ end normed_algebra section restrict_scalars variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] (E : Type*) [normed_group E] [normed_space 𝕜' E] (F : Type*) [semi_normed_group F] [semi_normed_space 𝕜' F] /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-seminormed space structure induced by a `𝕜'`-seminormed space structure when `𝕜'` is a seminormed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def semi_normed_space.restrict_scalars : semi_normed_space 𝕜 F := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' F } /-- Warning: This declaration should be used judiciously. Please consider using `is_scalar_tower` instead. `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. The type synonym `module.restrict_scalars 𝕜 𝕜' E` will be endowed with this instance by default. -/ def normed_space.restrict_scalars : normed_space 𝕜 E := { norm_smul_le := λc x, le_of_eq $ begin change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥, simp [norm_smul] end, ..restrict_scalars.module 𝕜 𝕜' E } instance {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [I : semi_normed_group F] : semi_normed_group (restrict_scalars 𝕜 𝕜' F) := I instance {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [I : normed_group E] : normed_group (restrict_scalars 𝕜 𝕜' E) := I instance module.restrict_scalars.semi_normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {F : Type*} [normed_field 𝕜'] [semi_normed_group F] [I : semi_normed_space 𝕜' F] : semi_normed_space 𝕜' (restrict_scalars 𝕜 𝕜' F) := I instance module.restrict_scalars.normed_space_orig {𝕜 : Type*} {𝕜' : Type*} {E : Type*} [normed_field 𝕜'] [normed_group E] [I : normed_space 𝕜' E] : normed_space 𝕜' (restrict_scalars 𝕜 𝕜' E) := I instance : semi_normed_space 𝕜 (restrict_scalars 𝕜 𝕜' F) := (semi_normed_space.restrict_scalars 𝕜 𝕜' F : semi_normed_space 𝕜 F) instance : normed_space 𝕜 (restrict_scalars 𝕜 𝕜' E) := (normed_space.restrict_scalars 𝕜 𝕜' E : normed_space 𝕜 E) end restrict_scalars section summable open_locale classical open finset filter variables [semi_normed_group α] [semi_normed_group β] lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} : cauchy_seq (λ s : finset ι, ∑ i in s, f i) ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := begin rw [cauchy_seq_finset_iff_vanishing, nhds_basis_ball.forall_iff], { simp only [ball_0_eq, set.mem_set_of_eq] }, { rintros s t hst ⟨s', hs'⟩, exact ⟨s', λ t' ht', hst $ hs' _ ht'⟩ } end lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} : summable f ↔ ∀ε > (0 : ℝ), ∃s:finset ι, ∀t, disjoint t s → ∥ ∑ i in t, f i ∥ < ε := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm] lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, ∑ i in s, f i) := cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε, let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in ⟨s, assume t ht, have ∥∑ i in t, g i∥ < ε := hs t ht, have nn : 0 ≤ ∑ i in t, g i := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)), lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $ by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩ lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : cauchy_seq (λ s : finset ι, ∑ a in s, f a) := cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _) /-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable with sum `a`. -/ lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥)) {s : γ → finset ι} {p : filter γ} [ne_bot p] (hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, ∑ i in s b, f i) p (𝓝 a)) : has_sum f a := tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hs ha lemma has_sum_iff_tendsto_nat_of_summable_norm {f : ℕ → α} {a : α} (hf : summable (λi, ∥f i∥)) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := ⟨λ h, h.tendsto_sum_nat, λ h, has_sum_of_subseq_of_summable hf tendsto_finset_range h⟩ /-- The direct comparison test for series: if the norm of `f` is bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded [complete_space α] {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) : summable f := by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h } lemma has_sum.norm_le_of_bounded {f : ι → α} {g : ι → ℝ} {a : α} {b : ℝ} (hf : has_sum f a) (hg : has_sum g b) (h : ∀ i, ∥f i∥ ≤ g i) : ∥a∥ ≤ b := le_of_tendsto_of_tendsto' hf.norm hg $ λ s, norm_sum_le_of_le _ $ λ i hi, h i /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `∥f i∥ ≤ g i`, then `∥∑' i, f i∥ ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_norm_bounded {f : ι → α} {g : ι → ℝ} {a : ℝ} (hg : has_sum g a) (h : ∀ i, ∥f i∥ ≤ g i) : ∥∑' i : ι, f i∥ ≤ a := begin by_cases hf : summable f, { exact hf.has_sum.norm_le_of_bounded hg h }, { rw [tsum_eq_zero_of_not_summable hf, norm_zero], exact ge_of_tendsto' hg (λ s, sum_nonneg $ λ i hi, (norm_nonneg _).trans (h i)) } end /-- If `∑' i, ∥f i∥` is summable, then `∥∑' i, f i∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥∑' i, f i∥ ≤ ∑' i, ∥f i∥ := tsum_of_norm_bounded hf.has_sum $ λ i, le_rfl /-- Quantitative result associated to the direct comparison test for series: If `∑' i, g i` is summable, and for all `i`, `nnnorm (f i) ≤ g i`, then `nnnorm (∑' i, f i) ≤ ∑' i, g i`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma tsum_of_nnnorm_bounded {f : ι → α} {g : ι → ℝ≥0} {a : ℝ≥0} (hg : has_sum g a) (h : ∀ i, nnnorm (f i) ≤ g i) : nnnorm (∑' i : ι, f i) ≤ a := begin simp only [← nnreal.coe_le_coe, ← nnreal.has_sum_coe, coe_nnnorm] at *, exact tsum_of_norm_bounded hg h end /-- If `∑' i, nnnorm (f i)` is summable, then `nnnorm (∑' i, f i) ≤ ∑' i, nnnorm (f i)`. Note that we do not assume that `∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/ lemma nnnorm_tsum_le {f : ι → α} (hf : summable (λi, nnnorm (f i))) : nnnorm (∑' i, f i) ≤ ∑' i, nnnorm (f i) := tsum_of_nnnorm_bounded hf.has_sum (λ i, le_rfl) variable [complete_space α] /-- Variant of the direct comparison test for series: if the norm of `f` is eventually bounded by a real function `g` which is summable, then `f` is summable. -/ lemma summable_of_norm_bounded_eventually {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀ᶠ i in cofinite, ∥f i∥ ≤ g i) : summable f := begin replace h := mem_cofinite.1 h, refine h.summable_compl_iff.mp _, refine summable_of_norm_bounded _ (h.summable_compl_iff.mpr hg) _, rintros ⟨a, h'⟩, simpa using h' end lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → ℝ≥0) (hg : summable g) (h : ∀i, ∥f i∥₊ ≤ g i) : summable f := summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i) lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f := summable_of_norm_bounded _ hf (assume i, le_refl _) lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λ a, ∥f a∥₊)) : summable f := summable_of_nnnorm_bounded _ hf (assume i, le_refl _) end summable namespace uniform_space namespace completion variables (V : Type*) instance [uniform_space V] [has_norm V] : has_norm (completion V) := { norm := completion.extension has_norm.norm } @[simp] lemma norm_coe {V} [semi_normed_group V] (v : V) : ∥(v : completion V)∥ = ∥v∥ := completion.extension_coe uniform_continuous_norm v instance [semi_normed_group V] : normed_group (completion V) := { dist_eq := begin intros x y, 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, metric.completion.dist_eq, dist_eq_norm] } end, .. (show add_comm_group (completion V), by apply_instance), .. (show metric_space (completion V), by apply_instance) } end completion end uniform_space namespace locally_constant variables {X Y : Type*} [topological_space X] [topological_space Y] (f : locally_constant X Y) /-- The inclusion of locally-constant functions into continuous functions as a multiplicative monoid hom. -/ @[to_additive "The inclusion of locally-constant functions into continuous functions as an additive monoid hom.", simps] def to_continuous_map_monoid_hom [monoid Y] [has_continuous_mul Y] : locally_constant X Y →* C(X, Y) := { to_fun := coe, map_one' := by { ext, simp, }, map_mul' := λ x y, by { ext, simp, }, } /-- The inclusion of locally-constant functions into continuous functions as a linear map. -/ @[simps] def to_continuous_map_linear_map (R : Type*) [semiring R] [topological_space R] [add_comm_monoid Y] [module R Y] [has_continuous_add Y] [has_continuous_smul R Y] : locally_constant X Y →ₗ[R] C(X, Y) := { to_fun := coe, map_add' := λ x y, by { ext, simp, }, map_smul' := λ x y, by { ext, simp, }, } /-- The inclusion of locally-constant functions into continuous functions as an algebra map. -/ @[simps] def to_continuous_map_alg_hom (R : Type*) [comm_semiring R] [topological_space R] [semiring Y] [algebra R Y] [topological_semiring Y] [has_continuous_smul R Y] : locally_constant X Y →ₐ[R] C(X, Y) := { to_fun := coe, map_one' := by { ext, simp, }, map_mul' := λ x y, by { ext, simp, }, map_zero' := by { ext, simp, }, map_add' := λ x y, by { ext, simp, }, commutes' := λ r, by { ext x, simp [algebra.smul_def], }, } end locally_constant
e3434ae2e67fa0c9b95223c28ebb2930c356f602
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/category/Group/basic.lean
c3727a1eb3ffd813aba77204adfa8a4926f941d7
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
9,209
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.category.Mon.basic import category_theory.endomorphism /-! # Category instances for group, add_group, comm_group, and add_comm_group. We introduce the bundled categories: * `Group` * `AddGroup` * `CommGroup` * `AddCommGroup` along with the relevant forgetful functors between them, and to the bundled monoid categories. -/ universes u v open category_theory /-- The category of groups and group morphisms. -/ @[to_additive AddGroup] def Group : Type (u+1) := bundled group /-- The category of additive groups and group morphisms -/ add_decl_doc AddGroup namespace Group @[to_additive] instance : bundled_hom.parent_projection group.to_monoid := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] Group AddGroup /-- Construct a bundled `Group` from the underlying type and typeclass. -/ @[to_additive] def of (X : Type u) [group X] : Group := bundled.of X /-- Construct a bundled `AddGroup` from the underlying type and typeclass. -/ add_decl_doc AddGroup.of @[to_additive] instance (G : Group) : group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [group R] : (Group.of R : Type u) = R := rfl @[to_additive] instance : has_one Group := ⟨Group.of punit⟩ @[to_additive] instance : inhabited Group := ⟨1⟩ @[to_additive] instance one.unique : unique (1 : Group) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : Group) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[ext, to_additive] lemma ext (G H : Group) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } -- should to_additive do this automatically? attribute [ext] AddGroup.ext @[to_additive has_forget_to_AddMon] instance has_forget_to_Mon : has_forget₂ Group Mon := bundled_hom.forget₂ _ _ end Group /-- The category of commutative groups and group morphisms. -/ @[to_additive AddCommGroup] def CommGroup : Type (u+1) := bundled comm_group /-- The category of additive commutative groups and group morphisms. -/ add_decl_doc AddCommGroup /-- `Ab` is an abbreviation for `AddCommGroup`, for the sake of mathematicians' sanity. -/ abbreviation Ab := AddCommGroup namespace CommGroup @[to_additive] instance : bundled_hom.parent_projection comm_group.to_group := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommGroup AddCommGroup /-- Construct a bundled `CommGroup` from the underlying type and typeclass. -/ @[to_additive] def of (G : Type u) [comm_group G] : CommGroup := bundled.of G /-- Construct a bundled `AddCommGroup` from the underlying type and typeclass. -/ add_decl_doc AddCommGroup.of @[to_additive] instance comm_group_instance (G : CommGroup) : comm_group G := G.str @[simp, to_additive] lemma coe_of (R : Type u) [comm_group R] : (CommGroup.of R : Type u) = R := rfl @[to_additive] instance : has_one CommGroup := ⟨CommGroup.of punit⟩ @[to_additive] instance : inhabited CommGroup := ⟨1⟩ @[to_additive] instance one.unique : unique (1 : CommGroup) := { default := 1, uniq := λ a, begin cases a, refl, end } @[simp, to_additive] lemma one_apply (G H : CommGroup) (g : G) : (1 : G ⟶ H) g = 1 := rfl @[to_additive,ext] lemma ext (G H : CommGroup) (f₁ f₂ : G ⟶ H) (w : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by { ext1, apply w } attribute [ext] AddCommGroup.ext @[to_additive has_forget_to_AddGroup] instance has_forget_to_Group : has_forget₂ CommGroup Group := bundled_hom.forget₂ _ _ @[to_additive has_forget_to_AddCommMon] instance has_forget_to_CommMon : has_forget₂ CommGroup CommMon := induced_category.has_forget₂ (λ G : CommGroup, CommMon.of G) end CommGroup -- This example verifies an improvement possible in Lean 3.8. -- Before that, to have `monoid_hom.map_map` usable by `simp` here, -- we had to mark all the concrete category `has_coe_to_sort` instances reducible. -- Now, it just works. @[to_additive] example {R S : CommGroup} (i : R ⟶ S) (r : R) (h : r = 1) : i r = 1 := by simp [h] namespace AddCommGroup /-- Any element of an abelian group gives a unique morphism from `ℤ` sending `1` to that element. -/ -- Note that because `ℤ : Type 0`, this forces `G : AddCommGroup.{0}`, -- so we write this explicitly to be clear. -- TODO generalize this, requiring a `ulift_instances.lean` file def as_hom {G : AddCommGroup.{0}} (g : G) : (AddCommGroup.of ℤ) ⟶ G := gmultiples_hom G g @[simp] lemma as_hom_apply {G : AddCommGroup.{0}} (g : G) (i : ℤ) : (as_hom g) i = i • g := rfl lemma as_hom_injective {G : AddCommGroup.{0}} : function.injective (@as_hom G) := λ h k w, by convert congr_arg (λ k : (AddCommGroup.of ℤ) ⟶ G, (k : ℤ → G) (1 : ℤ)) w; simp @[ext] lemma int_hom_ext {G : AddCommGroup.{0}} (f g : (AddCommGroup.of ℤ) ⟶ G) (w : f (1 : ℤ) = g (1 : ℤ)) : f = g := add_monoid_hom.ext_int w -- TODO: this argument should be generalised to the situation where -- the forgetful functor is representable. lemma injective_of_mono {G H : AddCommGroup.{0}} (f : G ⟶ H) [mono f] : function.injective f := λ g₁ g₂ h, begin have t0 : as_hom g₁ ≫ f = as_hom g₂ ≫ f := begin ext, simpa [as_hom_apply] using h, end, have t1 : as_hom g₁ = as_hom g₂ := (cancel_mono _).1 t0, apply as_hom_injective t1, end end AddCommGroup variables {X Y : Type u} /-- Build an isomorphism in the category `Group` from a `mul_equiv` between `group`s. -/ @[to_additive add_equiv.to_AddGroup_iso, simps] def mul_equiv.to_Group_iso [group X] [group Y] (e : X ≃* Y) : Group.of X ≅ Group.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddGroup` from an `add_equiv` between `add_group`s. -/ add_decl_doc add_equiv.to_AddGroup_iso /-- Build an isomorphism in the category `CommGroup` from a `mul_equiv` between `comm_group`s. -/ @[to_additive add_equiv.to_AddCommGroup_iso, simps] def mul_equiv.to_CommGroup_iso [comm_group X] [comm_group Y] (e : X ≃* Y) : CommGroup.of X ≅ CommGroup.of Y := { hom := e.to_monoid_hom, inv := e.symm.to_monoid_hom } /-- Build an isomorphism in the category `AddCommGroup` from a `add_equiv` between `add_comm_group`s. -/ add_decl_doc add_equiv.to_AddCommGroup_iso namespace category_theory.iso /-- Build a `mul_equiv` from an isomorphism in the category `Group`. -/ @[to_additive AddGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddGroup`.", simps] def Group_iso_to_mul_equiv {X Y : Group} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id /-- Build a `mul_equiv` from an isomorphism in the category `CommGroup`. -/ @[to_additive AddCommGroup_iso_to_add_equiv "Build an `add_equiv` from an isomorphism in the category `AddCommGroup`.", simps] def CommGroup_iso_to_mul_equiv {X Y : CommGroup} (i : X ≅ Y) : X ≃* Y := i.hom.to_mul_equiv i.inv i.hom_inv_id i.inv_hom_id end category_theory.iso /-- multiplicative equivalences between `group`s are the same as (isomorphic to) isomorphisms in `Group` -/ @[to_additive add_equiv_iso_AddGroup_iso "additive equivalences between `add_group`s are the same as (isomorphic to) isomorphisms in `AddGroup`"] def mul_equiv_iso_Group_iso {X Y : Type u} [group X] [group Y] : (X ≃* Y) ≅ (Group.of X ≅ Group.of Y) := { hom := λ e, e.to_Group_iso, inv := λ i, i.Group_iso_to_mul_equiv, } /-- multiplicative equivalences between `comm_group`s are the same as (isomorphic to) isomorphisms in `CommGroup` -/ @[to_additive add_equiv_iso_AddCommGroup_iso "additive equivalences between `add_comm_group`s are the same as (isomorphic to) isomorphisms in `AddCommGroup`"] def mul_equiv_iso_CommGroup_iso {X Y : Type u} [comm_group X] [comm_group Y] : (X ≃* Y) ≅ (CommGroup.of X ≅ CommGroup.of Y) := { hom := λ e, e.to_CommGroup_iso, inv := λ i, i.CommGroup_iso_to_mul_equiv, } namespace category_theory.Aut /-- The (bundled) group of automorphisms of a type is isomorphic to the (bundled) group of permutations. -/ def iso_perm {α : Type u} : Group.of (Aut α) ≅ Group.of (equiv.perm α) := { hom := ⟨λ g, g.to_equiv, (by tidy), (by tidy)⟩, inv := ⟨λ g, g.to_iso, (by tidy), (by tidy)⟩ } /-- The (unbundled) group of automorphisms of a type is `mul_equiv` to the (unbundled) group of permutations. -/ def mul_equiv_perm {α : Type u} : Aut α ≃* equiv.perm α := iso_perm.Group_iso_to_mul_equiv end category_theory.Aut @[to_additive] instance Group.forget_reflects_isos : reflects_isomorphisms (forget Group.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget Group).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_Group_iso).1⟩, end } @[to_additive] instance CommGroup.forget_reflects_isos : reflects_isomorphisms (forget CommGroup.{u}) := { reflects := λ X Y f _, begin resetI, let i := as_iso ((forget CommGroup).map f), let e : X ≃* Y := { ..f, ..i.to_equiv }, exact ⟨(is_iso.of_iso e.to_CommGroup_iso).1⟩, end }
d6704c060e6ecde3d223f463886d4c2f2207f7ec
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/topology/instances/real.lean
90acbd41fd43b959debde566ee8a57209e569559
[ "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
15,629
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 topology.metric_space.basic import topology.algebra.uniform_group import topology.algebra.ring import ring_theory.subring import group_theory.archimedean import algebra.periodic /-! # Topological properties of ℝ -/ noncomputable theory open classical set filter topological_space metric open_locale classical open_locale topological_space universes u v w variables {α : Type u} {β : Type v} {γ : Type w} instance : metric_space ℚ := metric_space.induced coe rat.cast_injective real.metric_space theorem rat.dist_eq (x y : ℚ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] lemma rat.dist_cast (x y : ℚ) : dist (x : ℝ) y = dist x y := rfl section low_prio -- we want to ignore this instance for the next declaration local attribute [instance, priority 10] int.uniform_space instance : metric_space ℤ := begin letI M := metric_space.induced coe int.cast_injective real.metric_space, refine @metric_space.replace_uniformity _ int.uniform_space M (le_antisymm refl_le_uniformity $ λ r ru, mem_uniformity_dist.2 ⟨1, zero_lt_one, λ a b h, mem_principal_sets.1 ru $ dist_le_zero.1 (_ : (abs (a - b) : ℝ) ≤ 0)⟩), have : (abs (↑a - ↑b) : ℝ) < 1 := h, have : abs (a - b) < 1, by norm_cast at this; assumption, have : abs (a - b) ≤ 0 := (@int.lt_add_one_iff _ 0).mp this, norm_cast, assumption end end low_prio theorem int.dist_eq (x y : ℤ) : dist x y = abs (x - y) := rfl @[norm_cast, simp] theorem int.dist_cast_real (x y : ℤ) : dist (x : ℝ) y = dist x y := rfl @[norm_cast, simp] theorem int.dist_cast_rat (x y : ℤ) : dist (x : ℚ) y = dist x y := by rw [← int.dist_cast_real, ← rat.dist_cast]; congr' 1; norm_cast instance : proper_space ℤ := ⟨ begin intros x r, apply set.finite.is_compact, have : closed_ball x r = coe ⁻¹' (closed_ball (x:ℝ) r) := rfl, simp [this, closed_ball_Icc, set.Icc_ℤ_finite], end ⟩ theorem uniform_continuous_of_rat : uniform_continuous (coe : ℚ → ℝ) := uniform_continuous_comap theorem uniform_embedding_of_rat : uniform_embedding (coe : ℚ → ℝ) := uniform_embedding_comap rat.cast_injective theorem dense_embedding_of_rat : dense_embedding (coe : ℚ → ℝ) := uniform_embedding_of_rat.dense_embedding $ λ x, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε,ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨q, h⟩ := exists_rat_near x ε0 in ⟨_, hε (mem_ball'.2 h), q, rfl⟩ theorem embedding_of_rat : embedding (coe : ℚ → ℝ) := dense_embedding_of_rat.to_embedding theorem continuous_of_rat : continuous (coe : ℚ → ℝ) := uniform_continuous_of_rat.continuous theorem real.uniform_continuous_add : uniform_continuous (λp : ℝ × ℝ, p.1 + p.2) := metric.uniform_continuous_iff.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₂⟩ -- TODO(Mario): Find a way to use rat_add_continuous_lemma theorem rat.uniform_continuous_add : uniform_continuous (λp : ℚ × ℚ, p.1 + p.2) := uniform_embedding_of_rat.to_uniform_inducing.uniform_continuous_iff.2 $ by simp [(∘)]; exact real.uniform_continuous_add.comp ((uniform_continuous_of_rat.comp uniform_continuous_fst).prod_mk (uniform_continuous_of_rat.comp uniform_continuous_snd)) theorem real.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℝ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [real.dist_eq] using h⟩ theorem rat.uniform_continuous_neg : uniform_continuous (@has_neg.neg ℚ _) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨_, ε0, λ a b h, by rw dist_comm at h; simpa [rat.dist_eq] using h⟩ instance : uniform_add_group ℝ := uniform_add_group.mk' real.uniform_continuous_add real.uniform_continuous_neg instance : uniform_add_group ℚ := uniform_add_group.mk' rat.uniform_continuous_add rat.uniform_continuous_neg -- short-circuit type class inference instance : topological_add_group ℝ := by apply_instance instance : topological_add_group ℚ := by apply_instance instance : order_topology ℚ := induced_order_topology _ (λ x y, rat.cast_lt) (@exists_rat_btwn _ _ _) instance : proper_space ℝ := { compact_ball := λx r, by { rw closed_ball_Icc, apply is_compact_Icc } } instance : second_countable_topology ℝ := second_countable_of_proper lemma real.is_topological_basis_Ioo_rat : @is_topological_basis ℝ _ (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_of_open_of_nhds (by simp [is_open_Ioo] {contextual:=tt}) (assume a v hav hv, let ⟨l, u, ⟨hl, hu⟩, h⟩ := mem_nhds_iff_exists_Ioo_subset.mp (is_open.mem_nhds hv hav), ⟨q, hlq, hqa⟩ := exists_rat_btwn hl, ⟨p, hap, hpu⟩ := exists_rat_btwn hu in ⟨Ioo q p, by { simp only [mem_Union], exact ⟨q, p, rat.cast_lt.1 $ hqa.trans hap, rfl⟩ }, ⟨hqa, hap⟩, assume a' ⟨hqa', ha'p⟩, h ⟨hlq.trans hqa', ha'p.trans hpu⟩⟩) /- TODO(Mario): Prove that these are uniform isomorphisms instead of uniform embeddings lemma uniform_embedding_add_rat {r : ℚ} : uniform_embedding (λp:ℚ, p + r) := _ lemma uniform_embedding_mul_rat {q : ℚ} (hq : q ≠ 0) : uniform_embedding ((*) q) := _ -/ lemma real.mem_closure_iff {s : set ℝ} {x : ℝ} : x ∈ closure s ↔ ∀ ε > 0, ∃ y ∈ s, abs (y - x) < ε := by simp [mem_closure_iff_nhds_basis nhds_basis_ball, real.dist_eq] lemma real.uniform_continuous_inv (s : set ℝ) {r : ℝ} (r0 : 0 < r) (H : ∀ x ∈ s, r ≤ abs x) : uniform_continuous (λp:s, p.1⁻¹) := metric.uniform_continuous_iff.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 real.uniform_continuous_abs : uniform_continuous (abs : ℝ → ℝ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b, lt_of_le_of_lt (abs_abs_sub_abs_le_abs_sub _ _)⟩ lemma rat.uniform_continuous_abs : uniform_continuous (abs : ℚ → ℚ) := metric.uniform_continuous_iff.2 $ λ ε ε0, ⟨ε, ε0, λ a b h, lt_of_le_of_lt (by simpa [rat.dist_eq] using abs_abs_sub_abs_le_abs_sub _ _) h⟩ lemma real.tendsto_inv {r : ℝ} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) := by rw ← abs_pos at r0; exact tendsto_of_uniform_continuous_subtype (real.uniform_continuous_inv {x | abs r / 2 < abs x} (half_pos r0) (λ x h, le_of_lt h)) (is_open.mem_nhds ((is_open_lt' (abs r / 2)).preimage continuous_abs) (half_lt_self r0)) lemma real.continuous_inv : continuous (λa:{r:ℝ // r ≠ 0}, a.val⁻¹) := continuous_iff_continuous_at.mpr $ assume ⟨r, hr⟩, tendsto.comp (real.tendsto_inv hr) (continuous_iff_continuous_at.mp continuous_subtype_val _) lemma real.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 real.continuous_inv.comp (continuous_subtype_mk _ hf) lemma real.uniform_continuous_mul_const {x : ℝ} : uniform_continuous ((*) x) := metric.uniform_continuous_iff.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 [real.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 real.uniform_continuous_mul (s : set (ℝ × ℝ)) {r₁ r₂ : ℝ} (H : ∀ x ∈ s, abs (x : ℝ × ℝ).1 < r₁ ∧ abs x.2 < r₂) : uniform_continuous (λp:s, p.1.1 * p.1.2) := metric.uniform_continuous_iff.2 $ λ ε ε0, let ⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abs ε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₂⟩ protected lemma real.continuous_mul : continuous (λp : ℝ × ℝ, p.1 * p.2) := continuous_iff_continuous_at.2 $ λ ⟨a₁, a₂⟩, tendsto_of_uniform_continuous_subtype (real.uniform_continuous_mul ({x | abs x < abs a₁ + 1}.prod {x | abs x < abs a₂ + 1}) (λ x, id)) (is_open.mem_nhds (((is_open_gt' (abs a₁ + 1)).preimage continuous_abs).prod ((is_open_gt' (abs a₂ + 1)).preimage continuous_abs )) ⟨lt_add_one (abs a₁), lt_add_one (abs a₂)⟩) instance : topological_ring ℝ := { continuous_mul := real.continuous_mul, ..real.topological_add_group } instance : topological_semiring ℝ := by apply_instance -- short-circuit type class inference lemma rat.continuous_mul : continuous (λp : ℚ × ℚ, p.1 * p.2) := embedding_of_rat.continuous_iff.2 $ by simp [(∘)]; exact real.continuous_mul.comp ((continuous_of_rat.comp continuous_fst).prod_mk (continuous_of_rat.comp continuous_snd)) instance : topological_ring ℚ := { continuous_mul := rat.continuous_mul, ..rat.topological_add_group } theorem real.ball_eq_Ioo (x ε : ℝ) : ball x ε = Ioo (x - ε) (x + ε) := set.ext $ λ y, by rw [mem_ball, real.dist_eq, abs_sub_lt_iff, sub_lt_iff_lt_add', and_comm, sub_lt]; refl theorem real.Ioo_eq_ball (x y : ℝ) : Ioo x y = ball ((x + y) / 2) ((y - x) / 2) := by rw [real.ball_eq_Ioo, ← sub_div, add_comm, ← sub_add, add_sub_cancel', add_self_div_two, ← add_div, add_assoc, add_sub_cancel'_right, add_self_div_two] instance : complete_space ℝ := begin apply complete_of_cauchy_seq_tendsto, intros u hu, let c : cau_seq ℝ abs := ⟨u, metric.cauchy_seq_iff'.1 hu⟩, refine ⟨c.lim, λ s h, _⟩, rcases metric.mem_nhds_iff.1 h with ⟨ε, ε0, hε⟩, have := c.equiv_lim ε ε0, simp only [mem_map, mem_at_top_sets, mem_set_of_eq], refine this.imp (λ N hN n hn, hε (hN n hn)) end lemma real.totally_bounded_ball (x ε : ℝ) : totally_bounded (ball x ε) := by rw real.ball_eq_Ioo; apply totally_bounded_Ioo lemma rat.totally_bounded_Icc (a b : ℚ) : totally_bounded (Icc a b) := begin have := totally_bounded_preimage uniform_embedding_of_rat (totally_bounded_Icc a b), rwa (set.ext (λ q, _) : Icc _ _ = _), simp end section lemma closure_of_rat_image_lt {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q < x}) = {r | ↑q ≤ r} := subset.antisymm ((is_closed_ge' _).closure_subset_iff.2 (image_subset_iff.2 $ λ p h, le_of_lt $ (@rat.cast_lt ℝ _ _ _).2 h)) $ λ x hx, mem_closure_iff_nhds.2 $ λ t ht, let ⟨ε, ε0, hε⟩ := metric.mem_nhds_iff.1 ht in let ⟨p, h₁, h₂⟩ := exists_rat_btwn ((lt_add_iff_pos_right x).2 ε0) in ⟨_, hε (show abs _ < _, by rwa [abs_of_nonneg (le_of_lt $ sub_pos.2 h₁), sub_lt_iff_lt_add']), p, rat.cast_lt.1 (@lt_of_le_of_lt ℝ _ _ _ _ hx h₁), rfl⟩ /- TODO(Mario): Put these back only if needed later lemma closure_of_rat_image_le_eq {q : ℚ} : closure ((coe:ℚ → ℝ) '' {x | q ≤ x}) = {r | ↑q ≤ r} := _ lemma closure_of_rat_image_le_le_eq {a b : ℚ} (hab : a ≤ b) : closure (of_rat '' {q:ℚ | a ≤ q ∧ q ≤ b}) = {r:ℝ | of_rat a ≤ r ∧ r ≤ of_rat b} := _-/ lemma real.bounded_iff_bdd_below_bdd_above {s : set ℝ} : bounded s ↔ bdd_below s ∧ bdd_above s := ⟨begin assume bdd, rcases (bounded_iff_subset_ball 0).1 bdd with ⟨r, hr⟩, -- hr : s ⊆ closed_ball 0 r rw closed_ball_Icc at hr, -- hr : s ⊆ Icc (0 - r) (0 + r) exact ⟨⟨-r, λy hy, by simpa using (hr hy).1⟩, ⟨r, λy hy, by simpa using (hr hy).2⟩⟩ end, begin rintros ⟨⟨m, hm⟩, ⟨M, hM⟩⟩, have I : s ⊆ Icc m M := λx hx, ⟨hm hx, hM hx⟩, have : Icc m M = closed_ball ((m+M)/2) ((M-m)/2) := by rw closed_ball_Icc; congr; ring, rw this at I, exact bounded.subset I bounded_closed_ball end⟩ lemma real.image_Icc {f : ℝ → ℝ} {a b : ℝ} (hab : a ≤ b) (h : continuous_on f $ Icc a b) : f '' Icc a b = Icc (Inf $ f '' Icc a b) (Sup $ f '' Icc a b) := eq_Icc_of_connected_compact ⟨(nonempty_Icc.2 hab).image f, is_preconnected_Icc.image f h⟩ (is_compact_Icc.image_of_continuous_on h) end section periodic namespace function lemma periodic.compact_of_continuous' [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : 0 < c) (hf : continuous f) : is_compact (range f) := begin convert is_compact_Icc.image hf, ext x, refine ⟨_, mem_range_of_mem_image f (Icc 0 c)⟩, rintros ⟨y, h1⟩, obtain ⟨z, hz, h2⟩ := hp.exists_mem_Ico hc y, exact ⟨z, mem_Icc_of_Ico hz, h2.symm.trans h1⟩, end /-- A continuous, periodic function has compact range. -/ lemma periodic.compact_of_continuous [topological_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : is_compact (range f) := begin cases lt_or_gt_of_ne hc with hneg hpos, exacts [hp.neg.compact_of_continuous' (neg_pos.mpr hneg) hf, hp.compact_of_continuous' hpos hf], end /-- A continuous, periodic function is bounded. -/ lemma periodic.bounded_of_continuous [pseudo_metric_space α] {f : ℝ → α} {c : ℝ} (hp : periodic f c) (hc : c ≠ 0) (hf : continuous f) : bounded (range f) := (hp.compact_of_continuous hc hf).bounded end function end periodic section subgroups /-- Given a nontrivial subgroup `G ⊆ ℝ`, if `G ∩ ℝ_{>0}` has no minimum then `G` is dense. -/ lemma real.subgroup_dense_of_no_min {G : add_subgroup ℝ} {g₀ : ℝ} (g₀_in : g₀ ∈ G) (g₀_ne : g₀ ≠ 0) (H' : ¬ ∃ a : ℝ, is_least {g : ℝ | g ∈ G ∧ 0 < g} a) : dense (G : set ℝ) := begin let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, push_neg at H', intros x, suffices : ∀ ε > (0 : ℝ), ∃ g ∈ G, abs (x - g) < ε, by simpa only [real.mem_closure_iff, abs_sub_comm], intros ε ε_pos, obtain ⟨g₁, g₁_in, g₁_pos⟩ : ∃ g₁ : ℝ, g₁ ∈ G ∧ 0 < g₁, { cases lt_or_gt_of_ne g₀_ne with Hg₀ Hg₀, { exact ⟨-g₀, G.neg_mem g₀_in, neg_pos.mpr Hg₀⟩ }, { exact ⟨g₀, g₀_in, Hg₀⟩ } }, obtain ⟨a, ha⟩ : ∃ a, is_glb G_pos a := ⟨Inf G_pos, is_glb_cInf ⟨g₁, g₁_in, g₁_pos⟩ ⟨0, λ _ hx, le_of_lt hx.2⟩⟩, have a_notin : a ∉ G_pos, { intros H, exact H' a ⟨H, ha.1⟩ }, obtain ⟨g₂, g₂_in, g₂_pos, g₂_lt⟩ : ∃ g₂ : ℝ, g₂ ∈ G ∧ 0 < g₂ ∧ g₂ < ε, { obtain ⟨b, hb, hb', hb''⟩ := ha.exists_between_self_add' a_notin ε_pos, obtain ⟨c, hc, hc', hc''⟩ := ha.exists_between_self_add' a_notin (sub_pos.2 hb'), refine ⟨b - c, G.sub_mem hb.1 hc.1, _, _⟩ ; linarith }, refine ⟨floor (x/g₂) * g₂, _, _⟩, { exact add_subgroup.int_mul_mem _ g₂_in }, { rw abs_of_nonneg (sub_floor_div_mul_nonneg x g₂_pos), linarith [sub_floor_div_mul_lt x g₂_pos] } end /-- Subgroups of `ℝ` are either dense or cyclic. See `real.subgroup_dense_of_no_min` and `subgroup_cyclic_of_min` for more precise statements. -/ lemma real.subgroup_dense_or_cyclic (G : add_subgroup ℝ) : dense (G : set ℝ) ∨ ∃ a : ℝ, G = add_subgroup.closure {a} := begin cases add_subgroup.bot_or_exists_ne_zero G with H H, { right, use 0, rw [H, add_subgroup.closure_singleton_zero] }, { let G_pos := {g : ℝ | g ∈ G ∧ 0 < g}, by_cases H' : ∃ a, is_least G_pos a, { right, rcases H' with ⟨a, ha⟩, exact ⟨a, add_subgroup.cyclic_of_min ha⟩ }, { left, rcases H with ⟨g₀, g₀_in, g₀_ne⟩, exact real.subgroup_dense_of_no_min g₀_in g₀_ne H' } } end end subgroups
6b66d1405ffc00b4a5b2e2252f72e9bbdf0c8114
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/induction_tac1.lean
f4f5a5ff2c1d94fd9efcf181b3147b460ff34f93
[ "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
610
lean
open tactic example (p q : Prop) : p ∨ q → q ∨ p := by do H ← intro `H, induction H [`Hp, `Hq], trace_state, constructor_idx 2, assumption, constructor_idx 1, assumption #print "-----" open nat example (n : ℕ) : n = 0 ∨ n = succ (pred n) := by do n ← get_local `n, induction n [`n', `Hind], trace_state, constructor_idx 1, reflexivity, constructor_idx 2, reflexivity, return () #print "-----" example (n : ℕ) (H : n ≠ 0) : n > 0 → n = succ (pred n) := by do n ← get_local `n, induction n [], trace_state, intro `H1, contradiction, intros, reflexivity
86b2d27b3c1f167c1b02358e992cda77471e5b24
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/category_theory/monoidal/internal.lean
68c72f2038678eaa7b5254025f298bda5f87763a
[ "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
6,501
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monoidal.category /-! # The category of monoids in a monoidal category, and modules over an internal monoid. -/ universes v u open category_theory variables (C : Type u) [category.{v} C] [monoidal_category.{v} C] /-- A monoid object internal to a monoidal category. When the monoidal category is preadditive, this is also sometimes called an "algebra object". -/ structure Mon_ := (X : C) (one : 𝟙_ C ⟶ X) (mul : X ⊗ X ⟶ X) (one_mul' : (one ⊗ 𝟙 X) ≫ mul = (λ_ X).hom . obviously) (mul_one' : (𝟙 X ⊗ one) ≫ mul = (ρ_ X).hom . obviously) -- Obviously there is some flexibility stating this axiom. -- This one has left- and right-hand sides matching the statement of `monoid.mul_assoc`, -- and chooses to place the associator on the right-hand side. -- The heuristic is that unitors and associators "don't have much weight". (mul_assoc' : (mul ⊗ 𝟙 X) ≫ mul = (α_ X X X).hom ≫ (𝟙 X ⊗ mul) ≫ mul . obviously) restate_axiom Mon_.one_mul' restate_axiom Mon_.mul_one' restate_axiom Mon_.mul_assoc' attribute [simp, reassoc] Mon_.one_mul Mon_.mul_one Mon_.mul_assoc namespace Mon_ variables {C} variables {M : Mon_ C} lemma assoc_flip : (𝟙 M.X ⊗ M.mul) ≫ M.mul = (α_ M.X M.X M.X).inv ≫ (M.mul ⊗ 𝟙 M.X) ≫ M.mul := by simp /-- A morphism of monoid objects. -/ @[ext] structure hom (M N : Mon_ C) := (hom : M.X ⟶ N.X) (one_hom' : M.one ≫ hom = N.one . obviously) (mul_hom' : M.mul ≫ hom = (hom ⊗ hom) ≫ N.mul . obviously) restate_axiom hom.one_hom' restate_axiom hom.mul_hom' attribute [simp, reassoc] hom.one_hom hom.mul_hom /-- The identity morphism on a monoid object. -/ @[simps] def id (M : Mon_ C) : hom M M := { hom := 𝟙 M.X, } instance hom_inhabited (M : Mon_ C) : inhabited (hom M M) := ⟨id M⟩ /-- Composition of morphisms of monoid objects. -/ @[simps] def comp {M N O : Mon_ C} (f : hom M N) (g : hom N O) : hom M O := { hom := f.hom ≫ g.hom, } instance : category (Mon_ C) := { hom := λ M N, hom M N, id := id, comp := λ M N O f g, comp f g, } @[simp] lemma id_hom' (M : Mon_ C) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl @[simp] lemma comp_hom' {M N K : Mon_ C} (f : M ⟶ N) (g : N ⟶ K) : (f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl /-- The forgetful functor from monoid objects to the ambient category. -/ def forget : Mon_ C ⥤ C := { obj := λ A, A.X, map := λ A B f, f.hom, } end Mon_ -- PROJECT: lax monoidal functors `C ⥤ D` induce functors `Mon_ C ⥤ Mon_ D`. variables {C} /-- A module object for a monoid object, all internal to some monoidal category. -/ structure Mod (A : Mon_ C) := (X : C) (act : A.X ⊗ X ⟶ X) (one_act' : (A.one ⊗ 𝟙 X) ≫ act = (λ_ X).hom . obviously) (assoc' : (A.mul ⊗ 𝟙 X) ≫ act = (α_ A.X A.X X).hom ≫ (𝟙 A.X ⊗ act) ≫ act . obviously) restate_axiom Mod.one_act' restate_axiom Mod.assoc' attribute [simp, reassoc] Mod.one_act Mod.assoc namespace Mod variables {A : Mon_ C} (M : Mod A) lemma assoc_flip : (𝟙 A.X ⊗ M.act) ≫ M.act = (α_ A.X A.X M.X).inv ≫ (A.mul ⊗ 𝟙 M.X) ≫ M.act := by simp /-- A morphism of module objects. -/ @[ext] structure hom (M N : Mod A) := (hom : M.X ⟶ N.X) (act_hom' : M.act ≫ hom = (𝟙 A.X ⊗ hom) ≫ N.act . obviously) restate_axiom hom.act_hom' attribute [simp, reassoc] hom.act_hom /-- The identity morphism on a module object. -/ @[simps] def id (M : Mod A) : hom M M := { hom := 𝟙 M.X, } instance hom_inhabited (M : Mod A) : inhabited (hom M M) := ⟨id M⟩ /-- Composition of module object morphisms. -/ @[simps] def comp {M N O : Mod A} (f : hom M N) (g : hom N O) : hom M O := { hom := f.hom ≫ g.hom, } instance : category (Mod A) := { hom := λ M N, hom M N, id := id, comp := λ M N O f g, comp f g, } @[simp] lemma id_hom' (M : Mod A) : (𝟙 M : hom M M).hom = 𝟙 M.X := rfl @[simp] lemma comp_hom' {M N K : Mod A} (f : M ⟶ N) (g : N ⟶ K) : (f ≫ g : hom M K).hom = f.hom ≫ g.hom := rfl variables (A) /-- A monoid object as a module over itself. -/ @[simps] def regular : Mod A := { X := A.X, act := A.mul, } instance : inhabited (Mod A) := ⟨regular A⟩ open category_theory.monoidal_category /-- A morphism of monoid objects induces a "restriction" or "comap" functor between the categories of module objects. -/ @[simps] def comap {A B : Mon_ C} (f : A ⟶ B) : Mod B ⥤ Mod A := { obj := λ M, { X := M.X, act := (f.hom ⊗ 𝟙 M.X) ≫ M.act, one_act' := begin slice_lhs 1 2 { rw [←comp_tensor_id], }, rw [f.one_hom, one_act], end, assoc' := begin -- oh, for homotopy.io in a widget! slice_rhs 2 3 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, rw id_tensor_comp, slice_rhs 4 5 { rw Mod.assoc_flip, }, slice_rhs 3 4 { rw associator_inv_naturality, }, slice_rhs 2 3 { rw [←tensor_id, associator_inv_naturality], }, slice_rhs 1 3 { rw [iso.hom_inv_id_assoc], }, slice_rhs 1 2 { rw [←comp_tensor_id, tensor_id_comp_id_tensor], }, slice_rhs 1 2 { rw [←comp_tensor_id, ←f.mul_hom], }, rw [comp_tensor_id, category.assoc], end, }, map := λ M N g, { hom := g.hom, act_hom' := begin dsimp, slice_rhs 1 2 { rw [id_tensor_comp_tensor_id, ←tensor_id_comp_id_tensor], }, slice_rhs 2 3 { rw ←g.act_hom, }, rw category.assoc, end }, } -- Lots more could be said about `comap`, e.g. how it interacts with -- identities, compositions, and equalities of monoid object morphisms. end Mod /-! Projects: * Check that `Mon_ Mon ≌ CommMon`, via the Eckmann-Hilton argument. (You'll have to hook up the cartesian monoidal structure on `Mon` first, available in #3463) * Check that `Mon_ Top ≌ [bundled topological monoids]`. * Check that `Mon_ AddCommGroup ≌ Ring`. (You'll have to hook up the monoidal structure on `AddCommGroup`. Currently we have the monoidal structure on `Module R`; perhaps one could specialize to `R = ℤ` and transport the monoidal structure across an equivalence? This sounds like some work!) * Check that `Mon_ (Module R) ≌ Algebra R`. * Show that if `C` is braided (see #3550) then `Mon_ C` is naturally monoidal. * Can you transport this monoidal structure to `Ring` or `Algebra R`? How does it compare to the "native" one? -/
31ec6f32f8af0934af0efd36c8c3ea966466ec79
5a8eb1c11f93715e070b588e85f2961065c3714d
/books/theorem-proving-in-lean/ch02-08.lean
352f4f85d54f58f3f8a989cc2d3580e2c256ddf3
[ "MIT" ]
permissive
luksamuk/study
0e19bf99d33e0793127c3d3f8ad3936fbeb36505
6a9417e071a8624c4cd9db696c16a3abcc430219
refs/heads/master
1,677,960,533,266
1,676,234,529,000
1,676,234,529,000
151,009,060
4
1
MIT
1,676,234,531,000
1,538,343,224,000
C++
UTF-8
Lean
false
false
1,047
lean
-- Modeling some basig list operations. -- Namespace is to avoid conflicts with the -- `list` namespace. -- These declarations are only for illustration. namespace hidden universe u constant list : Type u → Type u constant cons : Π α : Type u, α → list α → list α constant nil : Π α : Type u, list α constant head : Π α : Type u, list α → α constant tail : Π α : Type u, list α → list α constant append : Π α : Type u, list α → list α → list α end hidden -- Let's check some default operations on -- the `list` namespace. open list #check list #check @cons #check @nil #check @head #check @tail #check @append -- Same works for vecs namespace hidden universe u constant vec : Type u → ℕ → Type u namespace vec constant empty : Π α : Type u, vec α 0 constant cons : Π (α : Type u) (n : ℕ), α → vec α n → vec α (n + 1) constant append : Π (α : Type u) (n m : ℕ), vec α m → vec α n → vec α (n + m) end vec end hidden
b46de2f4571415ec70c38db29824a654f535a4e9
618003631150032a5676f229d13a079ac875ff77
/test/lint_simp_nf.lean
3390e95dd5f6ce07a23ef52fe47fbd321115d71e
[ "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
921
lean
import tactic.lint def f : ℕ → ℕ := default _ def c : ℕ := default _ def d : ℕ := default _ @[simp] lemma c_eq_d : c = d := rfl -- The following lemma never applies when using simp, because c is first rewritten to d @[simp] lemma f_c : f c = 0 := rfl example : f c = 0 := begin simp, guard_target f d = 0, -- does not apply f_c refl end open tactic #eval do decl ← get_decl ``f_c, res ← linter.simp_nf.test decl, -- linter complains guard $ res.is_some -- also works with `coe_to_fun` structure morphism := (f : ℕ → ℕ) instance : has_coe_to_fun morphism := ⟨_, morphism.f⟩ def h : morphism := ⟨default _⟩ -- Also never applies @[simp] lemma h_c : h c = 0 := rfl example : h c = 0 := begin simp, guard_target h d = 0, -- does not apply h_c refl end open tactic #eval do decl ← get_decl ``h_c, res ← linter.simp_nf.test decl, -- linter complains guard $ res.is_some
6db502d10a92b1d00a8bbba03466c45be19a7eea
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/control/traversable/instances.lean
5d8837eafd6b54512ff8b70657ef68ecdede8e64
[ "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
5,481
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import control.applicative import data.list.forall2 import data.set.functor /-! # Traversable instances This file provides instances of `traversable` for types from the core library: `option`, `list` and `sum`. -/ universes u v section option open functor variables {F G : Type u → Type u} variables [applicative F] [applicative G] variables [is_lawful_applicative F] [is_lawful_applicative G] lemma option.id_traverse {α} (x : option α) : option.traverse id.mk x = x := by cases x; refl @[nolint unused_arguments] lemma option.comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : option α) : option.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (option.traverse f <$> option.traverse g x) := by cases x; simp! with functor_norm; refl lemma option.traverse_eq_map_id {α β} (f : α → β) (x : option α) : traverse (id.mk ∘ f) x = id.mk (f <$> x) := by cases x; refl variable (η : applicative_transformation F G) lemma option.naturality {α β} (f : α → F β) (x : option α) : η (option.traverse f x) = option.traverse (@η _ ∘ f) x := by cases x with x; simp! [*] with functor_norm end option instance : is_lawful_traversable option := { id_traverse := @option.id_traverse, comp_traverse := @option.comp_traverse, traverse_eq_map_id := @option.traverse_eq_map_id, naturality := @option.naturality, .. option.is_lawful_monad } namespace list variables {F G : Type u → Type u} variables [applicative F] [applicative G] section variables [is_lawful_applicative F] [is_lawful_applicative G] open applicative functor open list (cons) protected lemma id_traverse {α} (xs : list α) : list.traverse id.mk xs = xs := by induction xs; simp! * with functor_norm; refl @[nolint unused_arguments] protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : list α) : list.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (list.traverse f <$> list.traverse g x) := by induction x; simp! * with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : list α) : list.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : list α) : η (list.traverse f x) = list.traverse (@η _ ∘ f) x := by induction x; simp! * with functor_norm open nat instance : is_lawful_traversable.{u} list := { id_traverse := @list.id_traverse, comp_traverse := @list.comp_traverse, traverse_eq_map_id := @list.traverse_eq_map_id, naturality := @list.naturality, .. list.is_lawful_monad } end section traverse variables {α' β' : Type u} (f : α' → F β') @[simp] lemma traverse_nil : traverse f ([] : list α') = (pure [] : F (list β')) := rfl @[simp] lemma traverse_cons (a : α') (l : list α') : traverse f (a :: l) = (::) <$> f a <*> traverse f l := rfl variables [is_lawful_applicative F] @[simp] lemma traverse_append : ∀ (as bs : list α'), traverse f (as ++ bs) = (++) <$> traverse f as <*> traverse f bs | [] bs := have has_append.append ([] : list β') = id, by funext; refl, by simp [this] with functor_norm | (a :: as) bs := by simp [traverse_append as bs] with functor_norm; congr lemma mem_traverse {f : α' → set β'} : ∀(l : list α') (n : list β'), n ∈ traverse f l ↔ forall₂ (λb a, b ∈ f a) n l | [] [] := by simp | (a::as) [] := by simp | [] (b::bs) := by simp | (a::as) (b::bs) := by simp [mem_traverse as bs] end traverse end list namespace sum section traverse variables {σ : Type u} variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) protected lemma traverse_map {α β γ : Type u} (g : α → β) (f : β → G γ) (x : σ ⊕ α) : sum.traverse f (g <$> x) = sum.traverse (f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; refl variables [is_lawful_applicative F] [is_lawful_applicative G] protected lemma id_traverse {σ α} (x : σ ⊕ α) : sum.traverse id.mk x = x := by cases x; refl @[nolint unused_arguments] protected lemma comp_traverse {α β γ} (f : β → F γ) (g : α → G β) (x : σ ⊕ α) : sum.traverse (comp.mk ∘ (<$>) f ∘ g) x = comp.mk (sum.traverse f <$> sum.traverse g x) := by cases x; simp! [sum.traverse,map_id] with functor_norm; refl protected lemma traverse_eq_map_id {α β} (f : α → β) (x : σ ⊕ α) : sum.traverse (id.mk ∘ f) x = id.mk (f <$> x) := by induction x; simp! * with functor_norm; refl protected lemma map_traverse {α β γ} (g : α → G β) (f : β → γ) (x : σ ⊕ α) : (<$>) f <$> sum.traverse g x = sum.traverse ((<$>) f ∘ g) x := by cases x; simp [sum.traverse, id_map] with functor_norm; congr; refl variable (η : applicative_transformation F G) protected lemma naturality {α β} (f : α → F β) (x : σ ⊕ α) : η (sum.traverse f x) = sum.traverse (@η _ ∘ f) x := by cases x; simp! [sum.traverse] with functor_norm end traverse instance {σ : Type u} : is_lawful_traversable.{u} (sum σ) := { id_traverse := @sum.id_traverse σ, comp_traverse := @sum.comp_traverse σ, traverse_eq_map_id := @sum.traverse_eq_map_id σ, naturality := @sum.naturality σ, .. sum.is_lawful_monad } end sum
4347a4ff305544a04e8a4cff2e834af8ab5afa88
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/witt_vector/structure_polynomial_auto.lean
9f733842ce671cd31d9e675b80710a9bf603c4b1
[]
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
14,923
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.matrix.notation import Mathlib.field_theory.mv_polynomial import Mathlib.field_theory.finite.polynomial import Mathlib.number_theory.basic import Mathlib.ring_theory.witt_vector.witt_polynomial import Mathlib.PostPort universes u_2 u_1 namespace Mathlib /-! # Witt structure polynomials In this file we prove the main theorem that makes the whole theory of Witt vectors work. Briefly, consider a polynomial `Φ : mv_polynomial idx ℤ` over the integers, with polynomials variables indexed by an arbitrary type `idx`. Then there exists a unique family of polynomials `φ : ℕ → mv_polynomial (idx × ℕ) Φ` such that for all `n : ℕ` we have (`witt_structure_int_exists_unique`) ``` bind₁ φ (witt_polynomial p ℤ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℤ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. N.b.: As far as we know, these polynomials do not have a name in the literature, so we have decided to call them the “Witt structure polynomials”. See `witt_structure_int`. ## Special cases With the main result of this file in place, we apply it to certain special polynomials. For example, by taking `Φ = X tt + X ff` resp. `Φ = X tt * X ff` we obtain families of polynomials `witt_add` resp. `witt_mul` (with type `ℕ → mv_polynomial (bool × ℕ) ℤ`) that will be used in later files to define the addition and multiplication on the ring of Witt vectors. ## Outline of the proof The proof of `witt_structure_int_exists_unique` is rather technical, and takes up most of this file. We start by proving the analogous version for polynomials with rational coefficients, instead of integer coefficients. In this case, the solution is rather easy, since the Witt polynomials form a faithful change of coordinates in the polynomial ring `mv_polynomial ℕ ℚ`. We therefore obtain a family of polynomials `witt_structure_rat Φ` for every `Φ : mv_polynomial idx ℚ`. If `Φ` has integer coefficients, then the polynomials `witt_structure_rat Φ n` do so as well. Proving this claim is the essential core of this file, and culminates in `map_witt_structure_int`, which proves that upon mapping the coefficients of `witt_structure_int Φ n` from the integers to the rationals, one obtains `witt_structure_rat Φ n`. Ultimately, the proof of `map_witt_structure_int` relies on ``` dvd_sub_pow_of_dvd_sub {R : Type*} [comm_ring R] {p : ℕ} {a b : R} : (p : R) ∣ a - b → ∀ (k : ℕ), (p : R) ^ (k + 1) ∣ a ^ p ^ k - b ^ p ^ k ``` ## Main results * `witt_structure_rat Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` associated with `Φ : mv_polynomial idx ℚ` and satisfying the property explained above. * `witt_structure_rat_prop`: the proof that `witt_structure_rat` indeed satisfies the property. * `witt_structure_int Φ`: the family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℤ` associated with `Φ : mv_polynomial idx ℤ` and satisfying the property explained above. * `map_witt_structure_int`: the proof that the integral polynomials `with_structure_int Φ` are equal to `witt_structure_rat Φ` when mapped to polynomials with rational coefficients. * `witt_structure_int_prop`: the proof that `witt_structure_int` indeed satisfies the property. * Five families of polynomials that will be used to define the ring structure on the ring of Witt vectors: - `witt_vector.witt_zero` - `witt_vector.witt_one` - `witt_vector.witt_add` - `witt_vector.witt_mul` - `witt_vector.witt_neg` (We also define `witt_vector.witt_sub`, and later we will prove that it describes subtraction, which is defined as `λ a b, a + -b`. See `witt_vector.sub_coeff` for this proof.) -/ -- This lemma reduces a bundled morphism to a "mere" function, -- and consequently the simplifier cannot use a lot of powerful simp-lemmas. -- We disable this locally, and probably it should be disabled globally in mathlib. /-- `witt_structure_rat Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_rat p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_rat Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_rat_prop` for this property, and `witt_structure_rat_exists_unique` for the fact that `witt_structure_rat` gives the unique family of polynomials with this property. These polynomials turn out to have integral coefficients, but it requires some effort to show this. See `witt_structure_int` for the version with integral coefficients, and `map_witt_structure_int` for the fact that it is equal to `witt_structure_rat` when mapped to polynomials over the rationals. -/ def witt_structure_rat (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial (idx × ℕ) ℚ := coe_fn (mv_polynomial.bind₁ fun (k : ℕ) => coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ k)) Φ) (X_in_terms_of_W p ℚ n) theorem witt_structure_rat_prop (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_structure_rat p Φ)) (witt_polynomial p ℚ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ n)) Φ := sorry theorem witt_structure_rat_exists_unique (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) : exists_unique fun (φ : ℕ → mv_polynomial (idx × ℕ) ℚ) => ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℚ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℚ n)) Φ := sorry theorem witt_structure_rat_rec_aux (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n * coe_fn mv_polynomial.C (↑p ^ n) = coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℚ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_rat p Φ i ^ p ^ (n - i) := sorry /-- Write `witt_structure_rat p φ n` in terms of `witt_structure_rat p φ i` for `i < n`. -/ theorem witt_structure_rat_rec (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (n : ℕ) : witt_structure_rat p Φ n = coe_fn mv_polynomial.C (1 / ↑p ^ n) * (coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℚ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_rat p Φ i ^ p ^ (n - i)) := sorry /-- `witt_structure_int Φ` is a family of polynomials `ℕ → mv_polynomial (idx × ℕ) ℚ` that are uniquely characterised by the property that ``` bind₁ (witt_structure_int p Φ) (witt_polynomial p ℚ n) = bind₁ (λ i, (rename (prod.mk i) (witt_polynomial p ℚ n))) Φ ``` In other words: evaluating the `n`-th Witt polynomial on the family `witt_structure_int Φ` is the same as evaluating `Φ` on the (appropriately renamed) `n`-th Witt polynomials. See `witt_structure_int_prop` for this property, and `witt_structure_int_exists_unique` for the fact that `witt_structure_int` gives the unique family of polynomials with this property. -/ def witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial (idx × ℕ) ℤ := finsupp.map_range rat.num sorry (witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) n) theorem bind₁_rename_expand_witt_polynomial {p : ℕ} {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ (m : ℕ), m < n + 1 → coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ m) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) m) : coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (coe_fn (mv_polynomial.expand p) (witt_polynomial p ℤ n))) Φ = coe_fn (mv_polynomial.bind₁ fun (i : ℕ) => coe_fn (mv_polynomial.expand p) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) := sorry theorem C_p_pow_dvd_bind₁_rename_witt_polynomial_sub_sum {p : ℕ} {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) (IH : ∀ (m : ℕ), m < n → coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ m) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) m) : coe_fn mv_polynomial.C ↑(p ^ n) ∣ coe_fn (mv_polynomial.bind₁ fun (b : idx) => coe_fn (mv_polynomial.rename fun (i : ℕ) => (b, i)) (witt_polynomial p ℤ n)) Φ - finset.sum (finset.range n) fun (i : ℕ) => coe_fn mv_polynomial.C (↑p ^ i) * witt_structure_int p Φ i ^ p ^ (n - i) := sorry @[simp] theorem map_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) (witt_structure_int p Φ n) = witt_structure_rat p (coe_fn (mv_polynomial.map (int.cast_ring_hom ℚ)) Φ) n := sorry theorem witt_structure_int_prop (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.bind₁ (witt_structure_int p Φ)) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ := sorry theorem eq_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) (h : ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ) : φ = witt_structure_int p Φ := sorry theorem witt_structure_int_exists_unique (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) : exists_unique fun (φ : ℕ → mv_polynomial (idx × ℕ) ℤ) => ∀ (n : ℕ), coe_fn (mv_polynomial.bind₁ φ) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.bind₁ fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p ℤ n)) Φ := Exists.intro (witt_structure_int p Φ) { left := witt_structure_int_prop p Φ, right := eq_witt_structure_int p Φ } theorem witt_structure_prop (p : ℕ) {R : Type u_1} {idx : Type u_2} [comm_ring R] [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (n : ℕ) : coe_fn (mv_polynomial.aeval fun (i : ℕ) => coe_fn (mv_polynomial.map (int.cast_ring_hom R)) (witt_structure_int p Φ i)) (witt_polynomial p ℤ n) = coe_fn (mv_polynomial.aeval fun (i : idx) => coe_fn (mv_polynomial.rename (Prod.mk i)) (witt_polynomial p R n)) Φ := sorry theorem witt_structure_int_rename (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] {σ : Type u_1} (Φ : mv_polynomial idx ℤ) (f : idx → σ) (n : ℕ) : witt_structure_int p (coe_fn (mv_polynomial.rename f) Φ) n = coe_fn (mv_polynomial.rename (prod.map f id)) (witt_structure_int p Φ n) := sorry @[simp] theorem constant_coeff_witt_structure_rat_zero (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) : coe_fn mv_polynomial.constant_coeff (witt_structure_rat p Φ 0) = coe_fn mv_polynomial.constant_coeff Φ := sorry theorem constant_coeff_witt_structure_rat (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℚ) (h : coe_fn mv_polynomial.constant_coeff Φ = 0) (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_structure_rat p Φ n) = 0 := sorry @[simp] theorem constant_coeff_witt_structure_int_zero (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) : coe_fn mv_polynomial.constant_coeff (witt_structure_int p Φ 0) = coe_fn mv_polynomial.constant_coeff Φ := sorry theorem constant_coeff_witt_structure_int (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] (Φ : mv_polynomial idx ℤ) (h : coe_fn mv_polynomial.constant_coeff Φ = 0) (n : ℕ) : coe_fn mv_polynomial.constant_coeff (witt_structure_int p Φ n) = 0 := sorry -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. theorem witt_structure_rat_vars (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] [fintype idx] (Φ : mv_polynomial idx ℚ) (n : ℕ) : mv_polynomial.vars (witt_structure_rat p Φ n) ⊆ finset.product finset.univ (finset.range (n + 1)) := sorry -- we could relax the fintype on `idx`, but then we need to cast from finset to set. -- for our applications `idx` is always finite. theorem witt_structure_int_vars (p : ℕ) {idx : Type u_2} [hp : fact (nat.prime p)] [fintype idx] (Φ : mv_polynomial idx ℤ) (n : ℕ) : mv_polynomial.vars (witt_structure_int p Φ n) ⊆ finset.product finset.univ (finset.range (n + 1)) := sorry end Mathlib
76b3673c7fb1bbb92aa6652c4cf5e5c984676117
61ccc57f9d72048e493dd6969b56ebd7f0a8f9e8
/src/measure_theory/probability_mass_function.lean
2829791b281cb9e1d5b41f84aacf59fc406a9960
[ "Apache-2.0" ]
permissive
jtristan/mathlib
375b3c8682975df28f79f53efcb7c88840118467
8fa8f175271320d675277a672f59ec53abd62f10
refs/heads/master
1,651,072,765,551
1,588,255,641,000
1,588,255,641,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,772
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Probability mass function -- discrete probability measures -/ import topology.instances.ennreal noncomputable theory variables {α : Type*} {β : Type*} {γ : Type*} open_locale classical /-- Probability mass functions, i.e. discrete probability measures -/ def {u} pmf (α : Type u) : Type u := { f : α → nnreal // has_sum f 1 } namespace pmf instance : has_coe_to_fun (pmf α) := ⟨λp, α → nnreal, λp a, p.1 a⟩ @[ext] protected lemma ext : ∀{p q : pmf α}, (∀a, p a = q a) → p = q | ⟨f, hf⟩ ⟨g, hg⟩ eq := subtype.eq $ funext eq lemma has_sum_coe_one (p : pmf α) : has_sum p 1 := p.2 lemma summable_coe (p : pmf α) : summable p := (p.has_sum_coe_one).summable @[simp] lemma tsum_coe (p : pmf α) : (∑'a, p a) = 1 := tsum_eq_has_sum p.has_sum_coe_one def support (p : pmf α) : set α := {a | p.1 a ≠ 0} def pure (a : α) : pmf α := ⟨λa', if a' = a then 1 else 0, has_sum_ite_eq _ _⟩ @[simp] lemma pure_apply (a a' : α) : pure a a' = (if a' = a then 1 else 0) := rfl instance [inhabited α] : inhabited (pmf α) := ⟨pure (default α)⟩ lemma coe_le_one (p : pmf α) (a : α) : p a ≤ 1 := has_sum_le (by intro b; split_ifs; simp [h]; exact le_refl _) (has_sum_ite_eq a (p a)) p.2 protected lemma bind.summable (p : pmf α) (f : α → pmf β) (b : β) : summable (λa:α, p a * f a b) := begin refine nnreal.summable_of_le (assume a, _) p.summable_coe, suffices : p a * f a b ≤ p a * 1, { simpa }, exact mul_le_mul_of_nonneg_left ((f a).coe_le_one _) (p a).2 end def bind (p : pmf α) (f : α → pmf β) : pmf β := ⟨λb, (∑'a, p a * f a b), begin apply ennreal.has_sum_coe.1, simp only [ennreal.coe_tsum (bind.summable p f _)], rw [ennreal.summable.has_sum_iff, ennreal.tsum_comm], simp [ennreal.tsum_mul_left, (ennreal.coe_tsum (f _).summable_coe).symm, (ennreal.coe_tsum p.summable_coe).symm] end⟩ @[simp] lemma bind_apply (p : pmf α) (f : α → pmf β) (b : β) : p.bind f b = (∑'a, p a * f a b) := rfl lemma coe_bind_apply (p : pmf α) (f : α → pmf β) (b : β) : (p.bind f b : ennreal) = (∑'a, p a * f a b) := eq.trans (ennreal.coe_tsum $ bind.summable p f b) $ by simp @[simp] lemma pure_bind (a : α) (f : α → pmf β) : (pure a).bind f = f a := have ∀b a', ite (a' = a) 1 0 * f a' b = ite (a' = a) (f a b) 0, from assume b a', by split_ifs; simp; subst h; simp, by ext b; simp [this] @[simp] lemma bind_pure (p : pmf α) : p.bind pure = p := have ∀a a', (p a * ite (a' = a) 1 0) = ite (a = a') (p a') 0, from assume a a', begin split_ifs; try { subst a }; try { subst a' }; simp * at * end, by ext b; simp [this] @[simp] lemma bind_bind (p : pmf α) (f : α → pmf β) (g : β → pmf γ) : (p.bind f).bind g = p.bind (λa, (f a).bind g) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end lemma bind_comm (p : pmf α) (q : pmf β) (f : α → β → pmf γ) : p.bind (λa, q.bind (f a)) = q.bind (λb, p.bind (λa, f a b)) := begin ext b, simp only [ennreal.coe_eq_coe.symm, coe_bind_apply, ennreal.tsum_mul_left.symm, ennreal.tsum_mul_right.symm], rw [ennreal.tsum_comm], simp [mul_assoc, mul_left_comm, mul_comm] end def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f) lemma bind_pure_comp (f : α → β) (p : pmf α) : bind p (pure ∘ f) = map f p := rfl lemma map_id (p : pmf α) : map id p = p := by simp [map] lemma map_comp (p : pmf α) (f : α → β) (g : β → γ) : (p.map f).map g = p.map (g ∘ f) := by simp [map] lemma pure_map (a : α) (f : α → β) : (pure a).map f = pure (f a) := by simp [map] def seq (f : pmf (α → β)) (p : pmf α) : pmf β := f.bind (λm, p.bind $ λa, pure (m a)) def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α := ⟨λa, s.count a / s.card, have s.to_finset.sum (λa, (s.count a : ℝ) / s.card) = 1, by simp [div_eq_inv_mul', finset.mul_sum.symm, (finset.sum_nat_cast _ _).symm, hs], have s.to_finset.sum (λa, (s.count a : nnreal) / s.card) = 1, by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp, begin rw ← this, apply has_sum_sum_of_ne_finset_zero, simp {contextual := tt}, end⟩ def of_fintype [fintype α] (f : α → nnreal) (h : finset.univ.sum f = 1) : pmf α := ⟨f, h ▸ has_sum_sum_of_ne_finset_zero (by simp)⟩ def bernoulli (p : nnreal) (h : p ≤ 1) : pmf bool := of_fintype (λb, cond b p (1 - p)) (nnreal.eq $ by simp [h]) end pmf
d947de7072bb4a43f96abc081dfcdd1059226580
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Elab/BuiltinNotation.lean
c986d185a14e1a60d12a5bcdc5e65cf50d555b48
[ "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,688
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 Init.Data.ToString import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.Transform import Lean.Elab.Term import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival us => do match ival.ctors with | [ctor] => let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by $tac:tacticSeq) => `(show $type from by $tac:tacticSeq) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => let mkId (x? : Option Syntax) : Syntax := x?.getD <| mkIdentFrom stx `this match stx with | `(have $[$x :]? $type from $val $[;]? $body) => let x := mkId x; `(let_fun $x : $type := $val; $body) | `(have $[$x :]? $type := $val $[;]? $body) => let x := mkId x; `(let_fun $x : $type := $val; $body) | `(have $[$x :]? $type by $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from by $tac:tacticSeq; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x :]? $type from $body; $val) | `(suffices $[$x :]? $type by $tac:tacticSeq $[;]? $body) => `(have $[$x :]? $type from $body; by $tac:tacticSeq) | _ => Macro.throwUnsupported private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := Name.str _ s _, scopes := scps, .. } => let kind := quote declName let s := quote s let p ← `(Lean.Parser.leadingNode $kind $prec $e) if scps == [] then -- TODO simplify the following quotation as soon as we have coercions `(OrElse.orElse (Lean.Parser.mkAntiquot $s (some $kind)) $p) else -- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind `(OrElse.orElse (Lean.Parser.mkAntiquot $s none) $p) | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(leading_parser $e) => elabParserMacroAux (quote Parser.maxPrec) e | `(leading_parser : $prec $e) => elabParserMacroAux prec e | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec : Syntax) (e : Syntax) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; `(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do let arg := stx[1] let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx => -- TODO: support for disabling runtime assertions let cond := stx[1] let body := stx[3] match cond.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx => let arg := stx[1] let body := stx[3] if arg.getKind == interpolatedStrKind then `(dbgTrace (s! $arg) fun _ => $body) else `(dbgTrace (toString $arg) fun _ => $body) @[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do logWarning "declaration uses 'sorry'" let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? @[builtinTermElab emptyC] def expandEmptyC : TermElab := fun stx expectedType? => do let stxNew ← `(EmptyCollection.emptyCollection) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do if i > 0 then let i := i - 1 let elem := elems[i] let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back private partial def hasCDot : Syntax → Bool | Syntax.node k args => if k == `Lean.Parser.Term.paren then false else if k == `Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Auxiliary function for expandind the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ private partial def expandCDot : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node k args) => if k == `Lean.Parser.Term.paren then pure stx else if k == `Lean.Parser.Term.cdot then withFreshMacroScope do let id ← `(a) modify fun s => s.push id; pure id else do let args ← args.mapM expandCDot pure $ Syntax.node k args | stx => pure stx /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do if hasCDot stx then let (newStx, binders) ← (expandCDot stx).run #[]; `(fun $binders* => $newStx) else pure none /-- Try to expand `·` notation, and if successful elaborate result. This method is used to elaborate the Lean parentheses notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ private def elabCDot (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← liftMacroM <| expandCDot? stx) with | some stx' => withMacroExpansion stx stx' (elabTerm stx' expectedType?) | none => elabTerm stx expectedType? /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Syntax) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f:ident $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do match stx with | `(()) => return Lean.mkConst `Unit.unit | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) $ elabType type let e ← elabCDot e type ensureHasType type e | `(($e)) => elabCDot e expectedType? | `(($e, $es,*)) => let pairs ← liftMacroM <| mkPairs (#[e] ++ es) withMacroExpansion stx pairs (elabCDot pairs expectedType?) | _ => throwError "unexpected parentheses notation" @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation" match stx with | `($heq ▸ $h) => do let mut heq ← elabTerm heq none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (typeWithLooseBVar : Expr) := withLocalDeclD (← mkFreshUserName `x) α fun x => do mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let h ← withRef h do let h ← elabTerm h hExpectedType try ensureHasType hExpectedType h catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq) mkEqNDRec (← mkMotive expectedAbst) h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut m := stx[2] if m.getKind == `Lean.Parser.Term.macroDollarArg then m := m[1] let m ← elabTerm m (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM `STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM `StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
1384c823e2cb6a830e539aec41e46d4fcd3606a9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/constructions/borel_space.lean
8b000064f6c86e9ee4212a02a048ae98c9d05bce
[ "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
81,029
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 measure_theory.function.ae_measurable_sequence import analysis.complex.basic import analysis.normed_space.finite_dimension import topology.G_delta import measure_theory.group.arithmetic import topology.semicontinuous import topology.instances.ereal import topology.continuous_function.basic /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal interval universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.countable_encodable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s t hs ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma borel_eq_generate_from_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_from_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_from_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ theorem _root_.measurable_set.induction_on_open [topological_space α] [measurable_space α] [borel_space α] {C : set α → Prop} (h_open : ∀ U, is_open U → C U) (h_compl : ∀ t, measurable_set t → C t → C tᶜ) (h_union : ∀ f : ℕ → set α, pairwise (disjoint on f) → (∀ i, measurable_set (f i)) → (∀ i, C (f i)) → C (⋃ i, f i)) : ∀ ⦃t⦄, measurable_set t → C t := measurable_space.induction_on_inter borel_space.measurable_eq is_pi_system_is_open (h_open _ is_open_empty) h_open h_compl h_union section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space_encodable {ι : Type*} {π : ι → Type*} [encodable ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance pi.opens_measurable_space_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := by { letI := fintype.encodable ι, apply_instance } instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end variables {α' : Type*} [topological_space α'] [measurable_space α'] lemma measure_interior_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (interior s) = μ s := measure_eq_measure_smaller_of_between_null_diff interior_subset subset_closure h_nullbdry lemma measure_closure_of_null_bdry {μ : measure α'} {s : set α'} (h_nullbdry : μ (frontier s) = 0) : μ (closure s) = μ s := (measure_eq_measure_larger_of_between_null_diff interior_subset subset_closure h_nullbdry).symm section preorder variables [preorder α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance nhds_within_Icc_is_measurably_generated : is_measurably_generated (𝓝[Icc a b] x) := by { rw [← Ici_inter_Iic, nhds_within_inter], apply_instance } instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated lemma bsupr_measure_Iic {μ : measure α} {s : set α} (hsc : countable s) (hst : ∀ x : α, ∃ y ∈ s, x ≤ y) (hdir : directed_on (≤) s) : (⨆ x ∈ s, μ (Iic x)) = μ univ := begin rw ← measure_bUnion_eq_supr hsc, { congr, exact bUnion_eq_univ_iff.2 hst }, { exact λ _ _, measurable_set_Iic }, { exact directed_on_iff_directed.2 (hdir.directed_coe.mono_comp _ $ λ x y, Iic_subset_Iic.2) } end end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b x : α} @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ instance nhds_within_interval_is_measurably_generated : is_measurably_generated (𝓝[[a, b]] x) := nhds_within_Icc_is_measurably_generated @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra h, push_neg at h, exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1, mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set lemma generate_from_Ico_mem_le_borel {α : Type*} [topological_space α] [linear_order α] [order_closed_topology α] (s t : set α) : measurable_space.generate_from {S | ∃ (l ∈ s) (u ∈ t) (h : l < u), Ico l u = S} ≤ borel α := begin apply generate_from_le, letI : measurable_space α := borel α, haveI : borel_space α := ⟨rfl⟩, rintro _ ⟨a, -, b, -, -, rfl⟩, exact measurable_set_Ico end lemma dense.borel_eq_generate_from_Ico_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_bot x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → y ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := begin set S : set (set α) := {S | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S}, refine le_antisymm _ (generate_from_Ico_mem_le_borel _ _), letI : measurable_space α := generate_from S, rw borel_eq_generate_from_Iio, refine generate_from_le (forall_range_iff.2 $ λ a, _), rcases hd.exists_countable_dense_subset_bot_top with ⟨t, hts, hc, htd, htb, htt⟩, by_cases ha : ∀ b < a, (Ioo b a).nonempty, { convert_to measurable_set (⋃ (l ∈ t) (u ∈ t) (hlu : l < u) (hu : u ≤ a), Ico l u), { ext y, simp only [mem_Union, mem_Iio, mem_Ico], split, { intro hy, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) y with ⟨l, hlt, hly⟩, rcases htd.exists_mem_open is_open_Ioo (ha y hy) with ⟨u, hut, hyu, hua⟩, exact ⟨l, hlt, u, hut, hly.trans_lt hyu, hua.le, hly, hyu⟩ }, { rintro ⟨l, -, u, -, -, hua, -, hyu⟩, exact hyu.trans_le hua } }, { refine measurable_set.bUnion hc (λ a ha, measurable_set.bUnion hc $ λ b hb, _), refine measurable_set.Union_Prop (λ hab, measurable_set.Union_Prop $ λ hb', _), exact generate_measurable.basic _ ⟨a, hts ha, b, hts hb, hab, mem_singleton _⟩ } }, { simp only [not_forall, not_nonempty_iff_eq_empty] at ha, replace ha : a ∈ s := hIoo ha.some a ha.some_spec.fst ha.some_spec.snd, convert_to measurable_set (⋃ (l ∈ t) (hl : l < a), Ico l a), { symmetry, simp only [← Ici_inter_Iio, ← Union_inter, inter_eq_right_iff_subset, subset_def, mem_Union, mem_Ici, mem_Iio], intros x hx, rcases htd.exists_le' (λ b hb, htb _ hb (hbot b hb)) x with ⟨z, hzt, hzx⟩, exact ⟨z, hzt, hzx.trans_lt hx, hzx⟩ }, { refine measurable_set.bUnion hc (λ x hx, measurable_set.Union_Prop $ λ hlt, _), exact generate_measurable.basic _ ⟨x, hts hx, a, ha, hlt, mem_singleton _⟩ } } end lemma dense.borel_eq_generate_from_Ico_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_bot_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ico l u = S} := hd.borel_eq_generate_from_Ico_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ico (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ico l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ico_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) lemma dense.borel_eq_generate_from_Ioc_mem_aux {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] {s : set α} (hd : dense s) (hbot : ∀ x, is_top x → x ∈ s) (hIoo : ∀ x y : α, x < y → Ioo x y = ∅ → x ∈ s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := begin convert hd.order_dual.borel_eq_generate_from_Ico_mem_aux hbot (λ x y hlt he, hIoo y x hlt _), { ext s, split; rintro ⟨l, hl, u, hu, hlt, rfl⟩, exacts [⟨u, hu, l, hl, hlt, dual_Ico⟩, ⟨u, hu, l, hl, hlt, dual_Ioc⟩] }, { erw dual_Ioo, exact he } end lemma dense.borel_eq_generate_from_Ioc_mem {α : Type*} [topological_space α] [linear_order α] [order_topology α] [second_countable_topology α] [densely_ordered α] [no_top_order α] {s : set α} (hd : dense s) : borel α = generate_from {S : set α | ∃ (l ∈ s) (u ∈ s) (h : l < u), Ioc l u = S} := hd.borel_eq_generate_from_Ioc_mem_aux (by simp) $ λ x y hxy H, ((nonempty_Ioo.2 hxy).ne_empty H).elim lemma borel_eq_generate_from_Ioc (α : Type*) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from {S : set α | ∃ l u (h : l < u), Ioc l u = S} := by simpa only [exists_prop, mem_univ, true_and] using (@dense_univ α _).borel_eq_generate_from_Ioc_mem_aux (λ _ _, mem_univ _) (λ _ _ _ _, mem_univ _) namespace measure_theory.measure /-- Two finite measures on a Borel space are equal if they agree on all closed-open intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ico` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ico_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin refine ext_of_generate_finite _ (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico (id : α → α) id) _ hμν, { rintro - ⟨a, b, hlt, rfl⟩, exact h hlt } end /-- Two finite measures on a Borel space are equal if they agree on all open-closed intervals. If `α` is a conditionally complete linear order with no top element, `measure_theory.measure..ext_of_Ioc` is an extensionality lemma with weaker assumptions on `μ` and `ν`. -/ lemma ext_of_Ioc_finite {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (hμν : μ univ = ν univ) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico_finite (order_dual α) _ _ _ _ _ ‹_› μ ν _ hμν (λ a b hab, _), erw dual_Ico, exact h hab end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_top_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ico a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := begin rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, hsb, hst⟩, have : countable (⋃ (l ∈ s) (u ∈ s) (h : l < u), {Ico l u} : set (set α)), from hsc.bUnion (λ l hl, hsc.bUnion (λ u hu, countable_Union_Prop $ λ _, countable_singleton _)), simp only [← set_of_eq_eq_singleton, ← set_of_exists] at this, refine measure.ext_of_generate_from_of_cover_subset (borel_space.measurable_eq.trans (borel_eq_generate_from_Ico α)) (is_pi_system_Ico id id) _ this _ _ _, { rintro _ ⟨l, -, u, -, h, rfl⟩, exact ⟨l, u, h, rfl⟩ }, { refine sUnion_eq_univ_iff.2 (λ x, _), rcases hsd.exists_le' hsb x with ⟨l, hls, hlx⟩, rcases hsd.exists_gt x with ⟨u, hus, hxu⟩, exact ⟨_, ⟨l, hls, u, hus, hlx.trans_lt hxu, rfl⟩, hlx, hxu⟩ }, { rintro _ ⟨l, -, u, -, hlt, rfl⟩, exact hμ hlt }, { rintro _ ⟨l, u, hlt, rfl⟩, exact h hlt } end /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc' {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] [no_bot_order α] (μ ν : measure α) (hμ : ∀ ⦃a b⦄, a < b → μ (Ioc a b) ≠ ∞) (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := begin refine @ext_of_Ico' (order_dual α) _ _ _ _ _ ‹_› _ μ ν _ _; intros a b hab; erw dual_Ico, exacts [hμ hab, h hab] end /-- Two measures which are finite on closed-open intervals are equal if the agree on all closed-open intervals. -/ lemma ext_of_Ico {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_top_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ico a b) = ν (Ico a b)) : μ = ν := μ.ext_of_Ico' ν (λ a b hab, measure_Ico_lt_top.ne) h /-- Two measures which are finite on closed-open intervals are equal if the agree on all open-closed intervals. -/ lemma ext_of_Ioc {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [conditionally_complete_linear_order α] [order_topology α] [borel_space α] [no_bot_order α] (μ ν : measure α) [is_locally_finite_measure μ] (h : ∀ ⦃a b⦄, a < b → μ (Ioc a b) = ν (Ioc a b)) : μ = ν := μ.ext_of_Ioc' ν (λ a b hab, measure_Ioc_lt_top.ne) h /-- Two finite measures on a Borel space are equal if they agree on all left-infinite right-closed intervals. -/ lemma ext_of_Iic {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Iic a) = ν (Iic a)) : μ = ν := begin refine ext_of_Ioc_finite μ ν _ (λ a b hlt, _), { rcases exists_countable_dense_bot_top α with ⟨s, hsc, hsd, -, hst⟩, have : directed_on (≤) s, from directed_on_iff_directed.2 (directed_of_sup $ λ _ _, id), simp only [← bsupr_measure_Iic hsc (hsd.exists_ge' hst) this, h] }, rw [← Iic_diff_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic measurable_set_Iic, measure_diff (Iic_subset_Iic.2 hlt.le) measurable_set_Iic measurable_set_Iic, h a, h b], { rw ← h a, exact (measure_lt_top μ _).ne }, { exact (measure_lt_top μ _).ne } end /-- Two finite measures on a Borel space are equal if they agree on all left-closed right-infinite intervals. -/ lemma ext_of_Ici {α : Type*} [topological_space α] {m : measurable_space α} [second_countable_topology α] [linear_order α] [order_topology α] [borel_space α] (μ ν : measure α) [is_finite_measure μ] (h : ∀ a, μ (Ici a) = ν (Ici a)) : μ = ν := @ext_of_Iic (order_dual α) _ _ _ _ _ ‹_› _ _ _ h end measure_theory.measure end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := by simpa only [max_def] using hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := by simpa only [min_def] using hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const.smul continuous_id).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section homeomorph @[measurability] protected lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.measurable, measurable_inv_fun := h.symm.measurable, to_equiv := h.to_equiv } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl end homeomorph @[measurability] lemma continuous_map.measurable (f : C(α, γ)) : measurable f := f.continuous.measurable lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv₀.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv₀ γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv₀⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space_fintype_encodable {ι : Type*} {π : ι → Type*} [encodable ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance pi.borel_space_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ protected lemma embedding.measurable_embedding {f : α → β} (h₁ : embedding f) (h₂ : measurable_set (range f)) : measurable_embedding f := show measurable_embedding (coe ∘ (homeomorph.of_embedding f h₁).to_measurable_equiv), from (measurable_embedding.subtype_coe h₂).comp (measurable_equiv.measurable_embedding _) protected lemma closed_embedding.measurable_embedding {f : α → β} (h : closed_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.closed_range.measurable_set protected lemma open_embedding.measurable_embedding {f : α → β} (h : open_embedding f) : measurable_embedding f := h.to_embedding.measurable_embedding h.open_range.measurable_set section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_from_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_from_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] }, by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end protected lemma monotone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : monotone_on f s) : ae_measurable f (μ.restrict s) := have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy, ae_measurable_restrict_of_measurable_subtype hs this.measurable protected lemma antitone.measurable [linear_order β] [order_closed_topology β] {f : β → α} (hf : antitone f) : measurable f := @monotone.measurable (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf lemma ae_measurable_restrict_of_antitone_on [linear_order β] [order_closed_topology β] {μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α} (hf : antitone_on f s) : ae_measurable f (μ.restrict s) := @ae_measurable_restrict_of_monotone_on (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ /-- One can cut out `ℝ≥0∞` into the sets `{0}`, `Ico (t^n) (t^(n+1))` for `n : ℤ` and `{∞}`. This gives a way to compute the measure of a set in terms of sets on which a given function `f` does not fluctuate by more than `t`. -/ lemma measure_eq_measure_preimage_add_measure_tsum_Ico_zpow [measurable_space α] (μ : measure α) {f : α → ℝ≥0∞} (hf : measurable f) {s : set α} (hs : measurable_set s) {t : ℝ≥0} (ht : 1 < t) : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' {∞}) + ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))) := begin have A : μ s = μ (s ∩ f⁻¹' {0}) + μ (s ∩ f⁻¹' (Ioi 0)), { rw ← measure_union, { congr' 1, ext x, have : 0 = f x ∨ 0 < f x := eq_or_lt_of_le bot_le, rw eq_comm at this, simp only [←and_or_distrib_left, this, mem_singleton_iff, mem_inter_eq, and_true, mem_union_eq, mem_Ioi, mem_preimage], }, { apply disjoint_left.2 (λ x hx h'x, _), have : 0 < f x := h'x.2, exact lt_irrefl 0 (this.trans_le hx.2.le) }, { exact hs.inter (hf (measurable_set_singleton _)) }, { exact hs.inter (hf measurable_set_Ioi) } }, have B : μ (s ∩ f⁻¹' (Ioi 0)) = μ (s ∩ f⁻¹' {∞}) + μ (s ∩ f⁻¹' (Ioo 0 ∞)), { rw ← measure_union, { rw ← inter_union_distrib_left, congr, ext x, simp only [mem_singleton_iff, mem_union_eq, mem_Ioo, mem_Ioi, mem_preimage], have H : f x = ∞ ∨ f x < ∞ := eq_or_lt_of_le le_top, cases H, { simp only [H, eq_self_iff_true, or_false, with_top.zero_lt_top, not_top_lt, and_false] }, { simp only [H, H.ne, and_true, false_or] } }, { apply disjoint_left.2 (λ x hx h'x, _), have : f x < ∞ := h'x.2.2, exact lt_irrefl _ (this.trans_le (le_of_eq hx.2.symm)) }, { exact hs.inter (hf (measurable_set_singleton _)) }, { exact hs.inter (hf measurable_set_Ioo) } }, have C : μ (s ∩ f⁻¹' (Ioo 0 ∞)) = ∑' (n : ℤ), μ (s ∩ f⁻¹' (Ico (t^n) (t^(n+1)))), { rw [← measure_Union, ennreal.Ioo_zero_top_eq_Union_Ico_zpow (ennreal.one_lt_coe_iff.2 ht) ennreal.coe_ne_top, preimage_Union, inter_Union], { assume i j, simp only [function.on_fun], wlog h : i ≤ j := le_total i j using [i j, j i] tactic.skip, { assume hij, replace hij : i + 1 ≤ j := lt_of_le_of_ne h hij, apply disjoint_left.2 (λ x hx h'x, lt_irrefl (f x) _), calc f x < t ^ (i + 1) : hx.2.2 ... ≤ t ^ j : ennreal.zpow_le_of_le (ennreal.one_le_coe_iff.2 ht.le) hij ... ≤ f x : h'x.2.1 }, { assume hij, rw disjoint.comm, exact this hij.symm } }, { assume n, exact hs.inter (hf measurable_set_Ico) } }, rw [A, B, C, add_assoc], end section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := begin convert is_pi_system_Ioo (coe : ℚ → ℝ) (coe : ℚ → ℝ), ext x, simp [eq_comm] end /-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals with rational endpoints for a locally finite measure `μ` on `ℝ`. -/ def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] : μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) := { set := λ n, Ioo (-(n + 1)) (n + 1), set_mem := λ n, begin simp only [mem_Union, mem_singleton_iff], refine ⟨-(n + 1), n + 1, _, by norm_cast⟩, exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos end, finite := λ n, measure_Ioo_lt_top, spanning := Union_eq_univ_iff.2 $ λ x, ⟨⌊|x|⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (nat.lt_floor_add_one _)), (le_abs_self x).trans_lt (nat.lt_floor_add_one _)⟩ } lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := (finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $ by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h } lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}), apply le_antisymm _ (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩, rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, g.measurable_set' (Iio q) := λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := nnreal.continuous_of_real.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_comp_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_comp_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← with_top.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.ennreal_tsum' {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (∑' i, f i) := begin convert measurable.ennreal_tsum h, ext1 x, exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)), end @[measurability] lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_comp_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_group variables [normed_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, nnnorm (f a)) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_group section limits variables [measurable_space β] [metric_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff], have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) := λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq, simp_rw [← this], show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))), exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs, end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) /-- A limit (over a general filter) of measurable functions valued in a metric space is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antitone_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap, rw [tendsto_pi], rw [tendsto_pi] at lim, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← h1s.mem_iff_inf_dist_zero h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a metric space is measurable. -/ lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : ae_measurable g μ := begin let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)), let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto, let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some, refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩, refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _, refine tendsto_pi.mpr (λ x, _), simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, }, { exact tendsto_const_nhds, }, end lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) := begin let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l), have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0, from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f 0 x⟩ : nonempty β).some), have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { intros x hx_conv, simp only [f_lim, hx_conv, dif_pos], exact (hp_mem x hx_conv).some_spec, }, have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n), exact (hp_mem x h).some_spec, }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _), exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), }, have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] variables [opens_measurable_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nondiscrete_normed_field section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := (closed_embedding_smul_left hc).measurable_embedding.measurable_comp_iff lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := (closed_embedding_smul_left hc).measurable_embedding.ae_measurable_comp_iff end normed_space
b78f537ef05a931129617af89b43db79bc70f14a
6305b69bc7636a761e1a1947508bb5ebad93cb7e
/tests/lean/run/coinductive.lean
31e446b7eb4c010b106510fef3716d9ed8da727c
[ "Apache-2.0" ]
permissive
HGldJ1966/lean
e7f0068f8a69fde3593b77d8a44609ae446d7738
049d940167c419cd5935d12b459c0695d8615ae9
refs/heads/master
1,611,340,395,700
1,503,103,829,000
1,503,103,829,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,568
lean
/- test cases for coinductive predicates -/ universe u def stream (α : Type u) := nat → α constant stream.cons {α} : α → stream α → stream α constant stream.head {α} : stream α → α constant stream.tail {α} : stream α → stream α notation h :: t := stream.cons h t coinductive all_stream {α : Type u} (s : set α) : stream α → Prop | step {} : ∀{a : α} {ω : stream α}, a ∈ s → all_stream ω → all_stream (a :: ω) #print prefix all_stream #check (@all_stream : Π {α : Type u}, set α → stream α → Prop) #check (@all_stream.step : ∀ {α : Type u} {s : set α} {a : α} {ω : stream α}, a ∈ s → all_stream s ω → all_stream s (a :: ω)) #check (@all_stream.corec_functional : ∀ {α : Type u} (s : set α) (C : stream α → Prop), (∀ (a : stream α), C a → all_stream.functional s C a) → ∀ (a : stream α), C a → all_stream s a) coinductive all_stream' {α : Type u} (s : set α) : stream α → Prop | step {} : ∀{ω : stream α}, stream.head ω ∈ s → all_stream' (stream.tail ω) → all_stream' ω coinductive alt_stream : stream bool → Prop | tt_step : ∀{ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω) | ff_step : ∀{ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω) #print prefix alt_stream #check (@alt_stream : stream bool → Prop) #check (@alt_stream.tt_step : ∀ {ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω)) #check (@alt_stream.ff_step : ∀ {ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω)) #check (@alt_stream.corec_functional : ∀ (C : stream bool → Prop), (∀ (a : stream bool), C a → alt_stream.functional C a) → ∀ (a : stream bool), C a → alt_stream a) mutual coinductive tt_stream, ff_stream with tt_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, ff_stream ω → tt_stream (stream.cons tt ω) with ff_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, tt_stream ω → ff_stream (stream.cons ff ω) #print prefix tt_stream #print prefix ff_stream #check (@tt_stream : stream bool → Prop) #check (@tt_stream.corec_functional : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_tt_stream a → tt_stream a) #check (@ff_stream : stream bool → Prop) #check (@ff_stream.corec_functional : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_ff_stream a → ff_stream a) mutual coinductive tt_ff_stream, ff_tt_stream with tt_ff_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, tt_ff_stream ω ∨ ff_tt_stream ω → tt_ff_stream (stream.cons tt ω) with ff_tt_stream : stream bool → Prop | step {} : ∀{ω : stream bool}, ff_tt_stream ω ∨ tt_ff_stream ω → ff_tt_stream (stream.cons ff ω) #print prefix tt_ff_stream inductive all_list {α : Type} (p : α → Prop) : list α → Prop | nil : all_list [] | cons : ∀a xs, p a → all_list xs → all_list (a :: xs) @[monotonicity] lemma monotonicity.all_list {α : Type} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : ∀xs, implies (all_list p xs) (all_list q xs) | ._ (all_list.nil ._) := all_list.nil _ | ._ (all_list.cons a xs ha hxs) := all_list.cons _ _ (h a ha) (monotonicity.all_list _ hxs) mutual coinductive walk_a, walk_b {α β : Type} (f : α → list β) (g : β → α) (p : α → Prop) (t : α → Prop) with walk_a : α → Prop | step : ∀a, all_list walk_b (f a) → p a → walk_a a | term : ∀a, t a → walk_a a with walk_b : β → Prop | step : ∀b, walk_a (g b) → walk_b b coinductive walk_list {α : Type} (f : α → list α) (p : α → Prop) : ℕ → α → Prop | step : ∀n a, all_list (walk_list n) (f a) → p a → walk_list (n + 1) a -- #check walk_a.corec_on example {f : ℕ → list ℕ} {a' : ℕ} {n : ℕ} {a : fin n}: walk_list f (λ a'', a'' = a') (n + 1) a' := begin coinduction walk_list.corec_on generalizing a n, show ∃ (n : ℕ), all_list (λ (a : ℕ), ∃ {n_1 : ℕ} {a_1 : fin n_1}, n_1 + 1 = n ∧ a' = a) (f a') ∧ a' = a' ∧ n + 1 = a_1 + 1, admit end
67acfd38576eaac53daa503b101dc3a7d49507aa
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch4/ex0102.lean
153379fc37447402ad4c24fcb265126e81b4de69
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
185
lean
variables (α : Type) (p q : α → Prop) example : (∀ x : α, p x ∧ q x) → ∀ x : α, p x := assume h : ∀ x : α, p x ∧ q x, assume z : α, show p z, from (h z).left
ca45c44b4eba15dc4b6181da31e0a424a1a79cad
42610cc2e5db9c90269470365e6056df0122eaa0
/hott/hit/groupoid_quotient.hlean
b22bf2cc074a063f7ce947533f7fdf6f3b98dcb8
[ "Apache-2.0" ]
permissive
tomsib2001/lean
2ab59bfaebd24a62109f800dcf4a7139ebd73858
eb639a7d53fb40175bea5c8da86b51d14bb91f76
refs/heads/master
1,586,128,387,740
1,468,968,950,000
1,468,968,950,000
61,027,234
0
0
null
1,465,813,585,000
1,465,813,585,000
null
UTF-8
Lean
false
false
9,550
hlean
/- Copyright (c) 2015-16 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn The groupoid quotient. This is a 1-type which path spaces is the same as the morphisms a given groupoid. We define it as the 1-truncation of a two quotient. -/ import algebra.category.groupoid .two_quotient homotopy.connectedness algebra.group_theory open trunc_two_quotient eq bool unit relation category e_closure iso is_trunc trunc equiv is_equiv group namespace groupoid_quotient section parameter (G : Groupoid) inductive groupoid_quotient_R : G → G → Type := | Rmk : Π{a b : G} (f : a ⟶ b), groupoid_quotient_R a b open groupoid_quotient_R local abbreviation R := groupoid_quotient_R inductive groupoid_quotient_Q : Π⦃x y : G⦄, e_closure groupoid_quotient_R x y → e_closure groupoid_quotient_R x y → Type := | Qconcat : Π{a b c : G} (g : b ⟶ c) (f : a ⟶ b), groupoid_quotient_Q [Rmk (g ∘ f)] ([Rmk f] ⬝r [Rmk g]) open groupoid_quotient_Q local abbreviation Q := groupoid_quotient_Q definition groupoid_quotient := trunc_two_quotient 1 R Q local attribute groupoid_quotient [reducible] definition is_trunc_groupoid_quotient [instance] : is_trunc 1 groupoid_quotient := _ parameter {G} variables {a b c : G} definition elt (a : G) : groupoid_quotient := incl0 a definition pth (f : a ⟶ b) : elt a = elt b := incl1 (Rmk f) definition resp_comp (g : b ⟶ c) (f : a ⟶ b) : pth (g ∘ f) = pth f ⬝ pth g := incl2 (Qconcat g f) definition resp_id (a : G) : pth (ID a) = idp := begin apply cancel_right (pth (id)), refine _ ⬝ !idp_con⁻¹, refine !resp_comp⁻¹ ⬝ _, exact ap pth !id_id, end definition resp_inv (f : a ⟶ b) : pth (f⁻¹) = (pth f)⁻¹ := begin apply eq_inv_of_con_eq_idp', refine !resp_comp⁻¹ ⬝ _, refine ap pth !right_inverse ⬝ _, apply resp_id end protected definition rec {P : groupoid_quotient → Type} [Πx, is_trunc 1 (P x)] (Pe : Πg, P (elt g)) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a =[pth f] Pe b) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), change_path (resp_comp g f) (Pp (g ∘ f)) = Pp f ⬝o Pp g) (x : groupoid_quotient) : P x := begin induction x, { apply Pe}, { induction s with a b f, apply Pp}, { induction q with a b c g f, apply Pcomp} end protected definition rec_on {P : groupoid_quotient → Type} [Πx, is_trunc 1 (P x)] (x : groupoid_quotient) (Pe : Πg, P (elt g)) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a =[pth f] Pe b) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), change_path (resp_comp g f) (Pp (g ∘ f)) = Pp f ⬝o Pp g) : P x := rec Pe Pp Pcomp x protected definition set_rec {P : groupoid_quotient → Type} [Πx, is_set (P x)] (Pe : Πg, P (elt g)) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a =[pth f] Pe b) (x : groupoid_quotient) : P x := rec Pe Pp !center x protected definition prop_rec {P : groupoid_quotient → Type} [Πx, is_prop (P x)] (Pe : Πg, P (elt g)) (x : groupoid_quotient) : P x := rec Pe !center !center x definition rec_pth {P : groupoid_quotient → Type} [Πx, is_trunc 1 (P x)] {Pe : Πg, P (elt g)} {Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a =[pth f] Pe b} (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), change_path (resp_comp g f) (Pp (g ∘ f)) = Pp f ⬝o Pp g) {a b : G} (f : a ⟶ b) : apd (rec Pe Pp Pcomp) (pth f) = Pp f := proof !rec_incl1 qed protected definition elim {P : Type} [is_trunc 1 P] (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) (x : groupoid_quotient) : P := begin induction x, { exact Pe a}, { induction s with a b f, exact Pp f}, { induction q with a b c g f, exact Pcomp g f} end protected definition elim_on [reducible] {P : Type} [is_trunc 1 P] (x : groupoid_quotient) (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) : P := elim Pe Pp Pcomp x protected definition set_elim [reducible] {P : Type} [is_set P] (Pe : G → P) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b) (x : groupoid_quotient) : P := elim Pe Pp !center x protected definition prop_elim [reducible] {P : Type} [is_prop P] (Pe : G → P) (x : groupoid_quotient) : P := elim Pe !center !center x definition elim_pth {P : Type} [is_trunc 1 P] {Pe : G → P} {Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b} (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) {a b : G} (f : a ⟶ b) : ap (elim Pe Pp Pcomp) (pth f) = Pp f := !elim_incl1 -- The following rule is also true because P is a 1-type, and can be proven by `!is_set.elims` -- The following is the canonical proofs which holds for any truncated two-quotient. theorem elim_resp_comp {P : Type} [is_trunc 1 P] {Pe : G → P} {Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a = Pe b} (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b), Pp (g ∘ f) = Pp f ⬝ Pp g) {a b c : G} (g : b ⟶ c) (f : a ⟶ b) : square (ap02 (elim Pe Pp Pcomp) (resp_comp g f)) (Pcomp g f) (elim_pth Pcomp (g ∘ f)) (!ap_con ⬝ (elim_pth Pcomp f ◾ elim_pth Pcomp g)) := proof !elim_incl2 qed protected definition elim_set.{u} (Pe : G → Set.{u}) (Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a ≃ Pe b) (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b) (x : Pe a), Pp (g ∘ f) x = Pp g (Pp f x)) (x : groupoid_quotient) : Set.{u} := elim Pe (λa b f, tua (Pp f)) (λa b c g f, ap tua (equiv_eq (Pcomp g f)) ⬝ !tua_trans) x theorem elim_set_pth {Pe : G → Set} {Pp : Π⦃a b⦄ (f : a ⟶ b), Pe a ≃ Pe b} (Pcomp : Π⦃a b c⦄ (g : b ⟶ c) (f : a ⟶ b) (x : Pe a), Pp (g ∘ f) x = Pp g (Pp f x)) {a b : G} (f : a ⟶ b) : transport (elim_set Pe Pp Pcomp) (pth f) = Pp f := by rewrite [tr_eq_cast_ap_fn, ↑elim_set, ▸*, ap_compose' trunctype.carrier, elim_pth]; apply tcast_tua_fn end end groupoid_quotient attribute groupoid_quotient.elt [constructor] attribute groupoid_quotient.rec groupoid_quotient.elim [unfold 7] [recursor 7] attribute groupoid_quotient.rec_on groupoid_quotient.elim_on [unfold 4] attribute groupoid_quotient.set_rec groupoid_quotient.set_elim [unfold 6] attribute groupoid_quotient.prop_rec groupoid_quotient.prop_elim groupoid_quotient.elim_set [unfold 5] open sigma pi is_conn function namespace groupoid_quotient section universe variables u v variables {G : Groupoid.{u v}} (a : G) {b c : G} include a protected definition code [unfold 3] (x : groupoid_quotient G) : Set.{v} := begin refine groupoid_quotient.elim_set _ _ _ x, { intro b, exact homset a b}, { intro b c g, exact equiv_postcompose g}, { intro b c d h g f, esimp at *, apply assoc'} end omit a local abbreviation code [unfold 3] := @groupoid_quotient.code G a variable {a} protected definition encode [unfold 4] (x : groupoid_quotient G) (p : elt a = x) : code a x := transport (code a) p (ID a) protected definition decode [unfold 3] (x : groupoid_quotient G) (z : code a x) : elt a = x := begin induction x using groupoid_quotient.set_rec with b b c g, { esimp, exact pth z}, { apply arrow_pathover_left, esimp, intro f, apply eq_pathover_constant_left_id_right, apply square_of_eq, refine !resp_comp⁻¹ ⬝ _ ⬝ !idp_con⁻¹, rewrite elim_set_pth} end local abbreviation encode [unfold_full] := @groupoid_quotient.encode G a local abbreviation decode [unfold 3] := @groupoid_quotient.decode G a protected definition decode_encode (x : groupoid_quotient G) (p : elt a = x) : decode x (encode x p) = p := begin induction p, esimp, apply resp_id end protected definition encode_decode (x : groupoid_quotient G) (z : code a x) : encode x (decode x z) = z := begin induction x using groupoid_quotient.prop_rec with b, esimp, refine ap10 !elim_set_pth.{u v v} (ID a) ⬝ _, esimp, apply id_right end definition decode_comp (z : code a (elt b)) (z' : code b (elt c)) : decode (elt c) (z' ∘ z) = decode (elt b) z ⬝ decode (elt c) z' := !resp_comp variables (a b) definition elt_eq_elt_equiv [constructor] : (elt a = elt b) ≃ (a ⟶ b) := equiv.MK (encode (elt b)) (decode (elt b)) (groupoid_quotient.encode_decode (elt b)) (groupoid_quotient.decode_encode (elt b)) variables {a b} definition encode_con (p : elt a = elt b) (q : elt b = elt c) : encode (elt c) (p ⬝ q) = encode (elt c) q ∘ encode (elt b) p := begin apply eq_of_fn_eq_fn (elt_eq_elt_equiv a c)⁻¹ᵉ, refine !right_inv ⬝ _ ⬝ !decode_comp⁻¹, apply concat2, do 2 exact (to_left_inv !elt_eq_elt_equiv _)⁻¹ end variable (G) definition is_conn_groupoid_quotient [H : is_conn 0 G] : is_conn 0 (groupoid_quotient G) := begin have g : trunc 0 G, from !center, induction g with g, have p : Πh, ∥ g = h ∥, begin intro h, refine !tr_eq_tr_equiv _, apply is_prop.elim end, fapply is_contr.mk, { apply trunc_functor 0 elt (tr g)}, { intro x, induction x with x, induction x using groupoid_quotient.prop_rec with b, esimp, induction p b with q, exact ap (tr ∘ elt) q} end end end groupoid_quotient
efa5b5902c466e36caace40afbab53c209661193
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/analysis/mean_inequalities.lean
5ad930db7a12e7df97ef3845b1fdee40c1c0cac7
[ "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
22,689
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import analysis.convex.specific_functions import analysis.special_functions.pow import data.real.conjugate_exponents import tactic.nth_rewrite /-! # Mean value inequalities In this file we prove several inequalities, including AM-GM inequality, Young's inequality, Hölder inequality, and Minkowski inequality. ## Main theorems ### AM-GM inequality: The inequality says that the geometric mean of a tuple of non-negative numbers is less than or equal to their arithmetic mean. We prove the weighted version of this inequality: if $w$ and $z$ are two non-negative vectors and $\sum_{i\in s} w_i=1$, then $$ \prod_{i\in s} z_i^{w_i} ≤ \sum_{i\in s} w_iz_i. $$ The classical version is a special case of this inequality for $w_i=\frac{1}{n}$. We prove a few versions of this inequality. Each of the following lemmas comes in two versions: a version for real-valued non-negative functions is in the `real` namespace, and a version for `nnreal`-valued functions is in the `nnreal` namespace. - `geom_mean_le_arith_mean_weighted` : weighted version for functions on `finset`s; - `geom_mean_le_arith_mean2_weighted` : weighted version for two numbers; - `geom_mean_le_arith_mean3_weighted` : weighted version for three numbers. ### Generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`fpow_arith_mean_le_arith_mean_fpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ### Young's inequality Young's inequality says that for non-negative numbers `a`, `b`, `p`, `q` such that $\frac{1}{p}+\frac{1}{q}=1$ we have $$ ab ≤ \frac{a^p}{p} + \frac{b^q}{q}. $$ This inequality is a special case of the AM-GM inequality. It can be used to prove Hölder's inequality (see below) but we use a different proof. ### Hölder's inequality The inequality says that for two conjugate exponents `p` and `q` (i.e., for two positive numbers such that $\frac{1}{p}+\frac{1}{q}=1$) and any two non-negative vectors their inner product is less than or equal to the product of the $L_p$ norm of the first vector and the $L_q$ norm of the second vector: $$ \sum_{i\in s} a_ib_i ≤ \sqrt[p]{\sum_{i\in s} a_i^p}\sqrt[q]{\sum_{i\in s} b_i^q}. $$ We give versions of this result in `real`, `nnreal` and `ennreal`. There are at least two short proofs of this inequality. In one proof we prenormalize both vectors, then apply Young's inequality to each $a_ib_i$. We use a different proof deducing this inequality from the generalized mean inequality for well-chosen vectors and weights. ### Minkowski's inequality The inequality says that for `p ≥ 1` the function $$ \|a\|_p=\sqrt[p]{\sum_{i\in s} a_i^p} $$ satisfies the triangle inequality $\|a+b\|_p\le \|a\|_p+\|b\|_p$. We give versions of this result in `real`, `nnreal` and `ennreal`. We deduce this inequality from Hölder's inequality. Namely, Hölder inequality implies that $\|a\|_p$ is the maximum of the inner product $\sum_{i\in s}a_ib_i$ over `b` such that $\|b\|_q\le 1$. Now Minkowski's inequality follows from the fact that the maximum value of the sum of two functions is less than or equal to the sum of the maximum values of the summands. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `strict_convex_on` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. - prove integral versions of these inequalities. -/ universes u v open finset open_locale classical nnreal big_operators noncomputable theory variables {ι : Type u} (s : finset ι) namespace real /-- AM-GM inequality: the geometric mean is less than or equal to the arithmetic mean, weighted version for real-valued nonnegative functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) : (∏ i in s, (z i) ^ (w i)) ≤ ∑ i in s, w i * z i := begin -- If some number `z i` equals zero and has non-zero weight, then LHS is 0 and RHS is nonnegative. by_cases A : ∃ i ∈ s, z i = 0 ∧ w i ≠ 0, { rcases A with ⟨i, his, hzi, hwi⟩, rw [prod_eq_zero his], { exact sum_nonneg (λ j hj, mul_nonneg (hw j hj) (hz j hj)) }, { rw hzi, exact zero_rpow hwi } }, -- If all numbers `z i` with non-zero weight are positive, then we apply Jensen's inequality -- for `exp` and numbers `log (z i)` with weights `w i`. { simp only [not_exists, not_and, ne.def, not_not] at A, have := convex_on_exp.map_sum_le hw hw' (λ i _, set.mem_univ $ log (z i)), simp only [exp_sum, (∘), smul_eq_mul, mul_comm (w _) (log _)] at this, convert this using 1; [apply prod_congr rfl, apply sum_congr rfl]; intros i hi, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { exact rpow_def_of_pos hz _ } }, { cases eq_or_lt_of_le (hz i hi) with hz hz, { simp [A i hi hz.symm] }, { rw [exp_log hz] } } } end theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : n.even) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow_of_even hn).map_sum_le hw hw' (λ _ _, trivial) theorem fpow_arith_mean_le_arith_mean_fpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) := (convex_on_fpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := (convex_on_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := begin have : 0 < p := lt_of_lt_of_le zero_lt_one hp, rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one], exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp, all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg], intros i hi, apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] }, end end real namespace nnreal /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for `nnreal`-valued functions. -/ theorem geom_mean_le_arith_mean_weighted (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) : (∏ i in s, (z i) ^ (w i:ℝ)) ≤ ∑ i in s, w i * z i := by exact_mod_cast real.geom_mean_le_arith_mean_weighted _ _ _ (λ i _, (w i).coe_nonneg) (by assumption_mod_cast) (λ i _, (z i).coe_nonneg) /-- The geometric mean is less than or equal to the arithmetic mean, weighted version for two `nnreal` numbers. -/ theorem geom_mean_le_arith_mean2_weighted (w₁ w₂ p₁ p₂ : ℝ≥0) : w₁ + w₂ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) ≤ w₁ * p₁ + w₂ * p₂ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one] using geom_mean_le_arith_mean_weighted (univ : finset (fin 2)) (fin.cons w₁ $ fin.cons w₂ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin_zero_elim) theorem geom_mean_le_arith_mean3_weighted (w₁ w₂ w₃ p₁ p₂ p₃ : ℝ≥0) : w₁ + w₂ + w₃ = 1 → p₁ ^ (w₁:ℝ) * p₂ ^ (w₂:ℝ) * p₃ ^ (w₃:ℝ) ≤ w₁ * p₁ + w₂ * p₂ + w₃ * p₃ := by simpa only [fin.prod_univ_succ, fin.sum_univ_succ, fin.prod_univ_zero, fin.sum_univ_zero, fin.cons_succ, fin.cons_zero, add_zero, mul_one, ← add_assoc, mul_assoc] using geom_mean_le_arith_mean_weighted (univ : finset (fin 3)) (fin.cons w₁ $ fin.cons w₂ $ fin.cons w₃ fin_zero_elim) (fin.cons p₁ $ fin.cons p₂ $ fin.cons p₃ fin_zero_elim) /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp end nnreal namespace real theorem geom_mean_le_arith_mean2_weighted {w₁ w₂ p₁ p₂ : ℝ} (hw₁ : 0 ≤ w₁) (hw₂ : 0 ≤ w₂) (hp₁ : 0 ≤ p₁) (hp₂ : 0 ≤ p₂) (hw : w₁ + w₂ = 1) : p₁ ^ w₁ * p₂ ^ w₂ ≤ w₁ * p₁ + w₂ * p₂ := nnreal.geom_mean_le_arith_mean2_weighted ⟨w₁, hw₁⟩ ⟨w₂, hw₂⟩ ⟨p₁, hp₁⟩ ⟨p₂, hp₂⟩ $ nnreal.coe_eq.1 $ by assumption /-- Young's inequality, a version for nonnegative real numbers. -/ theorem young_inequality_of_nonneg {a b p q : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) (hpq : p.is_conjugate_exponent q) : a * b ≤ a^p / p + b^q / q := by simpa [← rpow_mul, ha, hb, hpq.ne_zero, hpq.symm.ne_zero, div_eq_inv_mul] using geom_mean_le_arith_mean2_weighted hpq.one_div_nonneg hpq.symm.one_div_nonneg (rpow_nonneg_of_nonneg ha p) (rpow_nonneg_of_nonneg hb q) hpq.inv_add_inv_conj /-- Young's inequality, a version for arbitrary real numbers. -/ theorem young_inequality (a b : ℝ) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : a * b ≤ (abs a)^p / p + (abs b)^q / q := calc a * b ≤ abs (a * b) : le_abs_self (a * b) ... = abs a * abs b : abs_mul a b ... ≤ (abs a)^p / p + (abs b)^q / q : real.young_inequality_of_nonneg (abs_nonneg a) (abs_nonneg b) hpq end real namespace nnreal /-- Young's inequality, `ℝ≥0` version. We use `{p q : ℝ≥0}` in order to avoid constructing witnesses of `0 ≤ p` and `0 ≤ q` for the denominators. -/ theorem young_inequality (a b : ℝ≥0) {p q : ℝ≥0} (hp : 1 < p) (hpq : 1 / p + 1 / q = 1) : a * b ≤ a^(p:ℝ) / p + b^(q:ℝ) / q := real.young_inequality_of_nonneg a.coe_nonneg b.coe_nonneg ⟨hp, nnreal.coe_eq.2 hpq⟩ /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ℝ≥0`-valued functions. -/ theorem inner_le_Lp_mul_Lq (f g : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) * (∑ i in s, (g i) ^ q) ^ (1 / q) := begin -- Let `G=∥g∥_q` be the `L_q`-norm of `g`. set G := (∑ i in s, (g i) ^ q) ^ (1 / q), have hGq : G ^ q = ∑ i in s, (g i) ^ q, { rw [← rpow_mul, one_div_mul_cancel hpq.symm.ne_zero, rpow_one], }, -- First consider the trivial case `∥g∥_q=0` by_cases hG : G = 0, { rw [hG, sum_eq_zero, mul_zero], intros i hi, simp only [rpow_eq_zero_iff, sum_eq_zero_iff] at hG, simp [(hG.1 i hi).1] }, { -- Move power from right to left rw [← div_le_iff hG, sum_div], -- Now the inequality follows from the weighted generalized mean inequality -- with weights `w_i` and numbers `z_i` given by the following formulas. set w : ι → ℝ≥0 := λ i, (g i) ^ q / G ^ q, set z : ι → ℝ≥0 := λ i, f i * (G / g i) ^ (q / p), -- Show that the sum of weights equals one have A : ∑ i in s, w i = 1, { rw [← sum_div, hGq, div_self], simpa [rpow_eq_zero_iff, hpq.symm.ne_zero] using hG }, -- LHS of the goal equals LHS of the weighted generalized mean inequality calc (∑ i in s, f i * g i / G) = (∑ i in s, w i * z i) : begin refine sum_congr rfl (λ i hi, _), have : q - q / p = 1, by field_simp [hpq.ne_zero, hpq.symm.mul_eq_add], dsimp only [w, z], rw [← div_rpow, mul_left_comm, mul_div_assoc, ← @inv_div _ _ _ G, inv_rpow, ← div_eq_mul_inv, ← rpow_sub']; simp [this] end -- Apply the generalized mean inequality ... ≤ (∑ i in s, w i * (z i) ^ p) ^ (1 / p) : nnreal.arith_mean_le_rpow_mean s w z A (le_of_lt hpq.one_lt) -- Simplify the right hand side. Terms with `g i ≠ 0` are equal to `(f i) ^ p`, -- the others are zeros. ... ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) : begin refine rpow_le_rpow (sum_le_sum (λ i hi, _)) hpq.one_div_nonneg, dsimp only [w, z], rw [mul_rpow, mul_left_comm, ← rpow_mul _ _ p, div_mul_cancel _ hpq.ne_zero, div_rpow, div_mul_div, mul_comm (G ^ q), mul_div_mul_right], { nth_rewrite 1 [← mul_one ((f i) ^ p)], exact canonically_ordered_semiring.mul_le_mul (le_refl _) (div_self_le _) }, { simpa [hpq.symm.ne_zero] using hG } end } end /-- The `L_p` seminorm of a vector `f` is the greatest value of the inner product `∑ i in s, f i * g i` over functions `g` of `L_q` seminorm less than or equal to one. -/ theorem is_greatest_Lp (f : ι → ℝ≥0) {p q : ℝ} (hpq : p.is_conjugate_exponent q) : is_greatest ((λ g : ι → ℝ≥0, ∑ i in s, f i * g i) '' {g | ∑ i in s, (g i)^q ≤ 1}) ((∑ i in s, (f i)^p) ^ (1 / p)) := begin split, { use λ i, ((f i) ^ p / f i / (∑ i in s, (f i) ^ p) ^ (1 / q)), by_cases hf : ∑ i in s, (f i)^p = 0, { simp [hf, hpq.ne_zero, hpq.symm.ne_zero] }, { have A : p + q - q ≠ 0, by simp [hpq.ne_zero], have B : ∀ y : ℝ≥0, y * y^p / y = y^p, { refine λ y, mul_div_cancel_left_of_imp (λ h, _), simpa [h, hpq.ne_zero] }, simp only [set.mem_set_of_eq, div_rpow, ← sum_div, ← rpow_mul, div_mul_cancel _ hpq.symm.ne_zero, rpow_one, div_le_iff hf, one_mul, hpq.mul_eq_add, ← rpow_sub' _ A, _root_.add_sub_cancel, le_refl, true_and, ← mul_div_assoc, B], rw [div_eq_iff, ← rpow_add hf, hpq.inv_add_inv_conj, rpow_one], simpa [hpq.symm.ne_zero] using hf } }, { rintros _ ⟨g, hg, rfl⟩, apply le_trans (inner_le_Lp_mul_Lq s f g hpq), simpa only [mul_one] using canonically_ordered_semiring.mul_le_mul (le_refl _) (nnreal.rpow_le_one hg (le_of_lt hpq.symm.one_div_pos)) } end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `nnreal`-valued functions. -/ theorem Lp_add_le (f g : ι → ℝ≥0) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := begin -- The result is trivial when `p = 1`, so we can assume `1 < p`. rcases eq_or_lt_of_le hp with rfl|hp, { simp [finset.sum_add_distrib] }, have hpq := real.is_conjugate_exponent_conjugate_exponent hp, have := is_greatest_Lp s (f + g) hpq, simp only [pi.add_apply, add_mul, sum_add_distrib] at this, rcases this.1 with ⟨φ, hφ, H⟩, rw ← H, exact add_le_add ((is_greatest_Lp s f hpq).2 ⟨φ, hφ, rfl⟩) ((is_greatest_Lp s g hpq).2 ⟨φ, hφ, rfl⟩) end end nnreal namespace real variables (f g : ι → ℝ) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : is_conjugate_exponent p q) : ∑ i in s, f i * g i ≤ (∑ i in s, (abs $ f i)^p) ^ (1 / p) * (∑ i in s, (abs $ g i)^q) ^ (1 / q) := begin have := nnreal.coe_le_coe.2 (nnreal.inner_le_Lp_mul_Lq s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hpq), push_cast at this, refine le_trans (sum_le_sum $ λ i hi, _) this, simp only [← abs_mul, le_abs_self] end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (abs $ f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (abs $ f i) ^ p) ^ (1 / p) + (∑ i in s, (abs $ g i) ^ p) ^ (1 / p) := begin have := nnreal.coe_le_coe.2 (nnreal.Lp_add_le s (λ i, ⟨_, abs_nonneg (f i)⟩) (λ i, ⟨_, abs_nonneg (g i)⟩) hp), push_cast at this, refine le_trans (rpow_le_rpow _ (sum_le_sum $ λ i hi, _) _) this; simp [sum_nonneg, rpow_nonneg_of_nonneg, abs_nonneg, le_trans zero_le_one hp, abs_add, rpow_le_rpow] end variables {f g} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with real-valued nonnegative functions. -/ theorem inner_le_Lp_mul_Lq_of_nonneg (hpq : is_conjugate_exponent p q) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : ∑ i in s, f i * g i ≤ (∑ i in s, (f i)^p) ^ (1 / p) * (∑ i in s, (g i)^q) ^ (1 / q) := by convert inner_le_Lp_mul_Lq s f g hpq using 3; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi] /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `real`-valued nonnegative functions. -/ theorem Lp_add_le_of_nonneg (hp : 1 ≤ p) (hf : ∀ i ∈ s, 0 ≤ f i) (hg : ∀ i ∈ s, 0 ≤ g i) : (∑ i in s, (f i + g i) ^ p) ^ (1 / p) ≤ (∑ i in s, (f i) ^ p) ^ (1 / p) + (∑ i in s, (g i) ^ p) ^ (1 / p) := by convert Lp_add_le s f g hp using 2 ; [skip, congr' 1, congr' 1]; apply sum_congr rfl; intros i hi; simp only [abs_of_nonneg, hf i hi, hg i hi, add_nonneg] end real namespace ennreal variables (f g : ι → ennreal) {p q : ℝ} /-- Hölder inequality: the scalar product of two functions is bounded by the product of their `L^p` and `L^q` norms when `p` and `q` are conjugate exponents. Version for sums over finite sets, with `ennreal`-valued functions. -/ theorem inner_le_Lp_mul_Lq (hpq : p.is_conjugate_exponent q) : (∑ i in s, f i * g i) ≤ (∑ i in s, (f i)^p) ^ (1/p) * (∑ i in s, (g i)^q) ^ (1/q) := begin by_cases H : (∑ i in s, (f i)^p) ^ (1/p) = 0 ∨ (∑ i in s, (g i)^q) ^ (1/q) = 0, { replace H : (∀ i ∈ s, f i = 0) ∨ (∀ i ∈ s, g i = 0), by simpa [ennreal.rpow_eq_zero_iff, hpq.pos, hpq.symm.pos, asymm hpq.pos, asymm hpq.symm.pos, sum_eq_zero_iff_of_nonneg] using H, have : ∀ i ∈ s, f i * g i = 0 := λ i hi, by cases H; simp [H i hi], have : (∑ i in s, f i * g i) = (∑ i in s, 0) := sum_congr rfl this, simp [this] }, push_neg at H, by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^q) ^ (1/q) = ⊤, { cases H'; simp [H', -one_div_eq_inv, H] }, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm hpq.pos, asymm hpq.symm.pos, hpq.pos, hpq.symm.pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.inner_le_Lp_mul_Lq _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ _ hpq), push_cast [← ennreal.coe_rpow_of_nonneg, le_of_lt (hpq.pos), le_of_lt (hpq.one_div_pos), le_of_lt (hpq.symm.pos), le_of_lt (hpq.symm.one_div_pos)] at this, convert this using 1; [skip, congr' 2]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi] }, end /-- Minkowski inequality: the `L_p` seminorm of the sum of two vectors is less than or equal to the sum of the `L_p`-seminorms of the summands. A version for `ennreal` valued nonnegative functions. -/ theorem Lp_add_le (hp : 1 ≤ p) : (∑ i in s, (f i + g i) ^ p)^(1/p) ≤ (∑ i in s, (f i)^p) ^ (1/p) + (∑ i in s, (g i)^p) ^ (1/p) := begin by_cases H' : (∑ i in s, (f i)^p) ^ (1/p) = ⊤ ∨ (∑ i in s, (g i)^p) ^ (1/p) = ⊤, { cases H'; simp [H', -one_div_eq_inv] }, have pos : 0 < p := lt_of_lt_of_le zero_lt_one hp, replace H' : (∀ i ∈ s, f i ≠ ⊤) ∧ (∀ i ∈ s, g i ≠ ⊤), by simpa [ennreal.rpow_eq_top_iff, asymm pos, pos, ennreal.sum_eq_top_iff, not_or_distrib] using H', have := ennreal.coe_le_coe.2 (@nnreal.Lp_add_le _ s (λ i, ennreal.to_nnreal (f i)) (λ i, ennreal.to_nnreal (g i)) _ hp), push_cast [← ennreal.coe_rpow_of_nonneg, le_of_lt (pos), le_of_lt (one_div_pos_of_pos pos)] at this, convert this using 2; [skip, congr' 1, congr' 1]; { apply finset.sum_congr rfl (λ i hi, _), simp [H'.1 i hi, H'.2 i hi] } end end ennreal
fb31187f08312e7bc65afc73974be2da60d9a406
ece1fcd81204f318535500cde1f3c6433de98f46
/src/affine_algebraic_set/basic.lean
0e1dcea60459db0a5a9bf21a1905dd5783ce23bd
[ "Apache-2.0" ]
permissive
stjordanis/M4P33
ab5d90bda269428aee16885dbd33f0d21d7d2f79
d3b56421fcb03b935d9012e5a5b35e1c1ad0b0b4
refs/heads/master
1,607,921,471,294
1,579,298,081,000
1,579,298,081,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,313
lean
/- Copyright (c) 2020 Kevin Buzzard Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, and whoever else wants to join in. -/ import data.mv_polynomial -- We want to be able to talk about V ⊆ W if V and W are affine algebraic sets -- We will need import order.lattice at some point. /-! # Affine algebraic sets This file defines affine algebraic subsets of affine n-space and proves basic properties about them. ## Important definitions * `affine_algebraic_set k n` -- the type of affine algebraic subsets of kⁿ. ## Notation None as yet -- do we need 𝔸ⁿ for affine n-space? ## Implementation notes None yet. ## References Martin Orr's lecture notes https://homepages.warwick.ac.uk/staff/Martin.Orr/2017-8/alg-geom/ ## Tags algebraic geometry, algebraic variety -/ -- let k be a commutative ring variables {k : Type*} [comm_ring k] -- and let n be a natural number variable {n : ℕ} -- In Lean, the multivariable polynomial ring k[X₁, X₂, ..., Xₙ] is -- denoted `mv_polynomial (fin n) k`. We could use better notation. -- The set kⁿ is denoted `fin n → k` (which means maps from {0,1,2,...,(n-1)} to k). -- We now make some definitions which we'll need in the course. namespace mv_polynomial -- means "multivariable polynomial" /-- The set of zeros in kⁿ of a function f ∈ k[X₁, X₂, ..., Xₙ] -/ def zeros (f : mv_polynomial (fin n) k) : set (fin n → k) := {x | f.eval x = 0} -- I just want to write f(x) = 0 really /-- x is in the zeros of f iff f(x) = 0 -/ @[simp] lemma mem_zeros (f : mv_polynomial (fin n) k) (x : fin n → k) : x ∈ f.zeros ↔ f.eval x = 0 := iff.rfl -- note that the next result needs that k is a field. /-- The zeros of f * g are the union of the zeros of f and of g -/ lemma zeros_mul {k : Type*} [discrete_field k] (f g : mv_polynomial (fin n) k) : zeros (f * g) = zeros f ∪ zeros g := begin -- two sets are equal if they have the same elements ext, -- and now it's not hard to prove using `mem_zeros` and other -- equalities known to Lean's simplifier. simp, -- TODO -- should I give the full proof here? end end mv_polynomial open mv_polynomial /-- An affine algebraic subset of kⁿ is the common zeros of a set of polynomials -/ structure affine_algebraic_set (k : Type*) [comm_ring k] (n : ℕ) := -- a subset of the set of maps {0,1,2,...,n-1} → k (called "carrier") (carrier : set (fin n → k)) -- ...such that there's a set of polynomials such that the carrier is equal to the -- intersection of the zeros of the polynomials in the set. (is_algebraic' : ∃ S : set (mv_polynomial (fin n) k), carrier = ⋂ f ∈ S, zeros f) -- ...such that namespace affine_algebraic_set -- this is invisible notation so mathematicians don't need to understand the definition instance : has_coe_to_fun (affine_algebraic_set k n) := { F := λ _, _, coe := carrier } -- use `is_algebraic'` not `is_alegbraic` because the notation's right -- no "carrier". def is_algebraic (V : affine_algebraic_set k n) : ∃ S : set (mv_polynomial (fin n) k), (V : set _) = ⋂ f ∈ S, zeros f := affine_algebraic_set.is_algebraic' V -- Now some basic facts about affine algebraic subsets. /-- Two affine algebraic subsets with the same carrier are equal! -/ lemma ext {V W : affine_algebraic_set k n} : (V : set _) = W → V = W := begin intro h, cases V, cases W, simpa, -- TODO -- why no debugging output? end -- Do I want this instance? -- /-- We can talk about elements of affine algebraic subsets of kⁿ -/ -- instance : has_mem (fin n → k) (affine_algebraic_set k n) := -- ⟨λ x V, x ∈ V.carrier⟩ -- Computer scientists insist on using ≤ for any order relation such as ⊆ . -- It is some sort of problem with notation I think. instance : has_le (affine_algebraic_set k n) := ⟨λ V W, (V : set (fin n → k)) ⊆ W⟩ instance : partial_order (affine_algebraic_set k n) := { le := (≤), le_refl := λ _ _, id, le_trans := λ _ _ _, set.subset.trans, le_antisymm := λ U V hUV hVU, ext (set.subset.antisymm hUV hVU) } /-- Mathematicians want to talk about affine algebraic subsets of kⁿ being subsets of one another -/ instance : has_subset (affine_algebraic_set k n) := ⟨affine_algebraic_set.has_le.le⟩ end affine_algebraic_set
ed25066094ab66fc307f42859b08822ffb136c69
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/zmod/quotient.lean
3b4fedf4093b5524093509283dadc3c1a23bb240
[ "Apache-2.0" ]
permissive
kbuzzard/mathlib
2ff9e85dfe2a46f4b291927f983afec17e946eb8
58537299e922f9c77df76cb613910914a479c1f7
refs/heads/master
1,685,313,702,744
1,683,974,212,000
1,683,974,212,000
128,185,277
1
0
null
1,522,920,600,000
1,522,920,600,000
null
UTF-8
Lean
false
false
7,605
lean
/- Copyright (c) 2021 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import data.zmod.basic import group_theory.group_action.quotient import ring_theory.int.basic import ring_theory.ideal.quotient_operations /-! # `zmod n` and quotient groups / rings This file relates `zmod n` to the quotient group `quotient_add_group.quotient (add_subgroup.zmultiples n)` and to the quotient ring `(ideal.span {n}).quotient`. ## Main definitions - `zmod.quotient_zmultiples_nat_equiv_zmod` and `zmod.quotient_zmultiples_equiv_zmod`: `zmod n` is the group quotient of `ℤ` by `n ℤ := add_subgroup.zmultiples (n)`, (where `n : ℕ` and `n : ℤ` respectively) - `zmod.quotient_span_nat_equiv_zmod` and `zmod.quotient_span_equiv_zmod`: `zmod n` is the ring quotient of `ℤ` by `n ℤ : ideal.span {n}` (where `n : ℕ` and `n : ℤ` respectively) - `zmod.lift n f` is the map from `zmod n` induced by `f : ℤ →+ A` that maps `n` to `0`. ## Tags zmod, quotient group, quotient ring, ideal quotient -/ open quotient_add_group open zmod variables (n : ℕ) {A R : Type*} [add_group A] [ring R] namespace int /-- `ℤ` modulo multiples of `n : ℕ` is `zmod n`. -/ def quotient_zmultiples_nat_equiv_zmod : ℤ ⧸ add_subgroup.zmultiples (n : ℤ) ≃+ zmod n := (quotient_add_equiv_of_eq (zmod.ker_int_cast_add_hom _)).symm.trans $ quotient_ker_equiv_of_right_inverse (int.cast_add_hom (zmod n)) coe int_cast_zmod_cast /-- `ℤ` modulo multiples of `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_zmultiples_equiv_zmod (a : ℤ) : ℤ ⧸ add_subgroup.zmultiples a ≃+ zmod a.nat_abs := (quotient_add_equiv_of_eq (zmultiples_nat_abs a)).symm.trans (quotient_zmultiples_nat_equiv_zmod a.nat_abs) /-- `ℤ` modulo the ideal generated by `n : ℕ` is `zmod n`. -/ def quotient_span_nat_equiv_zmod : ℤ ⧸ ideal.span {↑n} ≃+* zmod n := (ideal.quot_equiv_of_eq (zmod.ker_int_cast_ring_hom _)).symm.trans $ ring_hom.quotient_ker_equiv_of_right_inverse $ show function.right_inverse coe (int.cast_ring_hom (zmod n)), from int_cast_zmod_cast /-- `ℤ` modulo the ideal generated by `a : ℤ` is `zmod a.nat_abs`. -/ def quotient_span_equiv_zmod (a : ℤ) : ℤ ⧸ ideal.span ({a} : set ℤ) ≃+* zmod a.nat_abs := (ideal.quot_equiv_of_eq (span_nat_abs a)).symm.trans (quotient_span_nat_equiv_zmod a.nat_abs) end int namespace add_action open add_subgroup add_monoid_hom add_equiv function variables {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) /-- The quotient `(ℤ ∙ a) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((+ᵥ) a) b`. -/ noncomputable def zmultiples_quotient_stabilizer_equiv : zmultiples a ⧸ stabilizer (zmultiples a) b ≃+ zmod (minimal_period ((+ᵥ) a) b) := (of_bijective (map _ (stabilizer (zmultiples a) b) (zmultiples_hom (zmultiples a) ⟨a, mem_zmultiples a⟩) (by { rw [zmultiples_le, mem_comap, mem_stabilizer_iff, zmultiples_hom_apply, coe_nat_zsmul, ←vadd_iterate], exact is_periodic_pt_minimal_period ((+ᵥ) a) b })) ⟨by { rw [←ker_eq_bot_iff, eq_bot_iff], refine λ q, induction_on' q (λ n hn, _), rw [mem_bot, eq_zero_iff, int.mem_zmultiples_iff, ←zsmul_vadd_eq_iff_minimal_period_dvd], exact (eq_zero_iff _).mp hn }, λ q, induction_on' q (λ ⟨_, n, rfl⟩, ⟨n, rfl⟩)⟩).symm.trans (int.quotient_zmultiples_nat_equiv_zmod (minimal_period ((+ᵥ) a) b)) lemma zmultiples_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((+ᵥ) a) b)) : (zmultiples_quotient_stabilizer_equiv a b).symm n = (n : ℤ) • (⟨a, mem_zmultiples a⟩ : zmultiples a) := rfl end add_action namespace mul_action open add_action subgroup add_subgroup function variables {α β : Type*} [group α] (a : α) [mul_action α β] (b : β) local attribute [semireducible] mul_opposite /-- The quotient `(a ^ ℤ) ⧸ (stabilizer b)` is cyclic of order `minimal_period ((•) a) b`. -/ noncomputable def zpowers_quotient_stabilizer_equiv : zpowers a ⧸ stabilizer (zpowers a) b ≃* multiplicative (zmod (minimal_period ((•) a) b)) := let f := zmultiples_quotient_stabilizer_equiv (additive.of_mul a) b in ⟨f.to_fun, f.inv_fun, f.left_inv, f.right_inv, f.map_add'⟩ lemma zpowers_quotient_stabilizer_equiv_symm_apply (n : zmod (minimal_period ((•) a) b)) : (zpowers_quotient_stabilizer_equiv a b).symm n = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (n : ℤ) := rfl /-- The orbit `(a ^ ℤ) • b` is a cycle of order `minimal_period ((•) a) b`. -/ noncomputable def orbit_zpowers_equiv : orbit (zpowers a) b ≃ zmod (minimal_period ((•) a) b) := (orbit_equiv_quotient_stabilizer _ b).trans (zpowers_quotient_stabilizer_equiv a b).to_equiv /-- The orbit `(ℤ • a) +ᵥ b` is a cycle of order `minimal_period ((+ᵥ) a) b`. -/ noncomputable def _root_.add_action.orbit_zmultiples_equiv {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) : add_action.orbit (zmultiples a) b ≃ zmod (minimal_period ((+ᵥ) a) b) := (add_action.orbit_equiv_quotient_stabilizer (zmultiples a) b).trans (zmultiples_quotient_stabilizer_equiv a b).to_equiv attribute [to_additive orbit_zmultiples_equiv] orbit_zpowers_equiv @[to_additive orbit_zmultiples_equiv_symm_apply] lemma orbit_zpowers_equiv_symm_apply (k : zmod (minimal_period ((•) a) b)) : (orbit_zpowers_equiv a b).symm k = (⟨a, mem_zpowers a⟩ : zpowers a) ^ (k : ℤ) • ⟨b, mem_orbit_self b⟩ := rfl lemma orbit_zpowers_equiv_symm_apply' (k : ℤ) : (orbit_zpowers_equiv a b).symm k = (⟨a, mem_zpowers a⟩ : zpowers a) ^ k • ⟨b, mem_orbit_self b⟩ := begin rw [orbit_zpowers_equiv_symm_apply, zmod.coe_int_cast], exact subtype.ext (zpow_smul_mod_minimal_period _ _ k), end lemma _root_.add_action.orbit_zmultiples_equiv_symm_apply' {α β : Type*} [add_group α] (a : α) [add_action α β] (b : β) (k : ℤ) : (add_action.orbit_zmultiples_equiv a b).symm k = (k • (⟨a, mem_zmultiples a⟩ : zmultiples a)) +ᵥ ⟨b, add_action.mem_orbit_self b⟩ := begin rw [add_action.orbit_zmultiples_equiv_symm_apply, zmod.coe_int_cast], exact subtype.ext (zsmul_vadd_mod_minimal_period _ _ k), end attribute [to_additive orbit_zmultiples_equiv_symm_apply'] orbit_zpowers_equiv_symm_apply' @[to_additive] lemma minimal_period_eq_card [fintype (orbit (zpowers a) b)] : minimal_period ((•) a) b = fintype.card (orbit (zpowers a) b) := by rw [←fintype.of_equiv_card (orbit_zpowers_equiv a b), zmod.card] @[to_additive] instance minimal_period_pos [finite $ orbit (zpowers a) b] : ne_zero $ minimal_period ((•) a) b := ⟨begin casesI nonempty_fintype (orbit (zpowers a) b), haveI : nonempty (orbit (zpowers a) b) := (orbit_nonempty b).to_subtype, rw minimal_period_eq_card, exact fintype.card_ne_zero, end⟩ end mul_action section group open subgroup variables {α : Type*} [group α] (a : α) /-- See also `order_eq_card_zpowers`. -/ @[to_additive add_order_eq_card_zmultiples' "See also `add_order_eq_card_zmultiples`."] lemma order_eq_card_zpowers' : order_of a = nat.card (zpowers a) := begin have := nat.card_congr (mul_action.orbit_zpowers_equiv a (1 : α)), rwa [nat.card_zmod, orbit_subgroup_one_eq_self, eq_comm] at this, end variables {a} @[to_additive is_of_fin_add_order.finite_zmultiples] lemma is_of_fin_order.finite_zpowers (h : is_of_fin_order a) : finite $ zpowers a := begin rw [← order_of_pos_iff, order_eq_card_zpowers'] at h, exact nat.finite_of_card_ne_zero h.ne.symm, end end group
86bf40aa5bbdf2f435c1e2205d17b078927e48e5
5e3548e65f2c037cb94cd5524c90c623fbd6d46a
/src_icannos_totilas/aops/2003-Pan_African_MO-Problem_4.lean
4e7dd1b395c40124b23a8df0b4d6957c60829d64
[]
no_license
ahayat16/lean_exos
d4f08c30adb601a06511a71b5ffb4d22d12ef77f
682f2552d5b04a8c8eb9e4ab15f875a91b03845c
refs/heads/main
1,693,101,073,585
1,636,479,336,000
1,636,479,336,000
415,000,441
0
0
null
null
null
null
UTF-8
Lean
false
false
105
lean
import data.real.basic theorem exo: (exists f: nat -> nat, forall n, f^[2003] (n) = 5 * n) := sorry