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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b6a8188d14d9c17329695c6787fffd74a18facec | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/data/finset/sort.lean | 46684f5b8c2a1f7152c23502ff07aa631b9ccbf1 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,798 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.basic
import data.multiset.sort
import data.list.nodup_equiv_fin
/-!
# Construct a sorted list from a finset.
-/
namespace finset
open multiset nat
variables {α β : Type*}
/-! ### sort -/
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
@[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card :=
multiset.length_sort _
end sort
section sort_linear_order
variables [linear_order α]
theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) :
(s.sort (≤)).nth_le 0 h = s.min' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) },
{ have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h),
exact s.min'_le _ this }
end
lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} :
(s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) :=
sorted_zero_eq_min'_aux _ _ _
lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} :
s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) :=
(sorted_zero_eq_min'_aux _ _ _).symm
lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length)
(H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s :=
(finset.mem_sort (≤)).1 (list.nth_le_mem l _ h),
exact s.le_max' _ this },
{ have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt,
exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) },
end
lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} :
(s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h =
s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) :=
sorted_last_eq_max'_aux _ _ _
lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} :
s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1)
(by simpa using nat.sub_lt (card_pos.mpr h) zero_lt_one) :=
(sorted_last_eq_max'_aux _ _ _).symm
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid
casting issues in further uses of this function. -/
def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o s :=
order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $
(s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $
set.ext $ λ x, mem_sort _
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is
the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a
proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to
avoid casting issues in further uses of this function. -/
def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α :=
(order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _)
@[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
↑(order_iso_of_fin s h i) = order_emb_of_fin s h i :=
rfl
lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : s) :
↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x :=
rfl
lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) :=
rfl
@[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
s.order_emb_of_fin h i ∈ s :=
(s.order_iso_of_fin h i).2
@[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) :
set.range (s.order_emb_of_fin h) = s :=
by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)]
/-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/
lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) :=
by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min']
/-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/
lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) :=
by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h]
/-- `order_emb_of_fin {a} h` sends any argument to `a`. -/
@[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) :
order_emb_of_fin {a} (card_singleton a) i = a :=
by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton]
/-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α}
(hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h :=
begin
apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono,
rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj],
refine eq_of_subset_of_card_le (λ x hx, _) _,
{ rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x },
{ rw [h, card_image_of_injective _ hmono.injective, fin_range_card] }
end
/-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α}
(hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h :=
rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono
/-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if
and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l`
(although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/
@[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff
{k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} :
s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) :=
begin
substs k l,
exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _)
end
lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) :
s.card ≤ t.card + 1 :=
begin
have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length,
{ intro i,
rw [finset.length_sort, ←nat.lt_sub_right_iff_add_lt],
exact i.2 },
have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length :=
λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i),
have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i))
((s.sort (≤)).nth_le (i + 1) (h1 i))
((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i)))
((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i)))
(s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)),
let f : fin (s.card - 1) → t :=
λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩,
have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j :=
λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans
(lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij))
(exists_prop.mp (classical.some_spec (p j))).2.1)),
have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm
(not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij))))
(not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))),
rwa [fintype.card_fin, fintype.card_coe, nat.sub_le_right_iff_le_add] at key,
end
end sort_linear_order
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
end finset
|
0df1fc572269b7aa652a2cabacb3fdcc9a2dcad1 | cc060cf567f81c404a13ee79bf21f2e720fa6db0 | /lean/tactics-monad.lean | 51625f3696cf6eca4476cb1a74f910dda80c831c | [
"Apache-2.0"
] | permissive | semorrison/proof | cf0a8c6957153bdb206fd5d5a762a75958a82bca | 5ee398aa239a379a431190edbb6022b1a0aa2c70 | refs/heads/master | 1,610,414,502,842 | 1,518,696,851,000 | 1,518,696,851,000 | 78,375,937 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 110 | lean | open tactic
variables A B : Prop
example : A → B → A ∧ B :=
by do trace "Hi, Mom!",
trace_state
|
078e7883e98e49d663ac1d59d741b5bbaaf60edf | 8930e38ac0fae2e5e55c28d0577a8e44e2639a6d | /tests/tactics.lean | 65d3eeafcb8ecadb186aa911bf47398830732aa2 | [
"Apache-2.0"
] | permissive | SG4316/mathlib | 3d64035d02a97f8556ad9ff249a81a0a51a3321a | a7846022507b531a8ab53b8af8a91953fceafd3a | refs/heads/master | 1,584,869,960,527 | 1,530,718,645,000 | 1,530,724,110,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,673 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic data.set.lattice
section solve_by_elim
example {a b : Prop} (h₀ : a → b) (h₁ : a) : b :=
begin
apply_assumption,
apply_assumption,
end
example {a b : Prop} (h₀ : a → b) (h₁ : a) : b :=
by solve_by_elim
example {α : Type} {a b : α → Prop} (h₀ : ∀ x : α, b x = a x) (y : α) : a y = b y :=
by solve_by_elim
example {α : Type} {p : α → Prop} (h₀ : ∀ x, p x) (y : α) : p y :=
begin
apply_assumption,
end
end solve_by_elim
section tauto₀
variables p q r : Prop
variables h : p ∧ q ∨ p ∧ r
include h
example : p ∧ p :=
by tauto
end tauto₀
section tauto₁
variables α : Type
variables p q r : α → Prop
variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x)
include h
example : ∃ x, p x :=
by tauto
end tauto₁
section tauto₂
variables α : Type
variables x : α
variables p q r : α → Prop
variables h₀ : (∀ x, p x → q x → r x) ∨ r x
variables h₁ : p x
variables h₂ : q x
include h₀ h₁ h₂
example : ∃ x, r x :=
by tauto
end tauto₂
section wlog
example {x y : ℕ} (a : x = 1) : true :=
begin
suffices : false, trivial,
wlog h : x = y,
{ guard_target x = y ∨ y = x,
admit },
{ guard_hyp h := x = y,
guard_hyp a := x = 1,
admit }
end
example {x y : ℕ} : true :=
begin
suffices : false, trivial,
wlog h : x ≤ y,
{ guard_hyp h := x ≤ y,
guard_target false,
admit }
end
example {x y z : ℕ} : true :=
begin
suffices : false, trivial,
wlog h : x ≤ y + z,
{ guard_target x ≤ y + z ∨ x ≤ z + y,
admit },
{ guard_hyp h := x ≤ y + z,
guard_target false,
admit }
end
example {x y z : ℕ} : true :=
begin
suffices : false, trivial,
wlog : x ≤ y + z using x y,
{ guard_target x ≤ y + z ∨ y ≤ x + z,
admit },
{ guard_hyp case := x ≤ y + z,
guard_target false,
admit },
end
example {x : ℕ} (S₀ S₁ : set ℕ) (P : ℕ → Prop)
(h : x ∈ S₀ ∪ S₁) : true :=
begin
suffices : false, trivial,
wlog h' : x ∈ S₀ using S₀ S₁,
{ guard_target x ∈ S₀ ∨ x ∈ S₁,
admit },
{ guard_hyp h := x ∈ S₀ ∪ S₁,
guard_hyp h' := x ∈ S₀,
admit }
end
example {n m i : ℕ} {p : ℕ → ℕ → ℕ → Prop} : true :=
begin
suffices : false, trivial,
wlog : p n m i using [n m i, n i m, i n m],
{ guard_target p n m i ∨ p n i m ∨ p i n m,
admit },
{ guard_hyp case := p n m i,
admit }
end
example {n m i : ℕ} {p : ℕ → Prop} : true :=
begin
suffices : false, trivial,
wlog : p n using [n m i, m n i, i n m],
{ guard_target p n ∨ p m ∨ p i,
admit },
{ guard_hyp case := p n,
admit }
end
example {n m i : ℕ} {p : ℕ → ℕ → Prop} {q : ℕ → ℕ → ℕ → Prop} : true :=
begin
suffices : q n m i, trivial,
have h : p n i ∨ p i m ∨ p m i, from sorry,
wlog : p n i := h using n m i,
{ guard_hyp h := p n i,
guard_target q n m i,
admit },
{ guard_hyp h := p i m,
guard_hyp this := q i m n,
guard_target q n m i,
admit },
{ guard_hyp h := p m i,
guard_hyp this := q m i n,
guard_target q n m i,
admit },
end
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
begin
ext x,
split,
{ intro hyp,
cases hyp,
wlog x_in : x ∈ B using B C,
{ assumption },
{ exact or.inl ⟨hyp_left, x_in⟩ } },
{ intro hyp,
wlog x_in : x ∈ A ∩ B using B C,
{ assumption },
{ exact ⟨x_in.left, or.inl x_in.right⟩ } }
end
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
begin
ext x,
split,
{ intro hyp,
wlog x_in : x ∈ B := hyp.2 using B C,
{ exact or.inl ⟨hyp.1, x_in⟩ } },
{ intro hyp,
wlog x_in : x ∈ A ∩ B := hyp using B C,
{ exact ⟨x_in.left, or.inl x_in.right⟩ } }
end
example (X : Type) (A B C : set X) : A ∩ (B ∪ C) = (A ∩ B) ∪ (A ∩ C) :=
begin
ext x,
split,
{ intro hyp,
cases hyp,
wlog x_in : x ∈ B := hyp_right using B C,
{ exact or.inl ⟨hyp_left, x_in⟩ }, },
{ intro hyp,
wlog x_in : x ∈ A ∩ B := hyp using B C,
{ exact ⟨x_in.left, or.inl x_in.right⟩ } }
end
end wlog
example (m n p q : nat) (h : m + n = p) : true :=
begin
have : m + n = q,
{ generalize_hyp h' : m + n = x at h,
guard_hyp h' := m + n = x,
guard_hyp h := x = p,
guard_target m + n = q,
admit },
have : m + n = q,
{ generalize_hyp h' : m + n = x at h ⊢,
guard_hyp h' := m + n = x,
guard_hyp h := x = p,
guard_target x = q,
admit },
trivial
end
example (α : Sort*) (L₁ L₂ L₃ : list α)
(H : L₁ ++ L₂ = L₃) : true :=
begin
have : L₁ ++ L₂ = L₂,
{ generalize_hyp h : L₁ ++ L₂ = L at H,
induction L with hd tl ih,
case list.nil
{ tactic.cleanup,
change list.nil = L₃ at H,
admit },
case list.cons
{ change hd :: tl = L₃ at H,
admit } },
trivial
end
section convert
open set
variables {α β : Type}
local attribute [simp]
private lemma singleton_inter_singleton_eq_empty {x y : α} :
({x} ∩ {y} = (∅ : set α)) ↔ x ≠ y :=
by simp [singleton_inter_eq_empty]
example {f : β → α} {x y : α} (h : x ≠ y) : f ⁻¹' {x} ∩ f ⁻¹' {y} = ∅ :=
begin
have : {x} ∩ {y} = (∅ : set α) := by simpa using h,
convert preimage_empty,
rw [←preimage_inter,this],
end
end convert
section rcases
universe u
variables {α β γ : Type u}
example (x : α × β × γ) : true :=
begin
rcases x with ⟨a, b, c⟩,
{ guard_hyp a := α,
guard_hyp b := β,
guard_hyp c := γ,
trivial }
end
example (x : α × β × γ) : true :=
begin
rcases x with ⟨a, ⟨b, c⟩⟩,
{ guard_hyp a := α,
guard_hyp b := β,
guard_hyp c := γ,
trivial }
end
example (x : (α × β) × γ) : true :=
begin
rcases x with ⟨⟨a, b⟩, c⟩,
{ guard_hyp a := α,
guard_hyp b := β,
guard_hyp c := γ,
trivial }
end
example (x : inhabited α × option β ⊕ γ) : true :=
begin
rcases x with ⟨⟨a⟩, _ | b⟩ | c,
{ guard_hyp a := α, trivial },
{ guard_hyp a := α, guard_hyp b := β, trivial },
{ guard_hyp c := γ, trivial }
end
example (x y : ℕ) (h : x = y) : true :=
begin
rcases x with _|⟨⟩|z,
{ guard_hyp h := nat.zero = y, trivial },
{ guard_hyp h := nat.succ nat.zero = y, trivial },
{ guard_hyp z := ℕ,
guard_hyp h := z.succ.succ = y, trivial },
end
-- from equiv.sum_empty
example (s : α ⊕ empty) : true :=
begin
rcases s with _ | ⟨⟨⟩⟩,
{ guard_hyp s := α, trivial }
end
end rcases
section ext
example (x y : ℕ) : true :=
begin
have : x = y,
{ ext <|> admit },
have : x = y,
{ ext i <|> admit },
have : x = y,
{ ext 1 <|> admit },
trivial
end
example (X Y : ℕ × ℕ) (h : X.1 = Y.1) (h : X.2 = Y.2) : X = Y :=
begin
ext ; assumption
end
example (X Y : (ℕ → ℕ) × ℕ) (h : ∀ i, X.1 i = Y.1 i) (h : X.2 = Y.2) : X = Y :=
begin
ext x ; solve_by_elim,
end
example (X Y : ℕ → ℕ × ℕ) (h : ∀ i, X i = Y i) : true :=
begin
have : X = Y,
{ ext 1 with i,
guard_target X i = Y i,
admit },
have : X = Y,
{ ext i,
guard_target (X i).fst = (Y i).fst, admit,
guard_target (X i).snd = (Y i).snd, admit, },
have : X = Y,
{ ext 1,
guard_target X x = Y x,
admit },
trivial,
end
def my_foo {α} (x : semigroup α) (y : group α) : true := trivial
example {α : Type} : true :=
begin
have : true,
{ refine_struct (@my_foo α { .. } { .. } ),
-- 9 goals
guard_tags _field mul semigroup, admit,
-- case semigroup, mul
-- α : Type
-- ⊢ α → α → α
guard_tags _field mul_assoc semigroup, admit,
-- case semigroup, mul_assoc
-- α : Type
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
guard_tags _field mul group, admit,
-- case group, mul
-- α : Type
-- ⊢ α → α → α
guard_tags _field mul_assoc group, admit,
-- case group, mul_assoc
-- α : Type
-- ⊢ ∀ (a b c : α), a * b * c = a * (b * c)
guard_tags _field one group, admit,
-- case group, one
-- α : Type
-- ⊢ α
guard_tags _field one_mul group, admit,
-- case group, one_mul
-- α : Type
-- ⊢ ∀ (a : α), 1 * a = a
guard_tags _field mul_one group, admit,
-- case group, mul_one
-- α : Type
-- ⊢ ∀ (a : α), a * 1 = a
guard_tags _field inv group, admit,
-- case group, inv
-- α : Type
-- ⊢ α → α
guard_tags _field mul_left_inv group, admit,
-- case group, mul_left_inv
-- α : Type
-- ⊢ ∀ (a : α), a⁻¹ * a = 1
},
trivial
end
def my_bar {α} (x : semigroup α) (y : group α) (i j : α) : α := i
example {α : Type} : true :=
begin
have : monoid α,
{ refine_struct { mul := my_bar { .. } { .. } },
guard_tags _field mul semigroup, admit,
guard_tags _field mul_assoc semigroup, admit,
guard_tags _field mul group, admit,
guard_tags _field mul_assoc group, admit,
guard_tags _field one group, admit,
guard_tags _field one_mul group, admit,
guard_tags _field mul_one group, admit,
guard_tags _field inv group, admit,
guard_tags _field mul_left_inv group, admit,
guard_tags _field mul_assoc monoid, admit,
guard_tags _field one monoid, admit,
guard_tags _field one_mul monoid, admit,
guard_tags _field mul_one monoid, admit, },
trivial
end
end ext
|
93b993d1fef54810ca5e079d0ae613a283f5927d | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/topology/metric_space/gromov_hausdorff_realized.lean | cc1860ca7f0283cc18501c62d25afc42099a9b8e | [
"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 | 27,426 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import topology.metric_space.gluing
import topology.metric_space.hausdorff_distance
import topology.continuous_function.bounded
/-!
# The Gromov-Hausdorff distance is realized
In this file, we construct of a good coupling between nonempty compact metric spaces, minimizing
their Hausdorff distance. This construction is instrumental to study the Gromov-Hausdorff
distance between nonempty compact metric spaces.
Given two nonempty compact metric spaces `X` and `Y`, we define `optimal_GH_coupling X Y` as a
compact metric space, together with two isometric embeddings `optimal_GH_injl` and `optimal_GH_injr`
respectively of `X` and `Y` into `optimal_GH_coupling X Y`. The main property of the optimal
coupling is that the Hausdorff distance between `X` and `Y` in `optimal_GH_coupling X Y` is smaller
than the corresponding distance in any other coupling. We do not prove completely this fact in this
file, but we show a good enough approximation of this fact in `Hausdorff_dist_optimal_le_HD`, that
will suffice to obtain the full statement once the Gromov-Hausdorff distance is properly defined,
in `Hausdorff_dist_optimal`.
The key point in the construction is that the set of possible distances coming from isometric
embeddings of `X` and `Y` in metric spaces is a set of equicontinuous functions. By Arzela-Ascoli,
it is compact, and one can find such a distance which is minimal. This distance defines a premetric
space structure on `X ⊕ Y`. The corresponding metric quotient is `optimal_GH_coupling X Y`.
-/
noncomputable theory
open_locale classical topological_space nnreal
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section Gromov_Hausdorff_realized
/- This section shows that the Gromov-Hausdorff distance
is realized. For this, we consider candidate distances on the disjoint union
`X ⊕ Y` of two compact nonempty metric spaces, almost realizing the Gromov-Hausdorff
distance, and show that they form a compact family by applying Arzela-Ascoli
theorem. The existence of a minimizer follows. -/
section definitions
variables (X : Type u) (Y : Type v)
[metric_space X] [compact_space X] [nonempty X]
[metric_space Y] [compact_space Y] [nonempty Y]
@[reducible] private def prod_space_fun : Type* := ((X ⊕ Y) × (X ⊕ Y)) → ℝ
@[reducible] private def Cb : Type* := bounded_continuous_function ((X ⊕ Y) × (X ⊕ Y)) ℝ
private def max_var : ℝ≥0 :=
2 * ⟨diam (univ : set X), diam_nonneg⟩ + 1 + 2 * ⟨diam (univ : set Y), diam_nonneg⟩
private lemma one_le_max_var : 1 ≤ max_var X Y := calc
(1 : real) = 2 * 0 + 1 + 2 * 0 : by simp
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) :
by apply_rules [add_le_add, mul_le_mul_of_nonneg_left, diam_nonneg]; norm_num
/-- The set of functions on `X ⊕ Y` that are candidates distances to realize the
minimum of the Hausdorff distances between `X` and `Y` in a coupling -/
def candidates : set (prod_space_fun X Y) :=
{f | (((((∀ x y : X, f (sum.inl x, sum.inl y) = dist x y)
∧ (∀ x y : Y, f (sum.inr x, sum.inr y) = dist x y))
∧ (∀ x y, f (x, y) = f (y, x)))
∧ (∀ x y z, f (x, z) ≤ f (x, y) + f (y, z)))
∧ (∀ x, f (x, x) = 0))
∧ (∀ x y, f (x, y) ≤ max_var X Y) }
/-- Version of the set of candidates in bounded_continuous_functions, to apply
Arzela-Ascoli -/
private def candidates_b : set (Cb X Y) := {f : Cb X Y | (f : _ → ℝ) ∈ candidates X Y}
end definitions --section
section constructions
variables {X : Type u} {Y : Type v}
[metric_space X] [compact_space X] [nonempty X] [metric_space Y] [compact_space Y] [nonempty Y]
{f : prod_space_fun X Y} {x y z t : X ⊕ Y}
local attribute [instance, priority 10] inhabited_of_nonempty'
private lemma max_var_bound : dist x y ≤ max_var X Y := calc
dist x y ≤ diam (univ : set (X ⊕ Y)) :
dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _)
... = diam (inl '' (univ : set X) ∪ inr '' (univ : set Y)) :
by apply congr_arg; ext x y z; cases x; simp [mem_univ, mem_range_self]
... ≤ diam (inl '' (univ : set X)) + dist (inl (default X)) (inr (default Y)) +
diam (inr '' (univ : set Y)) :
diam_union (mem_image_of_mem _ (mem_univ _)) (mem_image_of_mem _ (mem_univ _))
... = diam (univ : set X) + (dist (default X) (default X) + 1 + dist (default Y) (default Y)) +
diam (univ : set Y) :
by { rw [isometry_on_inl.diam_image, isometry_on_inr.diam_image], refl }
... = 1 * diam (univ : set X) + 1 + 1 * diam (univ : set Y) : by simp
... ≤ 2 * diam (univ : set X) + 1 + 2 * diam (univ : set Y) :
begin
apply_rules [add_le_add, mul_le_mul_of_nonneg_right, diam_nonneg, le_refl],
norm_num, norm_num
end
private lemma candidates_symm (fA : f ∈ candidates X Y) : f (x, y) = f (y, x) := fA.1.1.1.2 x y
private lemma candidates_triangle (fA : f ∈ candidates X Y) : f (x, z) ≤ f (x, y) + f (y, z) :=
fA.1.1.2 x y z
private lemma candidates_refl (fA : f ∈ candidates X Y) : f (x, x) = 0 := fA.1.2 x
private lemma candidates_nonneg (fA : f ∈ candidates X Y) : 0 ≤ f (x, y) :=
begin
have : 0 ≤ 2 * f (x, y) := calc
0 = f (x, x) : (candidates_refl fA).symm
... ≤ f (x, y) + f (y, x) : candidates_triangle fA
... = f (x, y) + f (x, y) : by rw [candidates_symm fA]
... = 2 * f (x, y) : by ring,
by linarith
end
private lemma candidates_dist_inl (fA : f ∈ candidates X Y) (x y: X) :
f (inl x, inl y) = dist x y :=
fA.1.1.1.1.1 x y
private lemma candidates_dist_inr (fA : f ∈ candidates X Y) (x y : Y) :
f (inr x, inr y) = dist x y :=
fA.1.1.1.1.2 x y
private lemma candidates_le_max_var (fA : f ∈ candidates X Y) : f (x, y) ≤ max_var X Y :=
fA.2 x y
/-- candidates are bounded by `max_var X Y` -/
private lemma candidates_dist_bound (fA : f ∈ candidates X Y) :
∀ {x y : X ⊕ Y}, f (x, y) ≤ max_var X Y * dist x y
| (inl x) (inl y) := calc
f (inl x, inl y) = dist x y : candidates_dist_inl fA x y
... = dist (inl x) (inl y) : by { rw @sum.dist_eq X Y, refl }
... = 1 * dist (inl x) (inl y) : by simp
... ≤ max_var X Y * dist (inl x) (inl y) :
mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg
| (inl x) (inr y) := calc
f (inl x, inr y) ≤ max_var X Y : candidates_le_max_var fA
... = max_var X Y * 1 : by simp
... ≤ max_var X Y * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y))
| (inr x) (inl y) := calc
f (inr x, inl y) ≤ max_var X Y : candidates_le_max_var fA
... = max_var X Y * 1 : by simp
... ≤ max_var X Y * dist (inl x) (inr y) :
mul_le_mul_of_nonneg_left sum.one_dist_le (le_trans (zero_le_one) (one_le_max_var X Y))
| (inr x) (inr y) := calc
f (inr x, inr y) = dist x y : candidates_dist_inr fA x y
... = dist (inr x) (inr y) : by { rw @sum.dist_eq X Y, refl }
... = 1 * dist (inr x) (inr y) : by simp
... ≤ max_var X Y * dist (inr x) (inr y) :
mul_le_mul_of_nonneg_right (one_le_max_var X Y) dist_nonneg
/-- Technical lemma to prove that candidates are Lipschitz -/
private lemma candidates_lipschitz_aux (fA : f ∈ candidates X Y) :
f (x, y) - f (z, t) ≤ 2 * max_var X Y * dist (x, y) (z, t) :=
calc
f (x, y) - f(z, t) ≤ f (x, t) + f (t, y) - f (z, t) : sub_le_sub_right (candidates_triangle fA) _
... ≤ (f (x, z) + f (z, t) + f(t, y)) - f (z, t) :
sub_le_sub_right (add_le_add_right (candidates_triangle fA) _ ) _
... = f (x, z) + f (t, y) : by simp [sub_eq_add_neg, add_assoc]
... ≤ max_var X Y * dist x z + max_var X Y * dist t y :
add_le_add (candidates_dist_bound fA) (candidates_dist_bound fA)
... ≤ max_var X Y * max (dist x z) (dist t y) + max_var X Y * max (dist x z) (dist t y) :
begin
apply add_le_add,
apply mul_le_mul_of_nonneg_left (le_max_left (dist x z) (dist t y))
(zero_le_one.trans (one_le_max_var X Y)),
apply mul_le_mul_of_nonneg_left (le_max_right (dist x z) (dist t y))
(zero_le_one.trans (one_le_max_var X Y)),
end
... = 2 * max_var X Y * max (dist x z) (dist y t) :
by { simp [dist_comm], ring }
... = 2 * max_var X Y * dist (x, y) (z, t) : by refl
/-- Candidates are Lipschitz -/
private lemma candidates_lipschitz (fA : f ∈ candidates X Y) :
lipschitz_with (2 * max_var X Y) f :=
begin
apply lipschitz_with.of_dist_le_mul,
rintros ⟨x, y⟩ ⟨z, t⟩,
rw [real.dist_eq, abs_sub_le_iff],
use candidates_lipschitz_aux fA,
rw [dist_comm],
exact candidates_lipschitz_aux fA
end
/-- candidates give rise to elements of bounded_continuous_functions -/
def candidates_b_of_candidates (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) : Cb X Y :=
bounded_continuous_function.mk_of_compact ⟨f, (candidates_lipschitz fA).continuous⟩
lemma candidates_b_of_candidates_mem (f : prod_space_fun X Y) (fA : f ∈ candidates X Y) :
candidates_b_of_candidates f fA ∈ candidates_b X Y := fA
/-- The distance on `X ⊕ Y` is a candidate -/
private lemma dist_mem_candidates : (λp : (X ⊕ Y) × (X ⊕ Y), dist p.1 p.2) ∈ candidates X Y :=
begin
simp only [candidates, dist_comm, forall_const, and_true, add_comm, eq_self_iff_true,
and_self, sum.forall, set.mem_set_of_eq, dist_self],
repeat { split
<|> exact (λa y z, dist_triangle_left _ _ _)
<|> exact (λx y, by refl)
<|> exact (λx y, max_var_bound) }
end
/-- The distance on `X ⊕ Y` as a candidate -/
def candidates_b_dist (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [inhabited X]
[metric_space Y] [compact_space Y] [inhabited Y] : Cb X Y :=
candidates_b_of_candidates _ dist_mem_candidates
lemma candidates_b_dist_mem_candidates_b : candidates_b_dist X Y ∈ candidates_b X Y :=
candidates_b_of_candidates_mem _ _
private lemma candidates_b_nonempty : (candidates_b X Y).nonempty :=
⟨_, candidates_b_dist_mem_candidates_b⟩
/-- To apply Arzela-Ascoli, we need to check that the set of candidates is closed and
equicontinuous. Equicontinuity follows from the Lipschitz control, we check closedness. -/
private lemma closed_candidates_b : is_closed (candidates_b X Y) :=
begin
have I1 : ∀ x y, is_closed {f : Cb X Y | f (inl x, inl y) = dist x y} :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I2 : ∀ x y, is_closed {f : Cb X Y | f (inr x, inr y) = dist x y } :=
λx y, is_closed_eq continuous_evalx continuous_const,
have I3 : ∀ x y, is_closed {f : Cb X Y | f (x, y) = f (y, x)} :=
λx y, is_closed_eq continuous_evalx continuous_evalx,
have I4 : ∀ x y z, is_closed {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)} :=
λx y z, is_closed_le continuous_evalx (continuous_evalx.add continuous_evalx),
have I5 : ∀ x, is_closed {f : Cb X Y | f (x, x) = 0} :=
λx, is_closed_eq continuous_evalx continuous_const,
have I6 : ∀ x y, is_closed {f : Cb X Y | f (x, y) ≤ max_var X Y} :=
λx y, is_closed_le continuous_evalx continuous_const,
have : candidates_b X Y = (⋂x y, {f : Cb X Y | f ((@inl X Y x), (@inl X Y y)) = dist x y})
∩ (⋂x y, {f : Cb X Y | f ((@inr X Y x), (@inr X Y y)) = dist x y})
∩ (⋂x y, {f : Cb X Y | f (x, y) = f (y, x)})
∩ (⋂x y z, {f : Cb X Y | f (x, z) ≤ f (x, y) + f (y, z)})
∩ (⋂x, {f : Cb X Y | f (x, x) = 0})
∩ (⋂x y, {f : Cb X Y | f (x, y) ≤ max_var X Y}),
{ ext, simp only [candidates_b, candidates, mem_inter_eq, mem_Inter, mem_set_of_eq], refl },
rw this,
repeat { apply is_closed.inter _ _
<|> apply is_closed_Inter _
<|> apply I1 _ _
<|> apply I2 _ _
<|> apply I3 _ _
<|> apply I4 _ _ _
<|> apply I5 _
<|> apply I6 _ _
<|> assume x },
end
/-- Compactness of candidates (in bounded_continuous_functions) follows. -/
private lemma compact_candidates_b : is_compact (candidates_b X Y) :=
begin
refine arzela_ascoli₂ (Icc 0 (max_var X Y)) is_compact_Icc (candidates_b X Y)
closed_candidates_b _ _,
{ rintros f ⟨x1, x2⟩ hf,
simp only [set.mem_Icc],
exact ⟨candidates_nonneg hf, candidates_le_max_var hf⟩ },
{ refine equicontinuous_of_continuity_modulus (λt, 2 * max_var X Y * t) _ _ _,
{ have : tendsto (λ (t : ℝ), 2 * (max_var X Y : ℝ) * t) (𝓝 0) (𝓝 (2 * max_var X Y * 0)) :=
tendsto_const_nhds.mul tendsto_id,
simpa using this },
{ assume x y f hf,
exact (candidates_lipschitz hf).dist_le_mul _ _ } }
end
/-- We will then choose the candidate minimizing the Hausdorff distance. Except that we are not
in a metric space setting, so we need to define our custom version of Hausdorff distance,
called HD, and prove its basic properties. -/
def HD (f : Cb X Y) := max (⨆ x, ⨅ y, f (inl x, inr y)) (⨆ y, ⨅ x, f (inl x, inr y))
/- We will show that HD is continuous on bounded_continuous_functions, to deduce that its
minimum on the compact set candidates_b is attained. Since it is defined in terms of
infimum and supremum on `ℝ`, which is only conditionnally complete, we will need all the time
to check that the defining sets are bounded below or above. This is done in the next few
technical lemmas -/
lemma HD_below_aux1 {f : Cb X Y} (C : ℝ) {x : X} :
bdd_below (range (λ (y : Y), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩
private lemma HD_bound_aux1 (f : Cb X Y) (C : ℝ) :
bdd_above (range (λ (x : X), ⨅ y, f (inl x, inr y) + C)) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λx, _)⟩,
calc (⨅ y, f (inl x, inr y) + C) ≤ f (inl x, inr (default Y)) + C :
cinfi_le (HD_below_aux1 C) (default Y)
... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _)
end
lemma HD_below_aux2 {f : Cb X Y} (C : ℝ) {y : Y} :
bdd_below (range (λ (x : X), f (inl x, inr y) + C)) :=
let ⟨cf, hcf⟩ := (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 in
⟨cf + C, forall_range_iff.2 (λi, add_le_add_right ((λx, hcf (mem_range_self x)) _) _)⟩
private lemma HD_bound_aux2 (f : Cb X Y) (C : ℝ) :
bdd_above (range (λ (y : Y), ⨅ x, f (inl x, inr y) + C)) :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).2 with ⟨Cf, hCf⟩,
refine ⟨Cf + C, forall_range_iff.2 (λy, _)⟩,
calc (⨅ x, f (inl x, inr y) + C) ≤ f (inl (default X), inr y) + C :
cinfi_le (HD_below_aux2 C) (default X)
... ≤ Cf + C : add_le_add ((λx, hCf (mem_range_self x)) _) (le_refl _)
end
/-- Explicit bound on `HD (dist)`. This means that when looking for minimizers it will
be sufficient to look for functions with `HD(f)` bounded by this bound. -/
lemma HD_candidates_b_dist_le :
HD (candidates_b_dist X Y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) :=
begin
refine max_le (csupr_le (λx, _)) (csupr_le (λy, _)),
{ have A : (⨅ y, candidates_b_dist X Y (inl x, inr y)) ≤
candidates_b_dist X Y (inl x, inr (default Y)) :=
cinfi_le (by simpa using HD_below_aux1 0) (default Y),
have B : dist (inl x) (inr (default Y)) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc
dist (inl x) (inr (default Y)) = dist x (default X) + 1 + dist (default Y) (default Y) : rfl
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ },
any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ },
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
end,
exact le_trans A B },
{ have A : (⨅ x, candidates_b_dist X Y (inl x, inr y)) ≤
candidates_b_dist X Y (inl (default X), inr y) :=
cinfi_le (by simpa using HD_below_aux2 0) (default X),
have B : dist (inl (default X)) (inr y) ≤ diam (univ : set X) + 1 + diam (univ : set Y) := calc
dist (inl (default X)) (inr y) = dist (default X) (default X) + 1 + dist (default Y) y : rfl
... ≤ diam (univ : set X) + 1 + diam (univ : set Y) :
begin
apply add_le_add (add_le_add _ (le_refl _)),
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _),
any_goals { exact ordered_add_comm_monoid.to_covariant_class_left ℝ },
any_goals { exact ordered_add_comm_monoid.to_covariant_class_right ℝ },
exact dist_le_diam_of_mem bounded_of_compact_space (mem_univ _) (mem_univ _)
end,
exact le_trans A B },
end
/- To check that HD is continuous, we check that it is Lipschitz. As HD is a max, we
prove separately inequalities controlling the two terms (relying too heavily on copy-paste...) -/
private lemma HD_lipschitz_aux1 (f g : Cb X Y) :
(⨆ x, ⨅ y, f (inl x, inr y)) ≤ (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : (⨆ x, ⨅ y, f (inl x, inr y)) ≤ ⨆ x, ⨅ y, g (inl x, inr y) + dist f g :=
csupr_le_csupr (HD_bound_aux1 _ (dist f g))
(λx, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀ x, (⨅ y, g (inl x, inr y)) + dist f g = ⨅ y, g (inl x, inr y) + dist f g,
{ assume x,
refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ show bdd_below (range (λ (y : Y), g (inl x, inr y))),
from ⟨cg, forall_range_iff.2(λi, Hcg _)⟩ } },
have E2 : (⨆ x, ⨅ y, g (inl x, inr y)) + dist f g = ⨆ x, (⨅ y, g (inl x, inr y)) + dist f g,
{ refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux1 _ 0 } },
-- deduce the result from the above two steps
simpa [E2, E1, function.comp]
end
private lemma HD_lipschitz_aux2 (f g : Cb X Y) :
(⨆ y, ⨅ x, f (inl x, inr y)) ≤ (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g :=
begin
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cg, hcg⟩,
have Hcg : ∀ x, cg ≤ g x := λx, hcg (mem_range_self x),
rcases (real.bounded_iff_bdd_below_bdd_above.1 bounded_range).1 with ⟨cf, hcf⟩,
have Hcf : ∀ x, cf ≤ f x := λx, hcf (mem_range_self x),
-- prove the inequality but with `dist f g` inside, by using inequalities comparing
-- supr to supr and infi to infi
have Z : (⨆ y, ⨅ x, f (inl x, inr y)) ≤ ⨆ y, ⨅ x, g (inl x, inr y) + dist f g :=
csupr_le_csupr (HD_bound_aux2 _ (dist f g))
(λy, cinfi_le_cinfi ⟨cf, forall_range_iff.2(λi, Hcf _)⟩ (λy, coe_le_coe_add_dist)),
-- move the `dist f g` out of the infimum and the supremum, arguing that continuous monotone maps
-- (here the addition of `dist f g`) preserve infimum and supremum
have E1 : ∀ y, (⨅ x, g (inl x, inr y)) + dist f g = ⨅ x, g (inl x, inr y) + dist f g,
{ assume y,
refine map_cinfi_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ show bdd_below (range (λx:X, g (inl x, inr y))),
from ⟨cg, forall_range_iff.2 (λi, Hcg _)⟩ } },
have E2 : (⨆ y, ⨅ x, g (inl x, inr y)) + dist f g = ⨆ y, (⨅ x, g (inl x, inr y)) + dist f g,
{ refine map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) _ _,
{ assume x y hx, simpa },
{ by simpa using HD_bound_aux2 _ 0 } },
-- deduce the result from the above two steps
simpa [E2, E1]
end
private lemma HD_lipschitz_aux3 (f g : Cb X Y) : HD f ≤ HD g + dist f g :=
max_le (le_trans (HD_lipschitz_aux1 f g) (add_le_add_right (le_max_left _ _) _))
(le_trans (HD_lipschitz_aux2 f g) (add_le_add_right (le_max_right _ _) _))
/-- Conclude that HD, being Lipschitz, is continuous -/
private lemma HD_continuous : continuous (HD : Cb X Y → ℝ) :=
lipschitz_with.continuous (lipschitz_with.of_le_add HD_lipschitz_aux3)
end constructions --section
section consequences
variables (X : Type u) (Y : Type v) [metric_space X] [compact_space X] [nonempty X] [metric_space Y]
[compact_space Y] [nonempty Y]
/- Now that we have proved that the set of candidates is compact, and that HD is continuous,
we can finally select a candidate minimizing HD. This will be the candidate realizing the
optimal coupling. -/
private lemma exists_minimizer : ∃ f ∈ candidates_b X Y, ∀ g ∈ candidates_b X Y, HD f ≤ HD g :=
compact_candidates_b.exists_forall_le candidates_b_nonempty HD_continuous.continuous_on
private definition optimal_GH_dist : Cb X Y := classical.some (exists_minimizer X Y)
private lemma optimal_GH_dist_mem_candidates_b : optimal_GH_dist X Y ∈ candidates_b X Y :=
by cases (classical.some_spec (exists_minimizer X Y)); assumption
private lemma HD_optimal_GH_dist_le (g : Cb X Y) (hg : g ∈ candidates_b X Y) :
HD (optimal_GH_dist X Y) ≤ HD g :=
let ⟨Z1, Z2⟩ := classical.some_spec (exists_minimizer X Y) in Z2 g hg
/-- With the optimal candidate, construct a premetric space structure on `X ⊕ Y`, on which the
predistance is given by the candidate. Then, we will identify points at `0` predistance
to obtain a genuine metric space -/
def premetric_optimal_GH_dist : pseudo_metric_space (X ⊕ Y) :=
{ dist := λp q, optimal_GH_dist X Y (p, q),
dist_self := λx, candidates_refl (optimal_GH_dist_mem_candidates_b X Y),
dist_comm := λx y, candidates_symm (optimal_GH_dist_mem_candidates_b X Y),
dist_triangle := λx y z, candidates_triangle (optimal_GH_dist_mem_candidates_b X Y) }
local attribute [instance] premetric_optimal_GH_dist pseudo_metric.dist_setoid
/-- A metric space which realizes the optimal coupling between `X` and `Y` -/
@[derive metric_space, nolint has_inhabited_instance]
definition optimal_GH_coupling : Type* :=
pseudo_metric_quot (X ⊕ Y)
/-- Injection of `X` in the optimal coupling between `X` and `Y` -/
def optimal_GH_injl (x : X) : optimal_GH_coupling X Y := ⟦inl x⟧
/-- The injection of `X` in the optimal coupling between `X` and `Y` is an isometry. -/
lemma isometry_optimal_GH_injl : isometry (optimal_GH_injl X Y) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inl x⟧ ⟦inl y⟧ = dist x y,
exact candidates_dist_inl (optimal_GH_dist_mem_candidates_b X Y) _ _,
end
/-- Injection of `Y` in the optimal coupling between `X` and `Y` -/
def optimal_GH_injr (y : Y) : optimal_GH_coupling X Y := ⟦inr y⟧
/-- The injection of `Y` in the optimal coupling between `X` and `Y` is an isometry. -/
lemma isometry_optimal_GH_injr : isometry (optimal_GH_injr X Y) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
change dist ⟦inr x⟧ ⟦inr y⟧ = dist x y,
exact candidates_dist_inr (optimal_GH_dist_mem_candidates_b X Y) _ _,
end
/-- The optimal coupling between two compact spaces `X` and `Y` is still a compact space -/
instance compact_space_optimal_GH_coupling : compact_space (optimal_GH_coupling X Y) :=
⟨begin
have : (univ : set (optimal_GH_coupling X Y)) =
(optimal_GH_injl X Y '' univ) ∪ (optimal_GH_injr X Y '' univ),
{ refine subset.antisymm (λxc hxc, _) (subset_univ _),
rcases quotient.exists_rep xc with ⟨x, hx⟩,
cases x; rw ← hx,
{ have : ⟦inl x⟧ = optimal_GH_injl X Y x := rfl,
rw this,
exact mem_union_left _ (mem_image_of_mem _ (mem_univ _)) },
{ have : ⟦inr x⟧ = optimal_GH_injr X Y x := rfl,
rw this,
exact mem_union_right _ (mem_image_of_mem _ (mem_univ _)) } },
rw this,
exact (compact_univ.image (isometry_optimal_GH_injl X Y).continuous).union
(compact_univ.image (isometry_optimal_GH_injr X Y).continuous)
end⟩
/-- For any candidate `f`, `HD(f)` is larger than or equal to the Hausdorff distance in the
optimal coupling. This follows from the fact that HD of the optimal candidate is exactly
the Hausdorff distance in the optimal coupling, although we only prove here the inequality
we need. -/
lemma Hausdorff_dist_optimal_le_HD {f} (h : f ∈ candidates_b X Y) :
Hausdorff_dist (range (optimal_GH_injl X Y)) (range (optimal_GH_injr X Y)) ≤ HD f :=
begin
refine le_trans (le_of_forall_le_of_dense (λr hr, _)) (HD_optimal_GH_dist_le X Y f h),
have A : ∀ x ∈ range (optimal_GH_injl X Y), ∃ y ∈ range (optimal_GH_injr X Y), dist x y ≤ r,
{ assume x hx,
rcases mem_range.1 hx with ⟨z, hz⟩,
rw ← hz,
have I1 : (⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y)) < r :=
lt_of_le_of_lt (le_max_left _ _) hr,
have I2 : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) ≤
⨆ x, ⨅ y, optimal_GH_dist X Y (inl x, inr y) :=
le_cSup (by simpa using HD_bound_aux1 _ 0) (mem_range_self _),
have I : (⨅ y, optimal_GH_dist X Y (inl z, inr y)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injr X Y z', mem_range_self _],
have : (optimal_GH_dist X Y) (inl z, inr z') ≤ r, by { rw hz', exact le_of_lt hr' },
exact this },
refine Hausdorff_dist_le_of_mem_dist _ A _,
{ rcases exists_mem_of_nonempty X with ⟨xX, _⟩,
have : optimal_GH_injl X Y xX ∈ range (optimal_GH_injl X Y) := mem_range_self _,
rcases A _ this with ⟨y, yrange, hy⟩,
exact le_trans dist_nonneg hy },
{ assume y hy,
rcases mem_range.1 hy with ⟨z, hz⟩,
rw ← hz,
have I1 : (⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y)) < r :=
lt_of_le_of_lt (le_max_right _ _) hr,
have I2 : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) ≤
⨆ y, ⨅ x, optimal_GH_dist X Y (inl x, inr y) :=
le_cSup (by simpa using HD_bound_aux2 _ 0) (mem_range_self _),
have I : (⨅ x, optimal_GH_dist X Y (inl x, inr z)) < r := lt_of_le_of_lt I2 I1,
rcases exists_lt_of_cInf_lt (range_nonempty _) I with ⟨r', r'range, hr'⟩,
rcases mem_range.1 r'range with ⟨z', hz'⟩,
existsi [optimal_GH_injl X Y z', mem_range_self _],
have : (optimal_GH_dist X Y) (inl z', inr z) ≤ r, by { rw hz', exact le_of_lt hr' },
rw dist_comm,
exact this }
end
end consequences
/- We are done with the construction of the optimal coupling -/
end Gromov_Hausdorff_realized
end Gromov_Hausdorff
|
f81e0c4e13f11aa88e0168d3bf9c034172f78d2a | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/number_theory/pythagorean_triples.lean | 125ef8ae9b4d667946e661d54950e2fdab06c863 | [
"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 | 25,921 | lean | /-
Copyright (c) 2020 Paul van Wamelen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Paul van Wamelen
-/
import algebra.field
import ring_theory.int.basic
import algebra.group_with_zero.power
import tactic.ring
import tactic.ring_exp
import tactic.field_simp
import data.zmod.basic
/-!
# Pythagorean Triples
The main result is the classification of Pythagorean triples. The final result is for general
Pythagorean triples. It follows from the more interesting relatively prime case. We use the
"rational parametrization of the circle" method for the proof. The parametrization maps the point
`(x / z, y / z)` to the slope of the line through `(-1 , 0)` and `(x / z, y / z)`. This quickly
shows that `(x / z, y / z) = (2 * m * n / (m ^ 2 + n ^ 2), (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))` where
`m / n` is the slope. In order to identify numerators and denominators we now need results showing
that these are coprime. This is easy except for the prime 2. In order to deal with that we have to
analyze the parity of `x`, `y`, `m` and `n` and eliminate all the impossible cases. This takes up
the bulk of the proof below.
-/
lemma sq_ne_two_fin_zmod_four (z : zmod 4) : z * z ≠ 2 :=
begin
change fin 4 at z,
fin_cases z; norm_num [fin.ext_iff, fin.coe_bit0, fin.coe_bit1]
end
lemma int.sq_ne_two_mod_four (z : ℤ) : (z * z) % 4 ≠ 2 :=
suffices ¬ (z * z) % (4 : ℕ) = 2 % (4 : ℕ), by norm_num at this,
begin
rw ← zmod.int_coe_eq_int_coe_iff',
simpa using sq_ne_two_fin_zmod_four _
end
noncomputable theory
open_locale classical
/-- Three integers `x`, `y`, and `z` form a Pythagorean triple if `x * x + y * y = z * z`. -/
def pythagorean_triple (x y z : ℤ) : Prop := x * x + y * y = z * z
/-- Pythagorean triples are interchangable, i.e `x * x + y * y = y * y + x * x = z * z`.
This comes from additive commutativity. -/
lemma pythagorean_triple_comm {x y z : ℤ} :
(pythagorean_triple x y z) ↔ (pythagorean_triple y x z) :=
by { delta pythagorean_triple, rw add_comm }
/-- The zeroth Pythagorean triple is all zeros. -/
lemma pythagorean_triple.zero : pythagorean_triple 0 0 0 :=
by simp only [pythagorean_triple, zero_mul, zero_add]
namespace pythagorean_triple
variables {x y z : ℤ} (h : pythagorean_triple x y z)
include h
lemma eq : x * x + y * y = z * z := h
@[symm]
lemma symm :
pythagorean_triple y x z :=
by rwa [pythagorean_triple_comm]
/-- A triple is still a triple if you multiply `x`, `y` and `z`
by a constant `k`. -/
lemma mul (k : ℤ) : pythagorean_triple (k * x) (k * y) (k * z) :=
begin
by_cases hk : k = 0,
{ simp only [pythagorean_triple, hk, zero_mul, zero_add], },
{ calc (k * x) * (k * x) + (k * y) * (k * y)
= k ^ 2 * (x * x + y * y) : by ring
... = k ^ 2 * (z * z) : by rw h.eq
... = (k * z) * (k * z) : by ring }
end
omit h
/-- `(k*x, k*y, k*z)` is a Pythagorean triple if and only if
`(x, y, z)` is also a triple. -/
lemma mul_iff (k : ℤ) (hk : k ≠ 0) :
pythagorean_triple (k * x) (k * y) (k * z) ↔ pythagorean_triple x y z :=
begin
refine ⟨_, λ h, h.mul k⟩,
simp only [pythagorean_triple],
intro h,
rw ← mul_left_inj' (mul_ne_zero hk hk),
convert h using 1; ring,
end
include h
/-- A Pythagorean triple `x, y, z` is “classified” if there exist integers `k, m, n` such that
either
* `x = k * (m ^ 2 - n ^ 2)` and `y = k * (2 * m * n)`, or
* `x = k * (2 * m * n)` and `y = k * (m ^ 2 - n ^ 2)`. -/
@[nolint unused_arguments] def is_classified := ∃ (k m n : ℤ),
((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n))
∨ (x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)))
∧ int.gcd m n = 1
/-- A primitive pythogorean triple `x, y, z` is a pythagorean triple with `x` and `y` coprime.
Such a triple is “primitively classified” if there exist coprime integers `m, n` such that either
* `x = m ^ 2 - n ^ 2` and `y = 2 * m * n`, or
* `x = 2 * m * n` and `y = m ^ 2 - n ^ 2`.
-/
@[nolint unused_arguments] def is_primitive_classified := ∃ (m n : ℤ),
((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n)
∨ (x = 2 * m * n ∧ y = m ^ 2 - n ^ 2))
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0))
lemma mul_is_classified (k : ℤ) (hc : h.is_classified) : (h.mul k).is_classified :=
begin
obtain ⟨l, m, n, ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co⟩⟩ := hc,
{ use [k * l, m, n], apply and.intro _ co, left, split; ring },
{ use [k * l, m, n], apply and.intro _ co, right, split; ring },
end
lemma even_odd_of_coprime (hc : int.gcd x y = 1) :
(x % 2 = 0 ∧ y % 2 = 1) ∨ (x % 2 = 1 ∧ y % 2 = 0) :=
begin
cases int.mod_two_eq_zero_or_one x with hx hx;
cases int.mod_two_eq_zero_or_one y with hy hy,
{ -- x even, y even
exfalso,
apply nat.not_coprime_of_dvd_of_dvd (dec_trivial : 1 < 2) _ _ hc,
{ apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hx },
{ apply int.dvd_nat_abs_of_of_nat_dvd, apply int.dvd_of_mod_eq_zero hy } },
{ left, exact ⟨hx, hy⟩ }, -- x even, y odd
{ right, exact ⟨hx, hy⟩ }, -- x odd, y even
{ -- x odd, y odd
exfalso,
obtain ⟨x0, y0, rfl, rfl⟩ : ∃ x0 y0, x = x0* 2 + 1 ∧ y = y0 * 2 + 1,
{ cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hx) with x0 hx2,
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hy) with y0 hy2,
rw sub_eq_iff_eq_add at hx2 hy2, exact ⟨x0, y0, hx2, hy2⟩ },
apply int.sq_ne_two_mod_four z,
rw show z * z = 4 * (x0 * x0 + x0 + y0 * y0 + y0) + 2, by { rw ← h.eq, ring },
norm_num [int.add_mod] }
end
lemma gcd_dvd : (int.gcd x y : ℤ) ∣ z :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
have hz : z = 0,
{ simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h },
simp only [hz, dvd_zero], },
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
int.exists_gcd_one' (nat.pos_of_ne_zero h0),
rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul],
rw [← int.pow_dvd_pow_iff (dec_trivial : 0 < 2), sq z, ← h.eq],
rw (by ring : x0 * k * (x0 * k) + y0 * k * (y0 * k) = k ^ 2 * (x0 * x0 + y0 * y0)),
exact dvd_mul_right _ _
end
lemma normalize : pythagorean_triple (x / int.gcd x y) (y / int.gcd x y) (z / int.gcd x y) :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
have hz : z = 0,
{ simpa only [pythagorean_triple, hx, hy, add_zero, zero_eq_mul, mul_zero, or_self] using h },
simp only [hx, hy, hz, int.zero_div], exact zero },
rcases h.gcd_dvd with ⟨z0, rfl⟩,
obtain ⟨k, x0, y0, k0, h2, rfl, rfl⟩ :
∃ (k : ℕ) x0 y0, 0 < k ∧ int.gcd x0 y0 = 1 ∧ x = x0 * k ∧ y = y0 * k :=
int.exists_gcd_one' (nat.pos_of_ne_zero h0),
have hk : (k : ℤ) ≠ 0, { norm_cast, rwa pos_iff_ne_zero at k0 },
rw [int.gcd_mul_right, h2, int.nat_abs_of_nat, one_mul] at h ⊢,
rw [mul_comm x0, mul_comm y0, mul_iff k hk] at h,
rwa [int.mul_div_cancel _ hk, int.mul_div_cancel _ hk, int.mul_div_cancel_left _ hk],
end
lemma is_classified_of_is_primitive_classified (hp : h.is_primitive_classified) :
h.is_classified :=
begin
obtain ⟨m, n, H⟩ := hp,
use [1, m, n],
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩;
{ apply and.intro _ co, rw one_mul, rw one_mul, tauto }
end
lemma is_classified_of_normalize_is_primitive_classified
(hc : h.normalize.is_primitive_classified) : h.is_classified :=
begin
convert h.normalize.mul_is_classified (int.gcd x y)
(is_classified_of_is_primitive_classified h.normalize hc);
rw int.mul_div_cancel',
{ exact int.gcd_dvd_left x y },
{ exact int.gcd_dvd_right x y },
{ exact h.gcd_dvd }
end
lemma ne_zero_of_coprime (hc : int.gcd x y = 1) : z ≠ 0 :=
begin
suffices : 0 < z * z, { rintro rfl, norm_num at this },
rw [← h.eq, ← sq, ← sq],
have hc' : int.gcd x y ≠ 0, { rw hc, exact one_ne_zero },
cases int.ne_zero_of_gcd hc' with hxz hyz,
{ apply lt_add_of_pos_of_le (sq_pos_of_ne_zero x hxz) (sq_nonneg y) },
{ apply lt_add_of_le_of_pos (sq_nonneg x) (sq_pos_of_ne_zero y hyz) }
end
lemma is_primitive_classified_of_coprime_of_zero_left (hc : int.gcd x y = 1) (hx : x = 0) :
h.is_primitive_classified :=
begin
subst x,
change nat.gcd 0 (int.nat_abs y) = 1 at hc,
rw [nat.gcd_zero_left (int.nat_abs y)] at hc,
cases int.nat_abs_eq y with hy hy,
{ use [1, 0], rw [hy, hc, int.gcd_zero_right], norm_num },
{ use [0, 1], rw [hy, hc, int.gcd_zero_left], norm_num }
end
lemma coprime_of_coprime (hc : int.gcd x y = 1) : int.gcd y z = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hpy, hpz⟩ := nat.prime.not_coprime_iff_dvd.mp H,
apply hp.not_dvd_one,
rw [← hc],
apply nat.dvd_gcd (int.prime.dvd_nat_abs_of_coe_dvd_sq hp _ _) hpy,
rw [sq, eq_sub_of_add_eq h],
rw [← int.coe_nat_dvd_left] at hpy hpz,
exact dvd_sub ((hpz).mul_right _) ((hpy).mul_right _),
end
end pythagorean_triple
section circle_equiv_gen
/-!
### A parametrization of the unit circle
For the classification of pythogorean triples, we will use a parametrization of the unit circle.
-/
variables {K : Type*} [field K]
/-- A parameterization of the unit circle that is useful for classifying Pythagorean triples.
(To be applied in the case where `K = ℚ`.) -/
def circle_equiv_gen (hk : ∀ x : K, 1 + x^2 ≠ 0) :
K ≃ {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} :=
{ to_fun := λ x, ⟨⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩,
by { field_simp [hk x, div_pow], ring },
begin
simp only [ne.def, div_eq_iff (hk x), ←neg_mul_eq_neg_mul, one_mul, neg_add,
sub_eq_add_neg, add_left_inj],
simpa only [eq_neg_iff_add_eq_zero, one_pow] using hk 1,
end⟩,
inv_fun := λ p, (p : K × K).1 / ((p : K × K).2 + 1),
left_inv := λ x,
begin
have h2 : (1 + 1 : K) = 2 := rfl,
have h3 : (2 : K) ≠ 0, { convert hk 1, rw [one_pow 2, h2] },
field_simp [hk x, h2, add_assoc, add_comm, add_sub_cancel'_right, mul_comm],
end,
right_inv := λ ⟨⟨x, y⟩, hxy, hy⟩,
begin
change x ^ 2 + y ^ 2 = 1 at hxy,
have h2 : y + 1 ≠ 0, { apply mt eq_neg_of_add_eq_zero, exact hy },
have h3 : (y + 1) ^ 2 + x ^ 2 = 2 * (y + 1),
{ rw [(add_neg_eq_iff_eq_add.mpr hxy.symm).symm], ring },
have h4 : (2 : K) ≠ 0, { convert hk 1, rw one_pow 2, refl },
simp only [prod.mk.inj_iff, subtype.mk_eq_mk],
split,
{ field_simp [h3], ring },
{ field_simp [h3], rw [← add_neg_eq_iff_eq_add.mpr hxy.symm], ring }
end }
@[simp] lemma circle_equiv_apply (hk : ∀ x : K, 1 + x^2 ≠ 0) (x : K) :
(circle_equiv_gen hk x : K × K) = ⟨2 * x / (1 + x^2), (1 - x^2) / (1 + x^2)⟩ := rfl
@[simp] lemma circle_equiv_symm_apply (hk : ∀ x : K, 1 + x^2 ≠ 0)
(v : {p : K × K // p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1}) :
(circle_equiv_gen hk).symm v = (v : K × K).1 / ((v : K × K).2 + 1) := rfl
end circle_equiv_gen
private lemma coprime_sq_sub_sq_add_of_even_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 0) (hn : n % 2 = 1) :
int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H,
rw ← int.coe_nat_dvd_left at hp1 hp2,
have h2m : (p : ℤ) ∣ 2 * m ^ 2, { convert dvd_add hp2 hp1, ring },
have h2n : (p : ℤ) ∣ 2 * n ^ 2, { convert dvd_sub hp2 hp1, ring },
have hmc : p = 2 ∨ p ∣ int.nat_abs m :=
prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2m,
have hnc : p = 2 ∨ p ∣ int.nat_abs n :=
prime_two_or_dvd_of_dvd_two_mul_pow_self_two hp h2n,
by_cases h2 : p = 2,
{ have h3 : (m ^ 2 + n ^ 2) % 2 = 1, { norm_num [sq, int.add_mod, int.mul_mod, hm, hn] },
have h4 : (m ^ 2 + n ^ 2) % 2 = 0, { apply int.mod_eq_zero_of_dvd, rwa h2 at hp2 },
rw h4 at h3, exact zero_ne_one h3 },
{ apply hp.not_dvd_one,
rw ← h,
exact nat.dvd_gcd (or.resolve_left hmc h2) (or.resolve_left hnc h2), }
end
private lemma coprime_sq_sub_sq_add_of_odd_even {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 0):
int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1 :=
begin
rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)],
rw [(by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2), add_comm],
apply coprime_sq_sub_sq_add_of_even_odd _ hn hm, rwa [int.gcd_comm],
end
private lemma coprime_sq_sub_mul_of_even_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 0) (hn : n % 2 = 1) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
by_contradiction H,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp H,
rw ← int.coe_nat_dvd_left at hp1 hp2,
have hnp : ¬ (p : ℤ) ∣ int.gcd m n,
{ rw h, norm_cast, exact mt nat.dvd_one.mp (nat.prime.ne_one hp) },
cases int.prime.dvd_mul hp hp2 with hp2m hpn,
{ rw int.nat_abs_mul at hp2m,
cases (nat.prime.dvd_mul hp).mp hp2m with hp2 hpm,
{ have hp2' : p = 2 := (nat.le_of_dvd zero_lt_two hp2).antisymm hp.two_le,
revert hp1, rw hp2',
apply mt int.mod_eq_zero_of_dvd,
norm_num [sq, int.sub_mod, int.mul_mod, hm, hn] },
apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpm)) hnp,
apply (or_self _).mp, apply int.prime.dvd_mul' hp,
rw (by ring : n * n = - (m ^ 2 - n ^ 2) + m * m),
apply dvd_add (dvd_neg_of_dvd hp1),
exact dvd_mul_of_dvd_left (int.coe_nat_dvd_left.mpr hpm) m },
rw int.gcd_comm at hnp,
apply mt (int.dvd_gcd (int.coe_nat_dvd_left.mpr hpn)) hnp,
apply (or_self _).mp, apply int.prime.dvd_mul' hp,
rw (by ring : m * m = (m ^ 2 - n ^ 2) + n * n),
apply dvd_add hp1,
exact (int.coe_nat_dvd_left.mpr hpn).mul_right n
end
private lemma coprime_sq_sub_mul_of_odd_even {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 0) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
rw [int.gcd, ← int.nat_abs_neg (m ^ 2 - n ^ 2)],
rw [(by ring : 2 * m * n = 2 * n * m), (by ring : -(m ^ 2 - n ^ 2) = n ^ 2 - m ^ 2)],
apply coprime_sq_sub_mul_of_even_odd _ hn hm, rwa [int.gcd_comm]
end
private lemma coprime_sq_sub_mul {m n : ℤ} (h : int.gcd m n = 1)
(hmn : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) :
int.gcd (m ^ 2 - n ^ 2) (2 * m * n) = 1 :=
begin
cases hmn with h1 h2,
{ exact coprime_sq_sub_mul_of_even_odd h h1.left h1.right },
{ exact coprime_sq_sub_mul_of_odd_even h h2.left h2.right }
end
private lemma coprime_sq_sub_sq_sum_of_odd_odd {m n : ℤ} (h : int.gcd m n = 1)
(hm : m % 2 = 1) (hn : n % 2 = 1) :
2 ∣ m ^ 2 + n ^ 2
∧ 2 ∣ m ^ 2 - n ^ 2
∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0
∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1 :=
begin
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hm) with m0 hm2,
cases exists_eq_mul_left_of_dvd (int.dvd_sub_of_mod_eq hn) with n0 hn2,
rw sub_eq_iff_eq_add at hm2 hn2, subst m, subst n,
have h1 : (m0 * 2 + 1) ^ 2 + (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 + n0 ^ 2 + m0 + n0) + 1),
by ring_exp,
have h2 : (m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2 = 2 * (2 * (m0 ^ 2 - n0 ^ 2 + m0 - n0)),
by ring_exp,
have h3 : ((m0 * 2 + 1) ^ 2 - (n0 * 2 + 1) ^ 2) / 2 % 2 = 0,
{ rw [h2, int.mul_div_cancel_left, int.mul_mod_right], exact dec_trivial },
refine ⟨⟨_, h1⟩, ⟨_, h2⟩, h3, _⟩,
have h20 : (2:ℤ) ≠ 0 := dec_trivial,
rw [h1, h2, int.mul_div_cancel_left _ h20, int.mul_div_cancel_left _ h20],
by_contra h4,
obtain ⟨p, hp, hp1, hp2⟩ := nat.prime.not_coprime_iff_dvd.mp h4,
apply hp.not_dvd_one,
rw ← h,
rw ← int.coe_nat_dvd_left at hp1 hp2,
apply nat.dvd_gcd,
{ apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp,
convert dvd_add hp1 hp2, ring_exp },
{ apply int.prime.dvd_nat_abs_of_coe_dvd_sq hp,
convert dvd_sub hp2 hp1, ring_exp },
end
namespace pythagorean_triple
variables {x y z : ℤ} (h : pythagorean_triple x y z)
include h
lemma is_primitive_classified_aux (hc : x.gcd y = 1) (hzpos : 0 < z)
{m n : ℤ} (hm2n2 : 0 < m ^ 2 + n ^ 2)
(hv2 : (x : ℚ) / z = 2 * m * n / (m ^ 2 + n ^ 2))
(hw2 : (y : ℚ) / z = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2))
(H : int.gcd (m ^ 2 - n ^ 2) (m ^ 2 + n ^ 2) = 1)
(co : int.gcd m n = 1)
(pp : (m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)):
h.is_primitive_classified :=
begin
have hz : z ≠ 0, apply ne_of_gt hzpos,
have h2 : y = m ^ 2 - n ^ 2 ∧ z = m ^ 2 + n ^ 2,
{ apply rat.div_int_inj hzpos hm2n2 (h.coprime_of_coprime hc) H, rw [hw2], norm_cast },
use [m, n], apply and.intro _ (and.intro co pp), right,
refine ⟨_, h2.left⟩,
rw [← rat.coe_int_inj _ _, ← div_left_inj' ((mt (rat.coe_int_inj z 0).mp) hz), hv2, h2.right],
norm_cast
end
theorem is_primitive_classified_of_coprime_of_odd_of_pos
(hc : int.gcd x y = 1) (hyo : y % 2 = 1) (hzpos : 0 < z) :
h.is_primitive_classified :=
begin
by_cases h0 : x = 0, { exact h.is_primitive_classified_of_coprime_of_zero_left hc h0 },
let v := (x : ℚ) / z,
let w := (y : ℚ) / z,
have hz : z ≠ 0, apply ne_of_gt hzpos,
have hq : v ^ 2 + w ^ 2 = 1,
{ field_simp [hz, sq], norm_cast, exact h },
have hvz : v ≠ 0, { field_simp [hz], exact h0 },
have hw1 : w ≠ -1,
{ contrapose! hvz with hw1,
rw [hw1, neg_sq, one_pow, add_left_eq_self] at hq,
exact pow_eq_zero hq, },
have hQ : ∀ x : ℚ, 1 + x^2 ≠ 0,
{ intro q, apply ne_of_gt, exact lt_add_of_pos_of_le zero_lt_one (sq_nonneg q) },
have hp : (⟨v, w⟩ : ℚ × ℚ) ∈ {p : ℚ × ℚ | p.1^2 + p.2^2 = 1 ∧ p.2 ≠ -1} := ⟨hq, hw1⟩,
let q := (circle_equiv_gen hQ).symm ⟨⟨v, w⟩, hp⟩,
have ht4 : v = 2 * q / (1 + q ^ 2) ∧ w = (1 - q ^ 2) / (1 + q ^ 2),
{ apply prod.mk.inj,
have := ((circle_equiv_gen hQ).apply_symm_apply ⟨⟨v, w⟩, hp⟩).symm,
exact congr_arg subtype.val this, },
let m := (q.denom : ℤ),
let n := q.num,
have hm0 : m ≠ 0, { norm_cast, apply rat.denom_ne_zero q },
have hq2 : q = n / m := (rat.num_div_denom q).symm,
have hm2n2 : 0 < m ^ 2 + n ^ 2,
{ apply lt_add_of_pos_of_le _ (sq_nonneg n),
exact lt_of_le_of_ne (sq_nonneg m) (ne.symm (pow_ne_zero 2 hm0)) },
have hw2 : w = (m ^ 2 - n ^ 2) / (m ^ 2 + n ^ 2),
{ rw [ht4.2, hq2], field_simp [hm2n2, rat.denom_ne_zero q, -rat.num_div_denom] },
have hm2n20 : (m : ℚ) ^ 2 + (n : ℚ) ^ 2 ≠ 0,
{ norm_cast, simpa only [int.coe_nat_pow] using ne_of_gt hm2n2 },
have hv2 : v = 2 * m * n / (m ^ 2 + n ^ 2),
{ apply eq.symm, apply (div_eq_iff hm2n20).mpr, rw [ht4.1], field_simp [hQ q],
rw [hq2] {occs := occurrences.pos [2, 3]},
field_simp [rat.denom_ne_zero q, -rat.num_div_denom],
ring },
have hnmcp : int.gcd n m = 1 := q.cop,
have hmncp : int.gcd m n = 1, { rw int.gcd_comm, exact hnmcp },
cases int.mod_two_eq_zero_or_one m with hm2 hm2;
cases int.mod_two_eq_zero_or_one n with hn2 hn2,
{ -- m even, n even
exfalso,
have h1 : 2 ∣ (int.gcd n m : ℤ),
{ exact int.dvd_gcd (int.dvd_of_mod_eq_zero hn2) (int.dvd_of_mod_eq_zero hm2) },
rw hnmcp at h1, revert h1, norm_num },
{ -- m even, n odd
apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp,
{ apply or.intro_left, exact and.intro hm2 hn2 },
{ apply coprime_sq_sub_sq_add_of_even_odd hmncp hm2 hn2 } },
{ -- m odd, n even
apply h.is_primitive_classified_aux hc hzpos hm2n2 hv2 hw2 _ hmncp,
{ apply or.intro_right, exact and.intro hm2 hn2 },
apply coprime_sq_sub_sq_add_of_odd_even hmncp hm2 hn2 },
{ -- m odd, n odd
exfalso,
have h1 : 2 ∣ m ^ 2 + n ^ 2 ∧ 2 ∣ m ^ 2 - n ^ 2
∧ ((m ^ 2 - n ^ 2) / 2) % 2 = 0 ∧ int.gcd ((m ^ 2 - n ^ 2) / 2) ((m ^ 2 + n ^ 2) / 2) = 1,
{ exact coprime_sq_sub_sq_sum_of_odd_odd hmncp hm2 hn2 },
have h2 : y = (m ^ 2 - n ^ 2) / 2 ∧ z = (m ^ 2 + n ^ 2) / 2,
{ apply rat.div_int_inj hzpos _ (h.coprime_of_coprime hc) h1.2.2.2,
{ show w = _, rw [←rat.mk_eq_div, ←(rat.div_mk_div_cancel_left (by norm_num : (2 : ℤ) ≠ 0))],
rw [int.div_mul_cancel h1.1, int.div_mul_cancel h1.2.1, hw2], norm_cast },
{ apply (mul_lt_mul_right (by norm_num : 0 < (2 : ℤ))).mp,
rw [int.div_mul_cancel h1.1, zero_mul], exact hm2n2 } },
rw [h2.1, h1.2.2.1] at hyo,
revert hyo,
norm_num }
end
theorem is_primitive_classified_of_coprime_of_pos (hc : int.gcd x y = 1) (hzpos : 0 < z):
h.is_primitive_classified :=
begin
cases h.even_odd_of_coprime hc with h1 h2,
{ exact (h.is_primitive_classified_of_coprime_of_odd_of_pos hc h1.right hzpos) },
rw int.gcd_comm at hc,
obtain ⟨m, n, H⟩ := (h.symm.is_primitive_classified_of_coprime_of_odd_of_pos hc h2.left hzpos),
use [m, n], tauto
end
theorem is_primitive_classified_of_coprime (hc : int.gcd x y = 1) : h.is_primitive_classified :=
begin
by_cases hz : 0 < z,
{ exact h.is_primitive_classified_of_coprime_of_pos hc hz },
have h' : pythagorean_triple x y (-z),
{ simpa [pythagorean_triple, neg_mul_neg] using h.eq, },
apply h'.is_primitive_classified_of_coprime_of_pos hc,
apply lt_of_le_of_ne _ (h'.ne_zero_of_coprime hc).symm,
exact le_neg.mp (not_lt.mp hz)
end
theorem classified : h.is_classified :=
begin
by_cases h0 : int.gcd x y = 0,
{ have hx : x = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_left h0 },
have hy : y = 0, { apply int.nat_abs_eq_zero.mp, apply nat.eq_zero_of_gcd_eq_zero_right h0 },
use [0, 1, 0], norm_num [hx, hy], },
apply h.is_classified_of_normalize_is_primitive_classified,
apply h.normalize.is_primitive_classified_of_coprime,
apply int.gcd_div_gcd_div_gcd (nat.pos_of_ne_zero h0),
end
omit h
theorem coprime_classification :
pythagorean_triple x y z ∧ int.gcd x y = 1 ↔
∃ m n, ((x = m ^ 2 - n ^ 2 ∧ y = 2 * m * n) ∨
(x = 2 * m * n ∧ y = m ^ 2 - n ^ 2))
∧ (z = m ^ 2 + n ^ 2 ∨ z = - (m ^ 2 + n ^ 2))
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0)) :=
begin
split,
{ intro h,
obtain ⟨m, n, H⟩ := h.left.is_primitive_classified_of_coprime h.right,
use [m, n],
rcases H with ⟨⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, co, pp⟩,
{ refine ⟨or.inl ⟨rfl, rfl⟩, _, co, pp⟩,
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2,
{ rw [sq, ← h.left.eq], ring },
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this },
{ refine ⟨or.inr ⟨rfl, rfl⟩, _, co, pp⟩,
have : z ^ 2 = (m ^ 2 + n ^ 2) ^ 2,
{ rw [sq, ← h.left.eq], ring },
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } },
{ delta pythagorean_triple,
rintro ⟨m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl, co, pp⟩;
{ split, { ring }, exact coprime_sq_sub_mul co pp }
<|>
{ split, { ring }, rw int.gcd_comm, exact coprime_sq_sub_mul co pp } }
end
/-- by assuming `x` is odd and `z` is positive we get a slightly more precise classification of
the pythagorean triple `x ^ 2 + y ^ 2 = z ^ 2`-/
theorem coprime_classification' {x y z : ℤ} (h : pythagorean_triple x y z)
(h_coprime : int.gcd x y = 1) (h_parity : x % 2 = 1) (h_pos : 0 < z) :
∃ m n, x = m ^ 2 - n ^ 2
∧ y = 2 * m * n
∧ z = m ^ 2 + n ^ 2
∧ int.gcd m n = 1
∧ ((m % 2 = 0 ∧ n % 2 = 1) ∨ (m % 2 = 1 ∧ n % 2 = 0))
∧ 0 ≤ m :=
begin
obtain ⟨m, n, ht1, ht2, ht3, ht4⟩ :=
pythagorean_triple.coprime_classification.mp (and.intro h h_coprime),
cases le_or_lt 0 m with hm hm,
{ use [m, n],
cases ht1 with h_odd h_even,
{ apply and.intro h_odd.1,
apply and.intro h_odd.2,
cases ht2 with h_pos h_neg,
{ apply and.intro h_pos (and.intro ht3 (and.intro ht4 hm)) },
{ exfalso, revert h_pos, rw h_neg,
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m)
(sq_nonneg n)))) } },
exfalso,
rcases h_even with ⟨rfl, -⟩,
rw [mul_assoc, int.mul_mod_right] at h_parity,
exact zero_ne_one h_parity },
{ use [-m, -n],
cases ht1 with h_odd h_even,
{ rw [neg_sq m],
rw [neg_sq n],
apply and.intro h_odd.1,
split, { rw h_odd.2, ring },
cases ht2 with h_pos h_neg,
{ apply and.intro h_pos,
split,
{ delta int.gcd, rw [int.nat_abs_neg, int.nat_abs_neg], exact ht3 },
{ rw [int.neg_mod_two, int.neg_mod_two],
apply and.intro ht4, linarith } },
{ exfalso, revert h_pos, rw h_neg,
exact imp_false.mpr (not_lt.mpr (neg_nonpos.mpr (add_nonneg (sq_nonneg m)
(sq_nonneg n)))) } },
exfalso,
rcases h_even with ⟨rfl, -⟩,
rw [mul_assoc, int.mul_mod_right] at h_parity,
exact zero_ne_one h_parity }
end
/-- **Formula for Pythagorean Triples** -/
theorem classification :
pythagorean_triple x y z ↔
∃ k m n, ((x = k * (m ^ 2 - n ^ 2) ∧ y = k * (2 * m * n)) ∨
(x = k * (2 * m * n) ∧ y = k * (m ^ 2 - n ^ 2)))
∧ (z = k * (m ^ 2 + n ^ 2) ∨ z = - k * (m ^ 2 + n ^ 2)) :=
begin
split,
{ intro h,
obtain ⟨k, m, n, H⟩ := h.classified,
use [k, m, n],
rcases H with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩,
{ refine ⟨or.inl ⟨rfl, rfl⟩, _⟩,
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2,
{ rw [sq, ← h.eq], ring },
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this },
{ refine ⟨or.inr ⟨rfl, rfl⟩, _⟩,
have : z ^ 2 = (k * (m ^ 2 + n ^ 2)) ^ 2,
{ rw [sq, ← h.eq], ring },
simpa using eq_or_eq_neg_of_sq_eq_sq _ _ this } },
{ rintro ⟨k, m, n, ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, rfl | rfl⟩;
delta pythagorean_triple; ring }
end
end pythagorean_triple
|
d13f14486d14f01138de45295169e4445e1f583b | f618aea02cb4104ad34ecf3b9713065cc0d06103 | /src/data/rat.lean | 3f7cb76704712b6bc96bd2f8b21c854e0c820396 | [
"Apache-2.0"
] | permissive | joehendrix/mathlib | 84b6603f6be88a7e4d62f5b1b0cbb523bb82b9a5 | c15eab34ad754f9ecd738525cb8b5a870e834ddc | refs/heads/master | 1,589,606,591,630 | 1,555,946,393,000 | 1,555,946,393,000 | 182,813,854 | 0 | 0 | null | 1,555,946,309,000 | 1,555,946,308,000 | null | UTF-8 | Lean | false | false | 44,990 | 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
Introduces the rational numbers as discrete, linear ordered field.
-/
import
data.nat.gcd data.pnat data.int.sqrt data.equiv.encodable order.basic
algebra.ordered_field data.real.cau_seq
local attribute [instance, priority 0] nat.cast_coe
local attribute [instance, priority 0] int.cast_coe
/- rational numbers -/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : denom > 0)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (int.of_nat d) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
local infix ` /. `:70 := mk
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_inj, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib] }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply eq_of_mul_eq_mul_right m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom
| ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _
@[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : ℚ → ℚ
| ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance : discrete_field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
zero_ne_one := rat.zero_ne_one,
mul_inv_cancel := rat.mul_inv_cancel,
inv_mul_cancel := rat.inv_mul_cancel,
has_decidable_eq := rat.decidable_eq,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : field ℚ := by apply_instance
instance : division_ring ℚ := by apply_instance
instance : integral_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain ℚ := by apply_instance
instance : nonzero_comm_ring ℚ := by apply_instance
instance : comm_ring ℚ := by apply_instance
--instance : ring ℚ := by apply_instance
instance : comm_semiring ℚ := by apply_instance
instance : semiring ℚ := by apply_instance
instance : add_comm_group ℚ := by apply_instance
instance : add_group ℚ := by apply_instance
instance : add_comm_monoid ℚ := by apply_instance
instance : add_monoid ℚ := by apply_instance
instance : add_left_cancel_semigroup ℚ := by apply_instance
instance : add_right_cancel_semigroup ℚ := by apply_instance
instance : add_comm_semigroup ℚ := by apply_instance
instance : add_semigroup ℚ := by apply_instance
instance : comm_monoid ℚ := by apply_instance
instance : monoid ℚ := by apply_instance
instance : comm_semigroup ℚ := by apply_instance
instance : semigroup ℚ := by apply_instance
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0]
protected def nonneg : ℚ → Prop
| ⟨n, d, h, c⟩ := n ≥ 0
@[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
simp [rat.nonneg],
have d0 := int.coe_nat_lt.2 h₁,
have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha,
constructor; intro h₂,
{ apply nonneg_of_mul_nonneg_right _ d0,
rw this, exact mul_nonneg h₂ (le_of_lt h) },
{ apply nonneg_of_mul_nonneg_right _ h,
rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) },
end
protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
intros n₁0 n₂0,
apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le}
end
protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
begin
have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁),
have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂),
simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0],
exact mul_nonneg
end
protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 :=
num_denom_cases_on' a $ λ n d h,
begin
have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h),
simp [d0, h],
exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁
end
protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) :=
by cases a with n; exact
or.imp_right neg_nonneg_of_nonpos (le_total 0 n)
instance decidable_nonneg : decidable (rat.nonneg a) :=
by cases a; unfold rat.nonneg; apply_instance
protected def le (a b : ℚ) := rat.nonneg (b - a)
instance : has_le ℚ := ⟨rat.le⟩
instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop)
| a b := show decidable (rat.nonneg (b - a)), by apply_instance
protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
show rat.nonneg _ ↔ _,
by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm]
using @sub_nonneg _ _ (b * c) (a * d)
protected theorem le_refl : a ≤ a :=
show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ)
protected theorem le_total : a ≤ b ∨ b ≤ a :=
by have := rat.nonneg_total (b - a); rwa neg_sub at this
protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b :=
by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa);
rwa neg_neg at this
protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc,
by simpa
instance : decidable_linear_order ℚ :=
{ le := rat.le,
le_refl := rat.le_refl,
le_trans := @rat.le_trans,
le_antisymm := @rat.le_antisymm,
le_total := rat.le_total,
decidable_eq := by apply_instance,
decidable_le := assume a b, rat.decidable_nonneg (b - a) }
/- Extra instances to short-circuit type class resolution -/
instance : has_lt ℚ := by apply_instance
instance : lattice.distrib_lattice ℚ := by apply_instance
instance : lattice.lattice ℚ := by apply_instance
instance : lattice.semilattice_inf ℚ := by apply_instance
instance : lattice.semilattice_sup ℚ := by apply_instance
instance : lattice.has_inf ℚ := by apply_instance
instance : lattice.has_sup ℚ := by apply_instance
instance : linear_order ℚ := by apply_instance
instance : partial_order ℚ := by apply_instance
instance : preorder ℚ := by apply_instance
theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a :=
show rat.nonneg a ↔ rat.nonneg (a - 0), by simp
theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a
| ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩
theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) :
a /. b ≤ c /. d ↔ a * d ≤ c * b :=
by conv in (_ ≤ _) {
simp only [(≤), rat.le],
rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁),
mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] }
protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b :=
by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub
protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb
instance : discrete_linear_ordered_field ℚ :=
{ zero_lt_one := dec_trivial,
add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab,
add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba,
not_le_of_lt ab $ rat.add_le_add_left.1 ba,
mul_nonneg := @rat.mul_nonneg,
mul_pos := assume a b ha hb, lt_of_le_of_ne
(rat.mul_nonneg (le_of_lt ha) (le_of_lt hb))
(mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm,
..rat.discrete_field, ..rat.decidable_linear_order }
/- Extra instances to short-circuit type class resolution -/
instance : linear_ordered_field ℚ := by apply_instance
instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_comm_ring ℚ := by apply_instance
instance : linear_ordered_ring ℚ := by apply_instance
instance : ordered_ring ℚ := by apply_instance
instance : decidable_linear_ordered_semiring ℚ := by apply_instance
instance : linear_ordered_semiring ℚ := by apply_instance
instance : ordered_semiring ℚ := by apply_instance
instance : decidable_linear_ordered_comm_group ℚ := by apply_instance
instance : ordered_comm_group ℚ := by apply_instance
instance : ordered_cancel_comm_monoid ℚ := by apply_instance
instance : ordered_comm_monoid ℚ := by apply_instance
attribute [irreducible] rat.le
theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a :=
lt_iff_lt_of_le_iff_le $
by simpa [(by cases a; refl : (-a).num = -a.num)]
using @num_nonneg_iff_zero_le (-a)
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _
theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def,
mul_def one_ne_zero d0, one_mul, mul_one]
end
/-- `floor q` is the largest integer `z` such that `z ≤ q` -/
def floor : ℚ → ℤ
| ⟨n, d, h, c⟩ := n / d
theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r
| ⟨n, d, h, c⟩ := begin
simp [floor],
rw [num_denom'],
have h' := int.coe_nat_lt.2 h,
conv { to_rhs,
rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] },
exact int.le_div_iff_mul_le h'
end
theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z :=
lt_iff_lt_of_le_iff_le le_floor
theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r :=
le_floor.1 (le_refl _)
theorem lt_succ_floor (r : ℚ) : r < (floor r).succ :=
floor_lt.1 $ int.lt_succ_self _
@[simp] theorem floor_coe (z : ℤ) : floor z = z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le]
theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b :=
le_floor.2 (le_trans (floor_le _) h)
@[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z :=
eq_of_forall_le_iff $ λ a, by rw [le_floor,
← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub]
theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z :=
eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _)
/-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/
def ceil (r : ℚ) : ℤ :=
-(floor (-r))
theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z :=
by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff]
theorem le_ceil (r : ℚ) : r ≤ ceil r :=
ceil_le.1 (le_refl _)
@[simp] theorem ceil_coe (z : ℤ) : ceil z = z :=
by rw [ceil, ← int.cast_neg, floor_coe, neg_neg]
theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b :=
ceil_le.2 (le_trans h (le_ceil _))
@[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z :=
by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl
theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z :=
eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _)
/- cast (injection into fields) -/
section cast
variables {α : Type*}
section
variables [division_ring α]
/-- Construct the canonical injection from `ℚ` into an arbitrary
division ring. If the field has positive characteristic `p`,
we define `1 / p = 1 / 0 = 0` for consistency with our
division by zero convention. -/
protected def cast : ℚ → α
| ⟨n, d, h, c⟩ := n / d
def cast_coe : has_coe ℚ α := ⟨rat.cast⟩
local attribute [instance, priority 0] cast_coe
@[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n :=
show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one]
@[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n :=
by rw [coe_int_eq_of_int, cast_of_int]
@[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
@[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
@[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n
@[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 :=
(cast_of_int _).trans int.cast_zero
@[simp] theorem cast_one : ((1 : ℚ) : α) = 1 :=
(cast_of_int _).trans int.cast_one
theorem mul_cast_comm (a : α) :
∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a
| ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a,
by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc,
← show (d:α)⁻¹ * a = a * d⁻¹, from
division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm]
theorem cast_mk_of_ne_zero (a b : ℤ)
(b0 : (b:α) ≠ 0) : (a /. b : α) = a / b :=
begin
have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} },
cases e : a /. b with n d h c,
have d0 : (d:α) ≠ 0,
{ intro d0,
have dd := denom_dvd a b,
cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke,
have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl},
rw [d0, zero_mul] at this, contradiction },
rw [num_denom'] at e,
have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e),
rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this,
symmetry, change (a * b⁻¹ : α) = n / d,
rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm,
← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one]
end
theorem cast_add_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', add_def d₁0' d₂0'],
suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) +
n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹,
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, left_distrib, right_distrib, mul_inv_eq,
d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul,
← nat.mul_cast_comm], simp [d₁0, mul_assoc]
end
@[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n
| ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹),
by rw [int.cast_neg, neg_mul_eq_neg_mul]
theorem cast_sub_of_ne_zero {m n : ℚ}
(m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n :=
have ((-n).denom : α) ≠ 0, by cases n; exact n0,
by simp [m0, this, cast_add_of_ne_zero]
theorem cast_mul_of_ne_zero : ∀ {m n : ℚ},
(m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin
have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl),
have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl),
rw [num_denom', num_denom', mul_def d₁0' d₂0'],
suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)),
{ rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero],
{ simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] },
all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} },
rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm]
end
theorem cast_inv_of_ne_zero : ∀ {n : ℚ},
(n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹
| ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin
have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl,
have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl),
rw [num_denom', inv_def],
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div];
simp [n0, d0]
end
theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0)
(nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n :=
have (n⁻¹.denom : ℤ) ∣ n.num,
by conv in n⁻¹.denom { rw [num_denom n, inv_def] };
apply denom_dvd,
have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from
λ h, let ⟨k, e⟩ := this in
by have := congr_arg (coe : ℤ → α) e;
rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this,
by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def]
@[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin
refine ⟨λ h, _, congr_arg _⟩,
have d₁0 : d₁ ≠ 0 := ne_of_gt h₁,
have d₂0 : d₂ ≠ 0 := ne_of_gt h₂,
have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0,
have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0,
rw [num_denom', num_denom'] at h ⊢,
rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢,
rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc,
division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _),
← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm,
← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul,
int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h
end
theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α)
| m n := cast_inj.1
@[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 :=
by rw [← cast_zero, cast_inj]
@[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 :=
not_congr cast_eq_zero
theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) :
∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n
| ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin
rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂],
have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] },
rw [← this, ← this, ← Hmul, div_mul_cancel],
exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h),
end
theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1)
(Hadd : ∀ x y, f (x + y) = f x + f y)
(Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n :=
eq_cast_of_ne_zero _ H1 Hadd Hmul _ $
nat.cast_ne_zero.2 $ ne_of_gt n.pos
end
local attribute [instance, priority 0] cast_coe
theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b :=
if b0 : b = 0 then by simp [b0, div_zero]
else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0)
@[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n :=
cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n :=
cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n :=
cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ :=
if n0 : n.num = 0 then
by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else
cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos)
@[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n :=
by rw [division_def, cast_mul, cast_inv, division_def]
@[simp] theorem cast_pow [discrete_field α] [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k :=
by induction k; simp only [*, cast_one, cast_mul, pow_zero, pow_succ]
@[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _
@[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n :=
by rw [bit1, cast_add, cast_one, cast_bit0]; refl
@[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n
| ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ),
by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h),
mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)),
int.cast_nonneg]
@[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
@[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n :=
by simpa [-cast_le] using not_congr (@cast_le α _ n m)
@[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_id : ∀ n : ℚ, ↑n = n
| ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div]
@[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b :=
by by_cases a ≤ b; simp [h, min]
@[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b :=
by by_cases a ≤ b; simp [h, max]
@[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q :=
by simp [abs]
end cast
/- nat ceiling -/
/-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`.
It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/
def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q)
theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n :=
by rw [nat_ceil, int.to_nat_le, ceil_le]; refl
theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q :=
not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le]
theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q :=
nat_ceil_le.1 (le_refl _)
theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ :=
nat_ceil_le.2 (le_trans h (le_nat_ceil _))
@[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n :=
show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl
@[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0
theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n :=
show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n,
by rw [ceil_add_int]; exact
match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with
| _, ⟨m, rfl⟩ := rfl
end
theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 :=
lt_nat_ceil.1 $ by rw [
show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self
@[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom
| ⟨_, d, _, _⟩ := rfl
@[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num)
| ⟨n, _, _, _⟩ := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom _,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by rwa [←num_denom q, ←num_denom r] at this,
by simp [mul_def hq' hr']
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else calc q / r = q * r⁻¹ : div_eq_mul_inv
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by rw [←num_denom q, ←num_denom r]
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
have hq : q ≠ 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [←rat.num_denom q],
have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{apply rat.num_ne_zero_of_ne_zero hq},
{simp [rat.denom_ne_zero]},
repeat {assumption} }
end
theorem mk_pnat_num (n : ℤ) (d : ℕ+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num =
(q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom =
(q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem abs_def (q : ℚ) : abs q = q.num.nat_abs /. q.denom :=
begin
have hz : (0:ℚ) = 0 /. 1 := rfl,
cases le_total q 0 with hq hq,
{ rw [abs_of_nonpos hq],
rw [num_denom q, hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one,
mul_one, zero_mul] at hq,
rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, ← num_denom q] },
{ rw [abs_of_nonneg hq],
rw [num_denom q, hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos),
mul_one, zero_mul] at hq,
rw [int.nat_abs_of_nonneg hq, ← num_denom q] }
end
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv { to_lhs, rw [rat.num_denom q, rat.num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
def sqrt (q : ℚ) : ℚ :=
rat.mk (int.sqrt q.num) (nat.sqrt q.denom)
theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = abs q :=
by rw [sqrt, mul_self_num, mul_self_denom,
int.sqrt_eq, nat.sqrt_eq, abs_def]
theorem exists_mul_self (x : ℚ) :
(∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x :=
⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self],
λ h, ⟨rat.sqrt x, h⟩⟩
theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q :=
nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $
nat.pos_of_ne_zero $ λ H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial
end rat
|
136d9bd4ca4d5b13f099e545b168ddd3b46e1a38 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/algebraic_geometry/projective_spectrum/scheme.lean | d99ce60d766e8010920b50a2e4a623cdc218c3fc | [
"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 | 14,993 | lean | /-
Copyright (c) 2022 Jujian Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jujian Zhang
-/
import algebraic_geometry.projective_spectrum.structure_sheaf
import algebraic_geometry.Spec
/-!
# Proj as a scheme
This file is to prove that `Proj` is a scheme.
## Notation
* `Proj` : `Proj` as a locally ringed space
* `Proj.T` : the underlying topological space of `Proj`
* `Proj| U` : `Proj` restricted to some open set `U`
* `Proj.T| U` : the underlying topological space of `Proj` restricted to open set `U`
* `pbo f` : basic open set at `f` in `Proj`
* `Spec` : `Spec` as a locally ringed space
* `Spec.T` : the underlying topological space of `Spec`
* `sbo g` : basic open set at `g` in `Spec`
* `A⁰_x` : the degree zero part of localized ring `Aₓ`
## Implementation
In `src/algebraic_geometry/projective_spectrum/structure_sheaf.lean`, we have given `Proj` a
structure sheaf so that `Proj` is a locally ringed space. In this file we will prove that `Proj`
equipped with this structure sheaf is a scheme. We achieve this by using an affine cover by basic
open sets in `Proj`, more specifically:
1. We prove that `Proj` can be covered by basic open sets at homogeneous element of positive degree.
2. We prove that for any `f : A`, `Proj.T | (pbo f)` is homeomorphic to `Spec.T A⁰_f`:
- forward direction `to_Spec`:
for any `x : pbo f`, i.e. a relevant homogeneous prime ideal `x`, send it to
`x ∩ span {g / 1 | g ∈ A}` (see `Proj_iso_Spec_Top_component.to_Spec.carrier`). This ideal is
prime, the proof is in `Proj_iso_Spec_Top_component.to_Spec.to_fun`. The fact that this function
is continuous is found in `Proj_iso_Spec_Top_component.to_Spec`
- backward direction `from_Spec`: TBC
## Main Definitions and Statements
* `degree_zero_part`: the degree zero part of the localized ring `Aₓ` where `x` is a homogeneous
element of degree `n` is the subring of elements of the form `a/f^m` where `a` has degree `mn`.
For a homogeneous element `f` of degree `n`
* `Proj_iso_Spec_Top_component.to_Spec`: `forward f` is the
continuous map between `Proj.T| pbo f` and `Spec.T A⁰_f`
* `Proj_iso_Spec_Top_component.to_Spec.preimage_eq`: for any `a: A`, if `a/f^m` has degree zero,
then the preimage of `sbo a/f^m` under `to_Spec f` is `pbo f ∩ pbo a`.
* [Robin Hartshorne, *Algebraic Geometry*][Har77]: Chapter II.2 Proposition 2.5
-/
noncomputable theory
namespace algebraic_geometry
open_locale direct_sum big_operators pointwise big_operators
open direct_sum set_like.graded_monoid localization finset (hiding mk_zero)
variables {R A : Type*}
variables [comm_ring R] [comm_ring A] [algebra R A]
variables (𝒜 : ℕ → submodule R A)
variables [graded_algebra 𝒜]
open Top topological_space
open category_theory opposite
open projective_spectrum.structure_sheaf
local notation `Proj` := Proj.to_LocallyRingedSpace 𝒜
-- `Proj` as a locally ringed space
local notation `Proj.T` := Proj .1.1.1
-- the underlying topological space of `Proj`
local notation `Proj| ` U := Proj .restrict (opens.open_embedding (U : opens Proj.T))
-- `Proj` restrict to some open set
local notation `Proj.T| ` U :=
(Proj .restrict (opens.open_embedding (U : opens Proj.T))).to_SheafedSpace.to_PresheafedSpace.1
-- the underlying topological space of `Proj` restricted to some open set
local notation `pbo` x := projective_spectrum.basic_open 𝒜 x
-- basic open sets in `Proj`
local notation `sbo` f := prime_spectrum.basic_open f
-- basic open sets in `Spec`
local notation `Spec` ring := Spec.LocallyRingedSpace_obj (CommRing.of ring)
-- `Spec` as a locally ringed space
local notation `Spec.T` ring :=
(Spec.LocallyRingedSpace_obj (CommRing.of ring)).to_SheafedSpace.to_PresheafedSpace.1
-- the underlying topological space of `Spec`
section
variable {𝒜}
/--
The degree zero part of the localized ring `Aₓ` is the subring of elements of the form `a/x^n` such
that `a` and `x^n` have the same degree.
-/
def degree_zero_part {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) : subring (away f) :=
{ carrier := { y | ∃ (n : ℕ) (a : 𝒜 (m * n)), y = mk a ⟨f^n, ⟨n, rfl⟩⟩ },
mul_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸
⟨n+n', ⟨⟨a.1 * b.1, (mul_add m n n').symm ▸ mul_mem a.2 b.2⟩,
by {rw mk_mul, congr' 1, simp only [pow_add], refl }⟩⟩,
one_mem' := ⟨0, ⟨1, (mul_zero m).symm ▸ one_mem⟩,
by { symmetry, rw subtype.coe_mk, convert ← mk_self 1, simp only [pow_zero], refl, }⟩,
add_mem' := λ _ _ ⟨n, ⟨a, h⟩⟩ ⟨n', ⟨b, h'⟩⟩, h.symm ▸ h'.symm ▸
⟨n+n', ⟨⟨f ^ n * b.1 + f ^ n' * a.1, (mul_add m n n').symm ▸
add_mem (mul_mem (by { rw mul_comm, exact set_like.pow_mem_graded n f_deg }) b.2)
begin
rw add_comm,
refine mul_mem _ a.2,
rw mul_comm,
exact set_like.pow_mem_graded _ f_deg
end⟩, begin
rw add_mk,
congr' 1,
simp only [pow_add],
refl,
end⟩⟩,
zero_mem' := ⟨0, ⟨0, (mk_zero _).symm⟩⟩,
neg_mem' := λ x ⟨n, ⟨a, h⟩⟩, h.symm ▸ ⟨n, ⟨-a, neg_mk _ _⟩⟩ }
end
local notation `A⁰_` f_deg := degree_zero_part f_deg
section
variable {𝒜}
instance (f : A) {m : ℕ} (f_deg : f ∈ 𝒜 m) : comm_ring (A⁰_ f_deg) :=
(degree_zero_part f_deg).to_comm_ring
/--
Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`,
`degree_zero_part.deg` picks this natural number `n`
-/
def degree_zero_part.deg {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : ℕ :=
x.2.some
/--
Every element in the degree zero part of `Aₓ` can be written as `a/x^n` for some `a` and `n : ℕ`,
`degree_zero_part.deg` picks the numerator `a`
-/
def degree_zero_part.num {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) : A :=
x.2.some_spec.some.1
lemma degree_zero_part.num_mem {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) :
degree_zero_part.num x ∈ 𝒜 (m * degree_zero_part.deg x) :=
x.2.some_spec.some.2
lemma degree_zero_part.eq {f : A} {m : ℕ} {f_deg : f ∈ 𝒜 m} (x : A⁰_ f_deg) :
(x : away f) = mk (degree_zero_part.num x) ⟨f^(degree_zero_part.deg x), ⟨_, rfl⟩⟩ :=
x.2.some_spec.some_spec
lemma degree_zero_part.coe_mul {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x y : A⁰_ f_deg) :
(↑(x * y) : away f) = x * y := rfl
end
namespace Proj_iso_Spec_Top_component
/-
This section is to construct the homeomorphism between `Proj` restricted at basic open set at
a homogeneous element `x` and `Spec A⁰ₓ` where `A⁰ₓ` is the degree zero part of the localized
ring `Aₓ`.
-/
namespace to_Spec
open ideal
-- This section is to construct the forward direction :
-- So for any `x` in `Proj| (pbo f)`, we need some point in `Spec A⁰_f`, i.e. a prime ideal,
-- and we need this correspondence to be continuous in their Zariski topology.
variables {𝒜} {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : Proj| (pbo f))
/--For any `x` in `Proj| (pbo f)`, the corresponding ideal in `Spec A⁰_f`. This fact that this ideal
is prime is proven in `Top_component.forward.to_fun`-/
def carrier : ideal (A⁰_ f_deg) :=
ideal.comap (algebra_map (A⁰_ f_deg) (away f))
(ideal.span $ algebra_map A (away f) '' x.1.as_homogeneous_ideal)
lemma mem_carrier_iff (z : A⁰_ f_deg) :
z ∈ carrier f_deg x ↔
↑z ∈ ideal.span (algebra_map A (away f) '' x.1.as_homogeneous_ideal) :=
iff.rfl
lemma mem_carrier.clear_denominator [decidable_eq (away f)]
{z : A⁰_ f_deg} (hz : z ∈ carrier f_deg x) :
∃ (c : algebra_map A (away f) '' x.1.as_homogeneous_ideal →₀ away f)
(N : ℕ)
(acd : Π y ∈ c.support.image c, A),
f ^ N • ↑z =
algebra_map A (away f) (∑ i in c.support.attach,
acd (c i) (finset.mem_image.mpr ⟨i, ⟨i.2, rfl⟩⟩) * classical.some i.1.2) :=
begin
rw [mem_carrier_iff, ←submodule_span_eq, finsupp.span_eq_range_total, linear_map.mem_range] at hz,
rcases hz with ⟨c, eq1⟩,
rw [finsupp.total_apply, finsupp.sum] at eq1,
obtain ⟨⟨_, N, rfl⟩, hN⟩ := is_localization.exist_integer_multiples_of_finset (submonoid.powers f)
(c.support.image c),
choose acd hacd using hN,
have prop1 : ∀ i, i ∈ c.support → c i ∈ finset.image c c.support,
{ intros i hi, rw finset.mem_image, refine ⟨_, hi, rfl⟩, },
refine ⟨c, N, acd, _⟩,
rw [← eq1, smul_sum, map_sum, ← sum_attach],
congr' 1,
ext i,
rw [_root_.map_mul, hacd, (classical.some_spec i.1.2).2, smul_eq_mul, smul_mul_assoc],
refl
end
lemma disjoint :
(disjoint (x.1.as_homogeneous_ideal.to_ideal : set A) (submonoid.powers f : set A)) :=
begin
by_contra rid,
rw [set.not_disjoint_iff] at rid,
choose g hg using rid,
obtain ⟨hg1, ⟨k, rfl⟩⟩ := hg,
by_cases k_ineq : 0 < k,
{ erw x.1.is_prime.pow_mem_iff_mem _ k_ineq at hg1,
exact x.2 hg1 },
{ erw [show k = 0, by linarith, pow_zero, ←ideal.eq_top_iff_one] at hg1,
apply x.1.is_prime.1,
exact hg1 },
end
lemma carrier_ne_top :
carrier f_deg x ≠ ⊤ :=
begin
have eq_top := disjoint x,
classical,
contrapose! eq_top,
obtain ⟨c, N, acd, eq1⟩ := mem_carrier.clear_denominator _ x ((ideal.eq_top_iff_one _).mp eq_top),
rw [algebra.smul_def, subring.coe_one, mul_one] at eq1,
change localization.mk (f ^ N) 1 = mk (∑ _, _) 1 at eq1,
simp only [mk_eq_mk', is_localization.eq] at eq1,
rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩,
erw [mul_one, mul_one] at eq1,
change f^_ * f^_ = _ * f^_ at eq1,
rw set.not_disjoint_iff_nonempty_inter,
refine ⟨f^N * f^M, eq1.symm ▸ mul_mem_right _ _
(sum_mem _ (λ i hi, mul_mem_left _ _ _)), ⟨N+M, by rw pow_add⟩⟩,
generalize_proofs h,
exact (classical.some_spec h).1,
end
/--The function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in
`Spec A⁰_f`. This is bundled into a continuous map in `Top_component.forward`.
-/
def to_fun (x : Proj.T| (pbo f)) : (Spec.T (A⁰_ f_deg)) :=
⟨carrier f_deg x, carrier_ne_top f_deg x, λ x1 x2 hx12, begin
classical,
rcases ⟨x1, x2⟩ with ⟨⟨x1, hx1⟩, ⟨x2, hx2⟩⟩,
induction x1 using localization.induction_on with data_x1,
induction x2 using localization.induction_on with data_x2,
rcases ⟨data_x1, data_x2⟩ with ⟨⟨a1, _, ⟨n1, rfl⟩⟩, ⟨a2, _, ⟨n2, rfl⟩⟩⟩,
rcases mem_carrier.clear_denominator f_deg x hx12 with ⟨c, N, acd, eq1⟩,
simp only [degree_zero_part.coe_mul, algebra.smul_def] at eq1,
change localization.mk (f ^ N) 1 * (mk _ _ * mk _ _) = mk (∑ _, _) _ at eq1,
simp only [localization.mk_mul, one_mul] at eq1,
simp only [mk_eq_mk', is_localization.eq] at eq1,
rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩,
rw [submonoid.coe_one, mul_one] at eq1,
change _ * _ * f^_ = _ * (f^_ * f^_) * f^_ at eq1,
rcases x.1.is_prime.mem_or_mem (show a1 * a2 * f ^ N * f ^ M ∈ _, from _) with h1|rid2,
rcases x.1.is_prime.mem_or_mem h1 with h1|rid1,
rcases x.1.is_prime.mem_or_mem h1 with h1|h2,
{ left,
rw mem_carrier_iff,
simp only [show (mk a1 ⟨f ^ n1, _⟩ : away f) = mk a1 1 * mk 1 ⟨f^n1, ⟨n1, rfl⟩⟩,
by rw [localization.mk_mul, mul_one, one_mul]],
exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h1, rfl⟩), },
{ right,
rw mem_carrier_iff,
simp only [show (mk a2 ⟨f ^ n2, _⟩ : away f) = mk a2 1 * mk 1 ⟨f^n2, ⟨n2, rfl⟩⟩,
by rw [localization.mk_mul, mul_one, one_mul]],
exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h2, rfl⟩), },
{ exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem N rid1)), },
{ exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem M rid2)), },
{ rw [mul_comm _ (f^N), eq1],
refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))),
generalize_proofs h,
exact (classical.some_spec h).1 },
end⟩
/-
The preimage of basic open set `D(a/f^n)` in `Spec A⁰_f` under the forward map from `Proj A` to
`Spec A⁰_f` is the basic open set `D(a) ∩ D(f)` in `Proj A`. This lemma is used to prove that the
forward map is continuous.
-/
lemma preimage_eq (a : A) (n : ℕ)
(a_mem_degree_zero : (mk a ⟨f ^ n, ⟨n, rfl⟩⟩ : away f) ∈ A⁰_ f_deg) :
to_fun 𝒜 f_deg ⁻¹'
((sbo (⟨mk a ⟨f ^ n, ⟨_, rfl⟩⟩, a_mem_degree_zero⟩ : A⁰_ f_deg)) :
set (prime_spectrum {x // x ∈ A⁰_ f_deg}))
= {x | x.1 ∈ (pbo f) ⊓ (pbo a)} :=
begin
classical,
ext1 y, split; intros hy,
{ refine ⟨y.2, _⟩,
rw [set.mem_preimage, opens.mem_coe, prime_spectrum.mem_basic_open] at hy,
rw projective_spectrum.mem_coe_basic_open,
intro a_mem_y,
apply hy,
rw [to_fun, mem_carrier_iff],
simp only [show (mk a ⟨f^n, ⟨_, rfl⟩⟩ : away f) = mk 1 ⟨f^n, ⟨_, rfl⟩⟩ * mk a 1,
by rw [mk_mul, one_mul, mul_one]],
exact ideal.mul_mem_left _ _ (ideal.subset_span ⟨_, a_mem_y, rfl⟩), },
{ change y.1 ∈ _ at hy,
rcases hy with ⟨hy1, hy2⟩,
rw projective_spectrum.mem_coe_basic_open at hy1 hy2,
rw [set.mem_preimage, to_fun, opens.mem_coe, prime_spectrum.mem_basic_open],
intro rid,
rcases mem_carrier.clear_denominator f_deg _ rid with ⟨c, N, acd, eq1⟩,
rw [algebra.smul_def] at eq1,
change localization.mk (f^N) 1 * mk _ _ = mk (∑ _, _) _ at eq1,
rw [mk_mul, one_mul, mk_eq_mk', is_localization.eq] at eq1,
rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩,
rw [submonoid.coe_one, mul_one] at eq1,
simp only [subtype.coe_mk] at eq1,
rcases y.1.is_prime.mem_or_mem (show a * f ^ N * f ^ M ∈ _, from _) with H1 | H3,
rcases y.1.is_prime.mem_or_mem H1 with H1 | H2,
{ exact hy2 H1, },
{ exact y.2 (y.1.is_prime.mem_of_pow_mem N H2), },
{ exact y.2 (y.1.is_prime.mem_of_pow_mem M H3), },
{ rw [mul_comm _ (f^N), eq1],
refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))),
generalize_proofs h,
exact (classical.some_spec h).1, }, },
end
end to_Spec
section
variable {𝒜}
/--The continuous function between the basic open set `D(f)` in `Proj` to the corresponding basic
open set in `Spec A⁰_f`.
-/
def to_Spec {f : A} (m : ℕ) (f_deg : f ∈ 𝒜 m) :
(Proj.T| (pbo f)) ⟶ (Spec.T (A⁰_ f_deg)) :=
{ to_fun := to_Spec.to_fun 𝒜 f_deg,
continuous_to_fun := begin
apply is_topological_basis.continuous (prime_spectrum.is_topological_basis_basic_opens),
rintros _ ⟨⟨g, hg⟩, rfl⟩,
induction g using localization.induction_on with data,
obtain ⟨a, ⟨_, ⟨n, rfl⟩⟩⟩ := data,
erw to_Spec.preimage_eq,
refine is_open_induced_iff.mpr ⟨(pbo f).1 ⊓ (pbo a).1, is_open.inter (pbo f).2 (pbo a).2, _⟩,
ext z, split; intros hz; simpa [set.mem_preimage],
end }
end
end Proj_iso_Spec_Top_component
end algebraic_geometry
|
3b3b671b7871ed9380bfb7ff91bdb58d546ea2e8 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/order/boolean_algebra.lean | bba1cd7a4266310a570f49a27dc5f3a8c4f19fb7 | [
"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 | 3,851 | 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
Type class hierarchy for Boolean algebras.
-/
import order.bounded_lattice
set_option old_structure_cmd true
universes u v
variables {α : Type u} {w x y z : α}
/-- Set / lattice complement -/
class has_compl (α : Type*) := (compl : α → α)
export has_compl (compl)
postfix `ᶜ`:(max+1) := compl
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A boolean algebra is a bounded distributive lattice with a
complementation operation `-` such that `x ⊓ - x = ⊥` and `x ⊔ - x = ⊤`.
This is a generalization of (classical) logic of propositions, or
the powerset lattice. -/
class boolean_algebra α extends bounded_distrib_lattice α, has_compl α, has_sdiff α :=
(inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥)
(top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ)
(sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ)
end prio
section boolean_algebra
variables [boolean_algebra α]
@[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ :=
bot_unique $ boolean_algebra.inf_compl_le_bot x
@[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ :=
eq.trans inf_comm inf_compl_eq_bot
@[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ :=
top_unique $ boolean_algebra.top_le_sup_compl x
@[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ :=
eq.trans sup_comm sup_compl_eq_top
theorem is_compl_compl : is_compl x xᶜ :=
is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top
theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y :=
(h.right_unique is_compl_compl).symm
theorem sdiff_eq : x \ y = x ⊓ yᶜ :=
boolean_algebra.sdiff_eq x y
theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y :=
(is_compl.of_eq i s).compl_eq
@[simp] theorem compl_top : ⊤ᶜ = (⊥:α) :=
is_compl_top_bot.compl_eq
@[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) :=
is_compl_bot_top.compl_eq
@[simp] theorem compl_compl' : xᶜᶜ = x :=
is_compl_compl.symm.compl_eq
theorem compl_injective : function.injective (compl : α → α) :=
function.involutive.injective $ λ x, compl_compl'
@[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y :=
compl_injective.eq_iff
@[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ :=
(is_compl_compl.inf_sup is_compl_compl).compl_eq
@[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ :=
(is_compl_compl.sup_inf is_compl_compl).compl_eq
theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ :=
is_compl_compl.antimono is_compl_compl h
theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y :=
⟨assume h, by have h := compl_le_compl h; simp at h; assumption,
compl_le_compl⟩
theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ :=
by simpa only [compl_compl'] using compl_le_compl h
theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y :=
by simpa only [compl_compl'] using compl_le_compl h
theorem compl_le_iff_compl_le : y ≤ xᶜ ↔ x ≤ yᶜ :=
⟨le_compl_of_le_compl, le_compl_of_le_compl⟩
theorem sup_sdiff_same : x ⊔ (y \ x) = x ⊔ y :=
by simp [sdiff_eq, sup_inf_left]
theorem sdiff_eq_left (h : x ⊓ y = ⊥) : x \ y = x :=
by rwa [sdiff_eq, inf_eq_left, is_compl_compl.le_right_iff, disjoint_iff]
theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z :=
by rw [sdiff_eq, sdiff_eq]; from inf_le_inf h₁ (compl_le_compl h₂)
end boolean_algebra
instance boolean_algebra_Prop : boolean_algebra Prop :=
{ compl := not,
sdiff := λ p q, p ∧ ¬ q,
sdiff_eq := λ _ _, rfl,
inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp,
top_le_sup_compl := λ p H, classical.em p,
.. bounded_distrib_lattice_Prop }
instance pi.boolean_algebra {α : Type u} {β : Type v} [boolean_algebra β] :
boolean_algebra (α → β) :=
by pi_instance
|
abf99ec9f26b25f3cd89d289a496fc96cfcfbbaf | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/facts/nnreal.lean | 7f39c879ed061d5121d384dcb22f4b4c5be6fdbd | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,836 | lean | import data.real.nnreal
open_locale nnreal
namespace nnreal
variables (r r' k c c₁ c₂ c₃ : ℝ≥0)
instance fact_le_of_lt [h : fact (c₁ < c₂)] : fact (c₁ ≤ c₂) := ⟨h.1.le⟩
instance fact_pos_of_one_le [hk : fact (1 ≤ c)] : fact (0 < c) :=
⟨lt_of_lt_of_le zero_lt_one hk.1⟩
instance fact_le_mul_of_one_le_left [hk : fact (1 ≤ k)] [hc : fact (c₁ ≤ c₂)] :
fact (c₁ ≤ k * c₂) :=
⟨calc c₁ = 1 * c₁ : (one_mul _).symm ... ≤ k * c₂ : mul_le_mul' hk.1 hc.1⟩
instance fact_le_mul_of_one_le_right [hc : fact (c₁ ≤ c₂)] [hk : fact (1 ≤ k)] :
fact (c₁ ≤ c₂ * k) :=
⟨calc c₁ = c₁ * 1 : (mul_one _).symm ... ≤ c₂ * k : mul_le_mul' hc.1 hk.1⟩
instance fact_mul_le_of_le_one_left [hk : fact (k ≤ 1)] [hc : fact (c₁ ≤ c₂)] :
fact (k * c₁ ≤ c₂) :=
⟨calc k * c₁ ≤ 1 * c₂ : mul_le_mul' hk.1 hc.1 ... = c₂ : one_mul _⟩
instance fact_mul_le_of_le_one_right [hk : fact (k ≤ 1)] [hc : fact (c₁ ≤ c₂)] :
fact (c₁ * k ≤ c₂) :=
⟨calc c₁ * k ≤ c₂ * 1 : mul_le_mul' hc.1 hk.1 ... = c₂ : mul_one _⟩
instance fact_one_le_add_one : fact (1 ≤ k + 1) :=
⟨self_le_add_left 1 k⟩
instance fact_le_refl : fact (c ≤ c) := ⟨le_rfl⟩
instance fact_le_subst_right [fact (c₁ ≤ c₂)] [h : fact (c₂ = c₃)]: fact (c₁ ≤ c₃) :=
by rwa ← h.1
instance fact_le_subst_right' [fact (c₁ ≤ c₂)] [h : fact (c₃ = c₂)]: fact (c₁ ≤ c₃) :=
by rwa ← h.1.symm
instance fact_le_subst_left [fact (c₁ ≤ c₂)] [h : fact (c₁ = c₃)]: fact (c₃ ≤ c₂) :=
by rwa ← h.1
instance fact_le_subst_left' [fact (c₁ ≤ c₂)] [h : fact (c₃ = c₁)]: fact (c₃ ≤ c₂) :=
by rwa ← h.1.symm
instance fact_inv_mul_le [h : fact (0 < r')] : fact (r'⁻¹ * (r' * c) ≤ c) :=
⟨le_of_eq $ inv_mul_cancel_left' (ne_of_gt h.1) _⟩
instance fact_mul_le_mul_left [h : fact (c₁ ≤ c₂)] : fact (r' * c₁ ≤ r' * c₂) :=
⟨mul_le_mul' le_rfl h.1⟩
instance fact_mul_le_mul_right [h : fact (c₁ ≤ c₂)] : fact (c₁ * r' ≤ c₂ * r') :=
⟨mul_le_mul' h.1 le_rfl⟩
instance fact_le_inv_mul_self [h1 : fact (0 < r')] [h2 : fact (r' ≤ 1)] : fact (c ≤ r'⁻¹ * c) :=
begin
constructor,
rw mul_comm,
apply le_mul_inv_of_mul_le (ne_of_gt h1.1),
nth_rewrite 1 ← mul_one c,
exact mul_le_mul (le_of_eq rfl) h2.1 (le_of_lt h1.1) zero_le',
end
instance fact_le_max_left (a b c : ℝ≥0) [h : fact (a ≤ b)] : fact (a ≤ max b c) :=
⟨h.1.trans $ le_max_left _ _⟩
instance fact_one_le_mul_self (a : ℝ≥0) [h : fact (1 ≤ a)] : fact (1 ≤ a * a) :=
⟨calc (1 : ℝ≥0) = 1 * 1 : (mul_one 1).symm
... ≤ a * a : mul_le_mul' h.1 h.1⟩
instance one_le_add {a b : ℝ≥0} [ha : fact (1 ≤ a)] : fact (1 ≤ a + b) :=
⟨le_trans ha.1 $ by simp⟩
instance one_le_add' {a b : ℝ≥0} [hb : fact (1 ≤ b)] : fact (1 ≤ a + b) :=
⟨le_trans hb.1 $ by simp⟩
instance fact_one_le_pow {n : ℕ} {a : ℝ≥0} [h : fact (1 ≤ a)] : fact (1 ≤ a^n) :=
begin
cases n,
{ simpa only [pow_zero] using nnreal.fact_le_refl _ },
{ rwa one_le_pow_iff, apply nat.succ_ne_zero }
end
instance fact_pow_le_one {n : ℕ} {a : ℝ≥0} [h : fact (a ≤ 1)] : fact (a^n ≤ 1) :=
begin
cases n,
{ simpa only [pow_zero] using nnreal.fact_le_refl _ },
{ rwa pow_le_one_iff, apply nat.succ_ne_zero }
end
lemma fact_le_pow_mul_of_le_pow_succ_mul {n : ℕ} (r : ℝ≥0)
[fact (r ≤ 1)] [h : fact (c₂ ≤ r ^ (n+1) * c₁)] :
fact (c₂ ≤ r ^ n * c₁) :=
begin
refine ⟨h.1.trans _⟩,
rw [pow_succ, mul_assoc],
apply fact.out
end
instance fact_le_mul_add : fact (c * c₁ + c * c₂ ≤ c * (c₁ + c₂)) :=
by { rw mul_add, exact nnreal.fact_le_refl _ }
instance fact_nat_cast_pos (N : ℕ) [hN: fact (0 < N)] : fact (0 < (N:ℝ≥0)) :=
⟨nat.cast_pos.mpr hN.1⟩
instance fact_nat_cast_inv_le_one (N : ℕ) : fact ((N:ℝ≥0)⁻¹ ≤ 1) :=
begin
by_cases hN : N = 0,
{ subst hN, simp only [nat.cast_zero, inv_zero, zero_le'], exact ⟨trivial⟩ },
{ rw [inv_le, mul_one], swap, { exact_mod_cast hN },
norm_cast,
rw nat.add_one_le_iff,
exact ⟨nat.pos_of_ne_zero hN⟩, }
end
instance fact_inv_le_one [H : fact (1 ≤ c)] : fact (c⁻¹ ≤ 1) :=
begin
by_cases hc : c = 0,
{ rw hc at H, exact (not_le_of_lt zero_lt_one H.1).elim },
rwa [inv_le hc, mul_one]
end
instance fact_one_le_two : fact ((1:ℝ≥0) ≤ 2) := ⟨one_le_two⟩
instance fact_two_pow_inv_le_two_pow_inv (N : ℕ) : fact ((2 ^ N : ℝ≥0)⁻¹ ≤ (2 ^ N : ℕ)⁻¹) :=
⟨le_of_eq $ by norm_cast⟩
instance fact_two_pow_inv_le_one (N : ℕ) : fact ((2 ^ N : ℝ≥0)⁻¹ ≤ 1) :=
⟨le_trans (nnreal.fact_two_pow_inv_le_two_pow_inv N).1 $ fact.out _⟩
end nnreal
#lint- only unused_arguments def_lemma doc_blame
|
dfbb3fee5c2d74aeaf1551046002455eef783a3e | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/Tactic/Congr.lean | 72ed18527ae8a0540f0a613a5a24eb827914b937 | [
"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 | EdAyers/lean4 | 57ac632d6b0789cb91fab2170e8c9e40441221bd | 37ba0df5841bde51dbc2329da81ac23d4f6a4de4 | refs/heads/master | 1,676,463,245,298 | 1,660,619,433,000 | 1,660,619,433,000 | 183,433,437 | 1 | 0 | Apache-2.0 | 1,657,612,672,000 | 1,556,196,574,000 | Lean | UTF-8 | Lean | false | false | 595 | lean | /-
Copyright (c) 2022 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Tactic.Congr
import Lean.Elab.Tactic.Basic
namespace Lean.Elab.Tactic
namespace Lean.Elab.Tactic
@[builtinTactic Parser.Tactic.congr] def evalCongr : Tactic := fun stx =>
match stx with
| `(tactic| congr $[$n?]?) =>
let hugeDepth := 1000000
let depth := n?.map (·.getNat) |>.getD hugeDepth
liftMetaTactic fun mvarId => mvarId.congrN depth
| _ => throwUnsupportedSyntax
end Lean.Elab.Tactic
|
24c1f68cce7550f36f10419979e2431fd7b63563 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/analysis/convex/exposed.lean | fe68eb7cfffb27a92a6098c8566293a0036141c6 | [
"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 | 9,336 | lean | /-
Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies, Bhavik Mehta
-/
import analysis.convex.extreme
import analysis.convex.function
import analysis.normed_space.ordered
/-!
# Exposed sets
This file defines exposed sets and exposed points for sets in a real vector space.
An exposed subset of `A` is a subset of `A` that is the set of all maximal points of a functional
(a continuous linear map `E → 𝕜`) over `A`. By convention, `∅` is an exposed subset of all sets.
This allows for better functoriality of the definition (the intersection of two exposed subsets is
exposed, faces of a polytope form a bounded lattice).
This is an analytic notion of "being on the side of". It is stronger than being extreme (see
`is_exposed.is_extreme`), but weaker (for exposed points) than being a vertex.
An exposed set of `A` is sometimes called a "face of `A`", but we decided to reserve this
terminology to the more specific notion of a face of a polytope (sometimes hopefully soon out
on mathlib!).
## Main declarations
* `is_exposed 𝕜 A B`: States that `B` is an exposed set of `A` (in the literature, `A` is often
implicit).
* `is_exposed.is_extreme`: An exposed set is also extreme.
## References
See chapter 8 of [Barry Simon, *Convexity*][simon2011]
## TODO
Define intrinsic frontier/interior and prove the lemmas related to exposed sets and points.
Generalise to Locally Convex Topological Vector Spaces™
More not-yet-PRed stuff is available on the branch `sperner_again`.
-/
open_locale classical affine big_operators
open set
variables (𝕜 : Type*) {E : Type*} [normed_linear_ordered_field 𝕜] [normed_add_comm_group E]
[normed_space 𝕜 E] {l : E →L[𝕜] 𝕜} {A B C : set E} {X : finset E} {x : E}
/-- A set `B` is exposed with respect to `A` iff it maximizes some functional over `A` (and contains
all points maximizing it). Written `is_exposed 𝕜 A B`. -/
def is_exposed (A B : set E) : Prop :=
B.nonempty → ∃ l : E →L[𝕜] 𝕜, B = {x ∈ A | ∀ y ∈ A, l y ≤ l x}
variables {𝕜}
/-- A useful way to build exposed sets from intersecting `A` with halfspaces (modelled by an
inequality with a functional). -/
def continuous_linear_map.to_exposed (l : E →L[𝕜] 𝕜) (A : set E) : set E :=
{x ∈ A | ∀ y ∈ A, l y ≤ l x}
lemma continuous_linear_map.to_exposed.is_exposed : is_exposed 𝕜 A (l.to_exposed A) := λ h, ⟨l, rfl⟩
lemma is_exposed_empty : is_exposed 𝕜 A ∅ :=
λ ⟨x, hx⟩, by { exfalso, exact hx }
namespace is_exposed
protected lemma subset (hAB : is_exposed 𝕜 A B) : B ⊆ A :=
begin
rintro x hx,
obtain ⟨_, rfl⟩ := hAB ⟨x, hx⟩,
exact hx.1,
end
@[refl] protected lemma refl (A : set E) : is_exposed 𝕜 A A :=
λ ⟨w, hw⟩, ⟨0, subset.antisymm (λ x hx, ⟨hx, λ y hy, by exact le_refl 0⟩) (λ x hx, hx.1)⟩
protected lemma antisymm (hB : is_exposed 𝕜 A B) (hA : is_exposed 𝕜 B A) :
A = B :=
hA.subset.antisymm hB.subset
/- `is_exposed` is *not* transitive: Consider a (topologically) open cube with vertices
`A₀₀₀, ..., A₁₁₁` and add to it the triangle `A₀₀₀A₀₀₁A₀₁₀`. Then `A₀₀₁A₀₁₀` is an exposed subset
of `A₀₀₀A₀₀₁A₀₁₀` which is an exposed subset of the cube, but `A₀₀₁A₀₁₀` is not itself an exposed
subset of the cube. -/
protected lemma mono (hC : is_exposed 𝕜 A C) (hBA : B ⊆ A) (hCB : C ⊆ B) :
is_exposed 𝕜 B C :=
begin
rintro ⟨w, hw⟩,
obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩,
exact ⟨l, subset.antisymm (λ x hx, ⟨hCB hx, λ y hy, hx.2 y (hBA hy)⟩)
(λ x hx, ⟨hBA hx.1, λ y hy, (hw.2 y hy).trans (hx.2 w (hCB hw))⟩)⟩,
end
/-- If `B` is an exposed subset of `A`, then `B` is the intersection of `A` with some closed
halfspace. The converse is *not* true. It would require that the corresponding open halfspace
doesn't intersect `A`. -/
lemma eq_inter_halfspace (hAB : is_exposed 𝕜 A B) :
∃ l : E →L[𝕜] 𝕜, ∃ a, B = {x ∈ A | a ≤ l x} :=
begin
obtain hB | hB := B.eq_empty_or_nonempty,
{ refine ⟨0, 1, _⟩,
rw [hB, eq_comm, eq_empty_iff_forall_not_mem],
rintro x ⟨-, h⟩,
rw continuous_linear_map.zero_apply at h,
linarith },
obtain ⟨l, rfl⟩ := hAB hB,
obtain ⟨w, hw⟩ := hB,
exact ⟨l, l w, subset.antisymm (λ x hx, ⟨hx.1, hx.2 w hw.1⟩)
(λ x hx, ⟨hx.1, λ y hy, (hw.2 y hy).trans hx.2⟩)⟩,
end
protected lemma inter (hB : is_exposed 𝕜 A B) (hC : is_exposed 𝕜 A C) :
is_exposed 𝕜 A (B ∩ C) :=
begin
rintro ⟨w, hwB, hwC⟩,
obtain ⟨l₁, rfl⟩ := hB ⟨w, hwB⟩,
obtain ⟨l₂, rfl⟩ := hC ⟨w, hwC⟩,
refine ⟨l₁ + l₂, subset.antisymm _ _⟩,
{ rintro x ⟨⟨hxA, hxB⟩, ⟨-, hxC⟩⟩,
exact ⟨hxA, λ z hz, add_le_add (hxB z hz) (hxC z hz)⟩ },
rintro x ⟨hxA, hx⟩,
refine ⟨⟨hxA, λ y hy, _⟩, hxA, λ y hy, _⟩,
{ exact (add_le_add_iff_right (l₂ x)).1 ((add_le_add (hwB.2 y hy) (hwC.2 x hxA)).trans
(hx w hwB.1)) },
{ exact (add_le_add_iff_left (l₁ x)).1 (le_trans (add_le_add (hwB.2 x hxA) (hwC.2 y hy))
(hx w hwB.1)) }
end
lemma sInter {F : finset (set E)} (hF : F.nonempty)
(hAF : ∀ B ∈ F, is_exposed 𝕜 A B) :
is_exposed 𝕜 A (⋂₀ F) :=
begin
revert hF F,
refine finset.induction _ _,
{ rintro h,
exfalso,
exact empty_not_nonempty h },
rintro C F _ hF _ hCF,
rw [finset.coe_insert, sInter_insert],
obtain rfl | hFnemp := F.eq_empty_or_nonempty,
{ rw [finset.coe_empty, sInter_empty, inter_univ],
exact hCF C (finset.mem_singleton_self C) },
exact (hCF C (finset.mem_insert_self C F)).inter (hF hFnemp (λ B hB,
hCF B(finset.mem_insert_of_mem hB))),
end
lemma inter_left (hC : is_exposed 𝕜 A C) (hCB : C ⊆ B) :
is_exposed 𝕜 (A ∩ B) C :=
begin
rintro ⟨w, hw⟩,
obtain ⟨l, rfl⟩ := hC ⟨w, hw⟩,
exact ⟨l, subset.antisymm (λ x hx, ⟨⟨hx.1, hCB hx⟩, λ y hy, hx.2 y hy.1⟩)
(λ x ⟨⟨hxC, _⟩, hx⟩, ⟨hxC, λ y hy, (hw.2 y hy).trans (hx w ⟨hC.subset hw, hCB hw⟩)⟩)⟩,
end
lemma inter_right (hC : is_exposed 𝕜 B C) (hCA : C ⊆ A) :
is_exposed 𝕜 (A ∩ B) C :=
begin
rw inter_comm,
exact hC.inter_left hCA,
end
protected lemma is_extreme (hAB : is_exposed 𝕜 A B) :
is_extreme 𝕜 A B :=
begin
refine ⟨hAB.subset, λ x₁ hx₁A x₂ hx₂A x hxB hx, _⟩,
obtain ⟨l, rfl⟩ := hAB ⟨x, hxB⟩,
have hl : convex_on 𝕜 univ l := l.to_linear_map.convex_on convex_univ,
have hlx₁ := hxB.2 x₁ hx₁A,
have hlx₂ := hxB.2 x₂ hx₂A,
refine ⟨⟨hx₁A, λ y hy, _⟩, ⟨hx₂A, λ y hy, _⟩⟩,
{ rw hlx₁.antisymm (hl.le_left_of_right_le (mem_univ _) (mem_univ _) hx hlx₂),
exact hxB.2 y hy },
{ rw hlx₂.antisymm (hl.le_right_of_left_le (mem_univ _) (mem_univ _) hx hlx₁),
exact hxB.2 y hy }
end
protected lemma convex (hAB : is_exposed 𝕜 A B) (hA : convex 𝕜 A) :
convex 𝕜 B :=
begin
obtain rfl | hB := B.eq_empty_or_nonempty,
{ exact convex_empty },
obtain ⟨l, rfl⟩ := hAB hB,
exact λ x₁ x₂ hx₁ hx₂ a b ha hb hab, ⟨hA hx₁.1 hx₂.1 ha hb hab, λ y hy,
((l.to_linear_map.concave_on convex_univ).convex_ge _
⟨mem_univ _, hx₁.2 y hy⟩ ⟨mem_univ _, hx₂.2 y hy⟩ ha hb hab).2⟩,
end
protected lemma is_closed [order_closed_topology 𝕜] (hAB : is_exposed 𝕜 A B) (hA : is_closed A) :
is_closed B :=
begin
obtain ⟨l, a, rfl⟩ := hAB.eq_inter_halfspace,
exact hA.is_closed_le continuous_on_const l.continuous.continuous_on,
end
protected lemma is_compact [order_closed_topology 𝕜] (hAB : is_exposed 𝕜 A B) (hA : is_compact A) :
is_compact B :=
compact_of_is_closed_subset hA (hAB.is_closed hA.is_closed) hAB.subset
end is_exposed
variables (𝕜)
/-- A point is exposed with respect to `A` iff there exists an hyperplane whose intersection with
`A` is exactly that point. -/
def set.exposed_points (A : set E) :
set E :=
{x ∈ A | ∃ l : E →L[𝕜] 𝕜, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x)}
variables {𝕜}
lemma exposed_point_def :
x ∈ A.exposed_points 𝕜 ↔ x ∈ A ∧ ∃ l : E →L[𝕜] 𝕜, ∀ y ∈ A, l y ≤ l x ∧ (l x ≤ l y → y = x) :=
iff.rfl
lemma exposed_points_subset :
A.exposed_points 𝕜 ⊆ A :=
λ x hx, hx.1
@[simp] lemma exposed_points_empty :
(∅ : set E).exposed_points 𝕜 = ∅ :=
subset_empty_iff.1 exposed_points_subset
/-- Exposed points exactly correspond to exposed singletons. -/
lemma mem_exposed_points_iff_exposed_singleton :
x ∈ A.exposed_points 𝕜 ↔ is_exposed 𝕜 A {x} :=
begin
use λ ⟨hxA, l, hl⟩ h, ⟨l, eq.symm $ eq_singleton_iff_unique_mem.2 ⟨⟨hxA, λ y hy, (hl y hy).1⟩,
λ z hz, (hl z hz.1).2 (hz.2 x hxA)⟩⟩,
rintro h,
obtain ⟨l, hl⟩ := h ⟨x, mem_singleton _⟩,
rw [eq_comm, eq_singleton_iff_unique_mem] at hl,
exact ⟨hl.1.1, l, λ y hy, ⟨hl.1.2 y hy, λ hxy, hl.2 y ⟨hy, λ z hz, (hl.1.2 z hz).trans hxy⟩⟩⟩,
end
lemma exposed_points_subset_extreme_points :
A.exposed_points 𝕜 ⊆ A.extreme_points 𝕜 :=
λ x hx, mem_extreme_points_iff_extreme_singleton.2
(mem_exposed_points_iff_exposed_singleton.1 hx).is_extreme
|
ddb8f585b325630513e1cae81b9b8291601e1d80 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/ring_theory/norm.lean | 1a57f15de105abfe01901481f7081f04ed61c3ea | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,035 | 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 linear_algebra.matrix.charpoly.coeff
import linear_algebra.determinant
import ring_theory.power_basis
/-!
# Norm for (finite) ring extensions
Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`,
the determinant of the linear map given by multiplying by `s` gives information
about the roots of the minimal polynomial of `s` over `R`.
## Implementation notes
Typically, the norm is defined specifically for finite field extensions.
The current definition is as general as possible and the assumption that we have
fields or that the extension is finite is added to the lemmas as needed.
We only define the norm for left multiplication (`algebra.left_mul_matrix`,
i.e. `algebra.lmul_left`).
For now, the definitions assume `S` is commutative, so the choice doesn't
matter anyway.
See also `algebra.trace`, which is defined similarly as the trace of
`algebra.left_mul_matrix`.
## References
* https://en.wikipedia.org/wiki/Field_norm
-/
universes u v w
variables {R S T : Type*} [comm_ring R] [integral_domain R] [comm_ring S]
variables [algebra R S]
variables {K L F : Type*} [field K] [field L] [field F]
variables [algebra K L] [algebra L F] [algebra K F]
variables {ι : Type w} [fintype ι]
open finite_dimensional
open linear_map
open matrix
open_locale big_operators
open_locale matrix
namespace algebra
variables (R)
/-- The norm of an element `s` of an `R`-algebra is the determinant of `(*) s`. -/
noncomputable def norm : S →* R :=
linear_map.det.comp (lmul R S).to_ring_hom.to_monoid_hom
lemma norm_apply (x : S) : norm R x = linear_map.det (lmul R S x) := rfl
lemma norm_eq_one_of_not_exists_basis
(h : ¬ ∃ (s : finset S), nonempty (basis s R S)) (x : S) : norm R x = 1 :=
by { rw [norm_apply, linear_map.det], split_ifs with h, refl }
variables {R}
-- Can't be a `simp` lemma because it depends on a choice of basis
lemma norm_eq_matrix_det [decidable_eq ι] (b : basis ι R S) (s : S) :
norm R s = matrix.det (algebra.left_mul_matrix b s) :=
by rw [norm_apply, ← linear_map.det_to_matrix b, to_matrix_lmul_eq]
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`. -/
lemma norm_algebra_map_of_basis (b : basis ι R S) (x : R) :
norm R (algebra_map R S x) = x ^ fintype.card ι :=
begin
haveI := classical.dec_eq ι,
rw [norm_apply, ← det_to_matrix b, lmul_algebra_map],
convert @det_diagonal _ _ _ _ _ (λ (i : ι), x),
{ ext i j, rw [to_matrix_lsmul, matrix.diagonal] },
{ rw [finset.prod_const, finset.card_univ] }
end
/-- If `x` is in the base field `K`, then the norm is `x ^ [L : K]`.
(If `L` is not finite-dimensional over `K`, then `norm = 1 = x ^ 0 = x ^ (finrank L K)`.)
-/
@[simp]
lemma norm_algebra_map (x : K) : norm K (algebra_map K L x) = x ^ finrank K L :=
begin
by_cases H : ∃ (s : finset L), nonempty (basis s K L),
{ rw [norm_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] },
{ rw [norm_eq_one_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis, pow_zero],
rintros ⟨s, ⟨b⟩⟩,
exact H ⟨s, ⟨b⟩⟩ },
end
section eq_prod_roots
lemma norm_gen_eq_prod_roots [algebra K S] (pb : power_basis K S)
(hf : (minpoly K pb.gen).splits (algebra_map K F)) :
algebra_map K F (norm K pb.gen) =
((minpoly K pb.gen).map (algebra_map K F)).roots.prod :=
begin
-- Write the LHS as the 0'th coefficient of `minpoly K pb.gen`
rw [norm_eq_matrix_det pb.basis, det_eq_sign_charpoly_coeff, charpoly_left_mul_matrix,
ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one,
← polynomial.coeff_map, fintype.card_fin],
-- Rewrite `minpoly K pb.gen` as a product over the roots.
conv_lhs { rw polynomial.eq_prod_roots_of_splits hf },
rw [polynomial.coeff_C_mul, polynomial.coeff_zero_multiset_prod, multiset.map_map,
(minpoly.monic pb.is_integral_gen).leading_coeff, ring_hom.map_one, one_mul],
-- Incorporate the `-1` from the `charpoly` back into the product.
rw [← multiset.prod_repeat (-1 : F), ← pb.nat_degree_minpoly,
polynomial.nat_degree_eq_card_roots hf, ← multiset.map_const, ← multiset.prod_map_mul],
-- And conclude that both sides are the same.
congr, convert multiset.map_id _, ext f, simp
end
end eq_prod_roots
section eq_zero_iff
lemma norm_eq_zero_iff_of_basis [integral_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x = 0 ↔ x = 0 :=
begin
have hι : nonempty ι := b.index_nonempty,
letI := classical.dec_eq ι,
rw algebra.norm_eq_matrix_det b,
split,
{ rw ← matrix.exists_mul_vec_eq_zero_iff,
rintros ⟨v, v_ne, hv⟩,
rw [← b.equiv_fun.apply_symm_apply v, b.equiv_fun_symm_apply, b.equiv_fun_apply,
algebra.left_mul_matrix_mul_vec_repr] at hv,
refine (mul_eq_zero.mp (b.ext_elem $ λ i, _)).resolve_right (show ∑ i, v i • b i ≠ 0, from _),
{ simpa only [linear_equiv.map_zero, pi.zero_apply] using congr_fun hv i },
{ contrapose! v_ne with sum_eq,
apply b.equiv_fun.symm.injective,
rw [b.equiv_fun_symm_apply, sum_eq, linear_equiv.map_zero] } },
{ rintro rfl,
rw [alg_hom.map_zero, matrix.det_zero hι] },
end
lemma norm_ne_zero_iff_of_basis [integral_domain S] (b : basis ι R S) {x : S} :
algebra.norm R x ≠ 0 ↔ x ≠ 0 :=
not_iff_not.mpr (algebra.norm_eq_zero_iff_of_basis b)
/-- See also `algebra.norm_eq_zero_iff'` if you already have rewritten with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff [finite_dimensional K L] {x : L} :
algebra.norm K x = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
/-- This is `algebra.norm_eq_zero_iff` composed with `algebra.norm_apply`. -/
@[simp]
lemma norm_eq_zero_iff' [finite_dimensional K L] {x : L} :
linear_map.det (algebra.lmul K L x) = 0 ↔ x = 0 :=
algebra.norm_eq_zero_iff_of_basis (basis.of_vector_space K L)
end eq_zero_iff
end algebra
|
fd1b2cf7db030f9e7bcfa8abe29ee5ea048f4c90 | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/analysis/analytic/linear.lean | 7c6dcec3c3f063999f3cb760cd3202bef09dc439 | [
"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 | 1,925 | lean | /-
Copyright (c) 2021 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury G. Kudryashov
-/
import analysis.analytic.basic
/-!
# Linear functions are analytic
In this file we prove that a `continuous_linear_map` defines an analytic function with
the formal power series `f x = f a + f (x - a)`.
-/
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
open_locale topological_space classical big_operators nnreal ennreal
open set filter asymptotics
noncomputable theory
namespace continuous_linear_map
/-- Formal power series of a continuous linear map `f : E →L[𝕜] F` at `x : E`:
`f y = f x + f (y - x)`. -/
@[simp] def fpower_series (f : E →L[𝕜] F) (x : E) : formal_multilinear_series 𝕜 E F
| 0 := continuous_multilinear_map.curry0 𝕜 _ (f x)
| 1 := (continuous_multilinear_curry_fin1 𝕜 _ _).symm f
| _ := 0
@[simp] lemma fpower_series_apply_add_two (f : E →L[𝕜] F) (x : E) (n : ℕ) :
f.fpower_series x (n + 2) = 0 := rfl
@[simp] lemma fpower_series_radius (f : E →L[𝕜] F) (x : E) : (f.fpower_series x).radius = ∞ :=
(f.fpower_series x).radius_eq_top_of_forall_image_add_eq_zero 2 $ λ n, rfl
protected theorem has_fpower_series_on_ball (f : E →L[𝕜] F) (x : E) :
has_fpower_series_on_ball f (f.fpower_series x) x ∞ :=
{ r_le := by simp,
r_pos := ennreal.coe_lt_top,
has_sum := λ y _, (has_sum_nat_add_iff' 2).1 $
by simp [finset.sum_range_succ, ← sub_sub, has_sum_zero] }
protected theorem has_fpower_series_at (f : E →L[𝕜] F) (x : E) :
has_fpower_series_at f (f.fpower_series x) x :=
⟨∞, f.has_fpower_series_on_ball x⟩
protected theorem analytic_at (f : E →L[𝕜] F) (x : E) : analytic_at 𝕜 f x :=
(f.has_fpower_series_at x).analytic_at
end continuous_linear_map
|
7703b90467929d3533142e78bdaaf83abb537898 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/topology/compacts.lean | 1d31302587df07a45a334a338a8743c866bb8f10 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,184 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import topology.homeomorph
/-!
# Compact sets
## Summary
We define the subtype of compact sets in a topological space.
## Main Definitions
- `closeds α` is the type of closed subsets of a topological space `α`.
- `compacts α` is the type of compact subsets of a topological space `α`.
- `nonempty_compacts α` is the type of non-empty compact subsets.
- `positive_compacts α` is the type of compact subsets with non-empty interior.
-/
open set
variables (α : Type*) {β : Type*} [topological_space α] [topological_space β]
namespace topological_space
/-- The type of closed subsets of a topological space. -/
def closeds := {s : set α // is_closed s}
/-- The type of closed subsets is inhabited, with default element the empty set. -/
instance : inhabited (closeds α) := ⟨⟨∅, is_closed_empty ⟩⟩
/-- The compact sets of a topological space. See also `nonempty_compacts`. -/
def compacts : Type* := { s : set α // is_compact s }
/-- The type of non-empty compact subsets of a topological space. The
non-emptiness will be useful in metric spaces, as we will be able to put
a distance (and not merely an edistance) on this space. -/
def nonempty_compacts := {s : set α // s.nonempty ∧ is_compact s}
/-- In an inhabited space, the type of nonempty compact subsets is also inhabited, with
default element the singleton set containing the default element. -/
instance nonempty_compacts_inhabited [inhabited α] : inhabited (nonempty_compacts α) :=
⟨⟨{default α}, singleton_nonempty (default α), is_compact_singleton ⟩⟩
/-- The compact sets with nonempty interior of a topological space. See also `compacts` and
`nonempty_compacts`. -/
@[nolint has_inhabited_instance]
def positive_compacts: Type* := { s : set α // is_compact s ∧ (interior s).nonempty }
/-- In a nonempty compact space, `set.univ` is a member of `positive_compacts`, the compact sets
with nonempty interior. -/
def positive_compacts_univ {α : Type*} [topological_space α] [compact_space α] [nonempty α] :
positive_compacts α :=
⟨set.univ, compact_univ, by simp⟩
variables {α}
namespace compacts
instance : semilattice_sup_bot (compacts α) :=
subtype.semilattice_sup_bot is_compact_empty (λ K₁ K₂, is_compact.union)
instance [t2_space α]: semilattice_inf_bot (compacts α) :=
subtype.semilattice_inf_bot is_compact_empty (λ K₁ K₂, is_compact.inter)
instance [t2_space α] : lattice (compacts α) :=
subtype.lattice (λ K₁ K₂, is_compact.union) (λ K₁ K₂, is_compact.inter)
@[simp] lemma bot_val : (⊥ : compacts α).1 = ∅ := rfl
@[simp] lemma sup_val {K₁ K₂ : compacts α} : (K₁ ⊔ K₂).1 = K₁.1 ∪ K₂.1 := rfl
@[ext] protected lemma ext {K₁ K₂ : compacts α} (h : K₁.1 = K₂.1) : K₁ = K₂ :=
subtype.eq h
@[simp] lemma finset_sup_val {β} {K : β → compacts α} {s : finset β} :
(s.sup K).1 = s.sup (λ x, (K x).1) :=
finset.sup_coe _ _
instance : inhabited (compacts α) := ⟨⊥⟩
/-- The image of a compact set under a continuous function. -/
protected def map (f : α → β) (hf : continuous f) (K : compacts α) : compacts β :=
⟨f '' K.1, K.2.image hf⟩
@[simp] lemma map_val {f : α → β} (hf : continuous f) (K : compacts α) :
(K.map f hf).1 = f '' K.1 := rfl
/-- A homeomorphism induces an equivalence on compact sets, by taking the image. -/
@[simp] protected def equiv (f : α ≃ₜ β) : compacts α ≃ compacts β :=
{ to_fun := compacts.map f f.continuous,
inv_fun := compacts.map _ f.symm.continuous,
left_inv := by { intro K, ext1, simp only [map_val, ← image_comp, f.symm_comp_self, image_id] },
right_inv := by { intro K, ext1,
simp only [map_val, ← image_comp, f.self_comp_symm, image_id] } }
/-- The image of a compact set under a homeomorphism can also be expressed as a preimage. -/
lemma equiv_to_fun_val (f : α ≃ₜ β) (K : compacts α) :
(compacts.equiv f K).1 = f.symm ⁻¹' K.1 :=
congr_fun (image_eq_preimage_of_inverse f.left_inv f.right_inv) K.1
end compacts
section nonempty_compacts
open topological_space set
variable {α}
instance nonempty_compacts.to_compact_space {p : nonempty_compacts α} : compact_space p.val :=
⟨is_compact_iff_is_compact_univ.1 p.property.2⟩
instance nonempty_compacts.to_nonempty {p : nonempty_compacts α} : nonempty p.val :=
p.property.1.to_subtype
/-- Associate to a nonempty compact subset the corresponding closed subset -/
def nonempty_compacts.to_closeds [t2_space α] : nonempty_compacts α → closeds α :=
set.inclusion $ λ s hs, hs.2.is_closed
end nonempty_compacts
section positive_compacts
variable (α)
/-- In a nonempty locally compact space, there exists a compact set with nonempty interior. -/
instance nonempty_positive_compacts [locally_compact_space α] [nonempty α] :
nonempty (positive_compacts α) :=
begin
inhabit α,
rcases exists_compact_subset is_open_univ (mem_univ (default α)) with ⟨K, hK⟩,
exact ⟨⟨K, hK.1, ⟨_, hK.2.1⟩⟩⟩
end
end positive_compacts
end topological_space
|
be55c84e26513e2848caec74759543ce7235fa95 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/measure_theory/measure_space.lean | 64a4840ff2d2e3125dde98ddf9a7f6afc3430a57 | [
"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 | 35,657 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.set.lattice data.set.finite
import topology.instances.ennreal
measure_theory.outer_measure
/-!
# Measure spaces
Measures are restricted to a measurable space (associated by the type class `measurable_space`).
This allows us to prove equalities between measures by restricting to a generating set of the
measurable space.
On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`)
is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is
somehow well-behaved on non-measurable sets.
This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be
a complete measure.
-/
noncomputable theory
open classical set lattice filter finset function
open_locale classical topological_space
universes u v w x
namespace measure_theory
section of_measurable
parameters {α : Type*} [measurable_space α]
parameters (m : Π (s : set α), is_measurable s → ennreal)
parameters (m0 : m ∅ is_measurable.empty = 0)
include m0
/-- Measure projection which is ∞ for non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, m s h
lemma measure'_eq {s} (h : is_measurable s) : measure' s = m s h :=
by simp [measure', h]
lemma measure'_empty : measure' ∅ = 0 :=
(measure'_eq is_measurable.empty).trans m0
lemma measure'_Union_nat
{f : ℕ → set α}
(hm : ∀i, is_measurable (f i))
(mU : m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i))) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
(measure'_eq _).trans $ mU.trans $
by congr; funext i; rw measure'_eq
/-- outer measure of a measure -/
def outer_measure' : outer_measure α :=
outer_measure.of_function measure' measure'_empty
lemma measure'_Union_le_tsum_nat'
(mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
m (⋃i, f i) (is_measurable.Union hm) ≤ (∑i, m (f i) (hm i)))
(s : ℕ → set α) :
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
begin
by_cases h : ∀i, is_measurable (s i),
{ rw [measure'_eq _ _ (is_measurable.Union h),
congr_arg tsum _], {apply mU h},
funext i, apply measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) }
end
parameter (mU : ∀ {f : ℕ → set α} (hm : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union hm) = (∑i, m (f i) (hm i)))
include mU
lemma measure'_Union
{β} [encodable β] {f : β → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
measure' (⋃i, f i) = (∑i, measure' (f i)) :=
begin
rw [encodable.Union_decode2, outer_measure.Union_aux],
{ exact measure'_Union_nat _ _
(λ n, encodable.Union_decode2_cases is_measurable.empty hm)
(mU _ (measurable_space.Union_decode2_disjoint_on hd)) },
{ apply measure'_empty },
end
lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
measure' (s₁ ∪ s₂) = measure' s₁ + measure' s₂ :=
begin
rw [union_eq_Union, measure'_Union _ _ @mU
(pairwise_disjoint_on_bool.2 hd) (bool.forall_bool.2 ⟨h₂, h₁⟩),
tsum_fintype],
change _+_ = _, simp
end
lemma measure'_mono {s₁ s₂ : set α} (h₁ : is_measurable s₁) (hs : s₁ ⊆ s₂) :
measure' s₁ ≤ measure' s₂ :=
le_infi $ λ h₂, begin
have := measure'_union _ _ @mU disjoint_diff h₁ (h₂.diff h₁),
rw union_diff_cancel hs at this,
rw ← measure'_eq m m0 _,
exact le_iff_exists_add.2 ⟨_, this⟩
end
lemma measure'_Union_le_tsum_nat : ∀ (s : ℕ → set α),
measure' (⋃i, s i) ≤ (∑i, measure' (s i)) :=
measure'_Union_le_tsum_nat' $ λ f h, begin
simp [Union_disjointed.symm] {single_pass := tt},
rw [mU (is_measurable.disjointed h) disjoint_disjointed],
refine ennreal.tsum_le_tsum (λ i, _),
rw [← measure'_eq m m0, ← measure'_eq m m0],
exact measure'_mono _ _ @mU (is_measurable.disjointed h _) (inter_subset_left _ _)
end
lemma outer_measure'_eq {s : set α} (hs : is_measurable s) :
outer_measure' s = m s hs :=
by rw ← measure'_eq m m0 hs; exact
(le_antisymm (outer_measure.of_function_le _ _ _) $
le_infi $ λ f, le_infi $ λ hf,
le_trans (measure'_mono _ _ @mU hs hf) $
measure'_Union_le_tsum_nat _ _ @mU _)
lemma outer_measure'_eq_measure' {s : set α} (hs : is_measurable s) :
outer_measure' s = measure' s :=
by rw [measure'_eq m m0 hs, outer_measure'_eq m m0 @mU hs]
end of_measurable
namespace outer_measure
variables {α : Type*} [measurable_space α] (m : outer_measure α)
def trim : outer_measure α :=
outer_measure' (λ s _, m s) m.empty
theorem trim_ge : m ≤ m.trim :=
λ s, le_infi $ λ f, le_infi $ λ hs,
le_trans (m.mono hs) $ le_trans (m.Union_nat f) $
ennreal.tsum_le_tsum $ λ i, le_infi $ λ hf, le_refl _
theorem trim_eq {s : set α} (hs : is_measurable s) : m.trim s = m s :=
le_antisymm (le_trans (of_function_le _ _ _) (infi_le _ hs)) (trim_ge _ _)
theorem trim_congr {m₁ m₂ : outer_measure α}
(H : ∀ {s : set α}, is_measurable s → m₁ s = m₂ s) :
m₁.trim = m₂.trim :=
by unfold trim; congr; funext s hs; exact H hs
theorem trim_le_trim {m₁ m₂ : outer_measure α} (H : m₁ ≤ m₂) : m₁.trim ≤ m₂.trim :=
λ s, infi_le_infi $ λ f, infi_le_infi $ λ hs,
ennreal.tsum_le_tsum $ λ b, infi_le_infi $ λ hf, H _
theorem le_trim_iff {m₁ m₂ : outer_measure α} : m₁ ≤ m₂.trim ↔
∀ s, is_measurable s → m₁ s ≤ m₂ s :=
le_of_function.trans $ forall_congr $ λ s, le_infi_iff
theorem trim_eq_infi (s : set α) : m.trim s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), m t :=
begin
refine le_antisymm
(le_infi $ λ t, le_infi $ λ st, le_infi $ λ ht, _)
(le_infi $ λ f, le_infi $ λ hf, _),
{ rw ← trim_eq m ht, exact (trim m).mono st },
{ by_cases h : ∀i, is_measurable (f i),
{ refine infi_le_of_le _ (infi_le_of_le hf $
infi_le_of_le (is_measurable.Union h) _),
rw congr_arg tsum _, {exact m.Union_nat _},
funext i, exact measure'_eq _ _ (h i) },
{ cases not_forall.1 h with i hi,
exact le_trans (le_infi $ λ h, hi.elim h) (ennreal.le_tsum i) } }
end
theorem trim_eq_infi' (s : set α) : m.trim s = ⨅ t : {t // s ⊆ t ∧ is_measurable t}, m t.1 :=
by simp [infi_subtype, infi_and, trim_eq_infi]
theorem trim_trim (m : outer_measure α) : m.trim.trim = m.trim :=
le_antisymm (le_trim_iff.2 $ λ s hs, by simp [trim_eq _ hs, le_refl]) (trim_ge _)
theorem trim_zero : (0 : outer_measure α).trim = 0 :=
ext $ λ s, le_antisymm
(le_trans ((trim 0).mono (subset_univ s)) $
le_of_eq $ trim_eq _ is_measurable.univ)
(zero_le _)
theorem trim_add (m₁ m₂ : outer_measure α) : (m₁ + m₂).trim = m₁.trim + m₂.trim :=
ext $ λ s, begin
simp [trim_eq_infi'],
rw ennreal.infi_add_infi,
rintro ⟨t₁, st₁, ht₁⟩ ⟨t₂, st₂, ht₂⟩,
exact ⟨⟨_, subset_inter_iff.2 ⟨st₁, st₂⟩, ht₁.inter ht₂⟩,
add_le_add'
(m₁.mono' (inter_subset_left _ _))
(m₂.mono' (inter_subset_right _ _))⟩,
end
theorem trim_sum_ge {ι} (m : ι → outer_measure α) : sum (λ i, (m i).trim) ≤ (sum m).trim :=
λ s, by simp [trim_eq_infi]; exact
λ t st ht, ennreal.tsum_le_tsum (λ i,
infi_le_of_le t $ infi_le_of_le st $ infi_le _ ht)
end outer_measure
structure measure (α : Type*) [measurable_space α] extends outer_measure α :=
(m_Union {f : ℕ → set α} :
(∀i, is_measurable (f i)) → pairwise (disjoint on f) →
measure_of (⋃i, f i) = (∑i, measure_of (f i)))
(trimmed : to_outer_measure.trim = to_outer_measure)
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
instance measure.has_coe_to_fun {α} [measurable_space α] : has_coe_to_fun (measure α) :=
⟨λ _, set α → ennreal, λ m, m.to_outer_measure⟩
namespace measure
def of_measurable {α} [measurable_space α]
(m : Π (s : set α), is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))) :
measure α :=
{ m_Union := λ f hf hd,
show outer_measure' m m0 (Union f) =
∑ i, outer_measure' m m0 (f i), begin
rw [outer_measure'_eq m m0 @mU, mU hf hd],
congr, funext n, rw outer_measure'_eq m m0 @mU
end,
trimmed :=
show (outer_measure' m m0).trim = outer_measure' m m0, begin
unfold outer_measure.trim,
congr, funext s hs,
exact outer_measure'_eq m m0 @mU hs
end,
..outer_measure' m m0 }
lemma of_measurable_apply {α} [measurable_space α]
{m : Π (s : set α), is_measurable s → ennreal}
{m0 : m ∅ is_measurable.empty = 0}
{mU : ∀ {f : ℕ → set α} (h : ∀i, is_measurable (f i)),
pairwise (disjoint on f) →
m (⋃i, f i) (is_measurable.Union h) = (∑i, m (f i) (h i))}
(s : set α) (hs : is_measurable s) :
of_measurable m m0 @mU s = m s hs :=
outer_measure'_eq m m0 @mU hs
@[ext] lemma ext {α} [measurable_space α] :
∀ {μ₁ μ₂ : measure α}, (∀s, is_measurable s → μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, u₁, h₁⟩ ⟨m₂, u₂, h₂⟩ h := by congr; rw [← h₁, ← h₂];
exact outer_measure.trim_congr h
end measure
section
variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure α} {s s₁ s₂ : set α}
@[simp] lemma to_outer_measure_apply (s) : μ.to_outer_measure s = μ s := rfl
lemma measure_eq_trim (s) : μ s = μ.to_outer_measure.trim s :=
by rw μ.trimmed; refl
lemma measure_eq_infi (s) : μ s = ⨅ t (st : s ⊆ t) (ht : is_measurable t), μ t :=
by rw [measure_eq_trim, outer_measure.trim_eq_infi]; refl
lemma measure_eq_outer_measure' :
μ s = outer_measure' (λ s _, μ s) μ.empty s :=
measure_eq_trim _
lemma to_outer_measure_eq_outer_measure' :
μ.to_outer_measure = outer_measure' (λ s _, μ s) μ.empty :=
μ.trimmed.symm
lemma measure_eq_measure' (hs : is_measurable s) :
μ s = measure' (λ s _, μ s) μ.empty s :=
by rw [measure_eq_outer_measure',
outer_measure'_eq_measure' (λ s _, μ s) _ μ.m_Union hs]
@[simp] lemma measure_empty : μ ∅ = 0 := μ.empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ s₁ ≤ μ s₂ := μ.mono h
lemma measure_mono_null (h : s₁ ⊆ s₂) (h₂ : μ s₂ = 0) : μ s₁ = 0 :=
by rw [← le_zero_iff_eq, ← h₂]; exact measure_mono h
lemma exists_is_measurable_superset_of_measure_eq_zero {s : set α} (h : μ s = 0) :
∃t, s ⊆ t ∧ is_measurable t ∧ μ t = 0 :=
begin
rw [measure_eq_infi] at h,
have h := (infi_eq_bot _).1 h,
choose t ht using show ∀n:ℕ, ∃t, s ⊆ t ∧ is_measurable t ∧ μ t < n⁻¹,
{ assume n,
have : (0 : ennreal) < n⁻¹ :=
(zero_lt_iff_ne_zero.2 $ ennreal.inv_ne_zero.2 $ ennreal.nat_ne_top _),
rcases h _ this with ⟨t, ht⟩,
use [t],
simpa [(>), infi_lt_iff, -add_comm] using ht },
refine ⟨⋂n, t n, subset_Inter (λn, (ht n).1), is_measurable.Inter (λn, (ht n).2.1), _⟩,
refine eq_of_le_of_forall_le_of_dense bot_le (assume r hr, _),
rcases ennreal.exists_inv_nat_lt (ne_of_gt hr) with ⟨n, hn⟩,
calc μ (⋂n, t n) ≤ μ (t n) : measure_mono (Inter_subset _ _)
... ≤ n⁻¹ : le_of_lt (ht n).2.2
... ≤ r : le_of_lt hn
end
theorem measure_Union_le {β} [encodable β] (s : β → set α) : μ (⋃i, s i) ≤ (∑i, μ (s i)) :=
μ.to_outer_measure.Union _
lemma measure_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, μ (s i) = 0) → μ (⋃i, s i) = 0 :=
μ.to_outer_measure.Union_null
theorem measure_union_le (s₁ s₂ : set α) : μ (s₁ ∪ s₂) ≤ μ s₁ + μ s₂ :=
μ.to_outer_measure.union _ _
lemma measure_union_null {s₁ s₂ : set α} : μ s₁ = 0 → μ s₂ = 0 → μ (s₁ ∪ s₂) = 0 :=
μ.to_outer_measure.union_null
lemma measure_Union {β} [encodable β] {f : β → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ (⋃i, f i) = (∑i, μ (f i)) :=
by rw [measure_eq_measure' (is_measurable.Union h),
measure'_Union (λ s _, μ s) _ μ.m_Union hn h];
simp [measure_eq_measure', h]
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ (s₁ ∪ s₂) = μ s₁ + μ s₂ :=
by rw [measure_eq_measure' (h₁.union h₂),
measure'_union (λ s _, μ s) _ μ.m_Union hd h₁ h₂];
simp [measure_eq_measure', h₁, h₂]
lemma measure_bUnion {s : set β} {f : β → set α} (hs : countable s)
(hd : pairwise_on s (disjoint on f)) (h : ∀b∈s, is_measurable (f b)) :
μ (⋃b∈s, f b) = ∑p:s, μ (f p.1) :=
begin
haveI := hs.to_encodable,
rw [← measure_Union, bUnion_eq_Union],
{ rintro ⟨i, hi⟩ ⟨j, hj⟩ ij x ⟨h₁, h₂⟩,
exact hd i hi j hj (mt subtype.eq' ij:_) ⟨h₁, h₂⟩ },
{ simpa }
end
lemma measure_sUnion {S : set (set α)} (hs : countable S)
(hd : pairwise_on S disjoint) (h : ∀s∈S, is_measurable s) :
μ (⋃₀ S) = ∑s:S, μ s.1 :=
by rw [sUnion_eq_bUnion, measure_bUnion hs hd h]
lemma measure_diff {s₁ s₂ : set α} (h : s₂ ⊆ s₁)
(h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ s₂ < ⊤) : μ (s₁ \ s₂) = μ s₁ - μ s₂ :=
begin
refine (ennreal.add_sub_self' h_fin).symm.trans _,
rw [← measure_union disjoint_diff h₂ (h₁.diff h₂), union_diff_cancel h]
end
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ (⋃i, s i) = (⨆i, μ (s i)) :=
begin
refine le_antisymm _ (supr_le $ λ i, measure_mono $ subset_Union _ _),
rw [← Union_disjointed,
measure_Union disjoint_disjointed (is_measurable.disjointed h),
ennreal.tsum_eq_supr_nat],
refine supr_le (λ n, _),
cases n, {apply zero_le _},
suffices : sum (finset.range n.succ) (λ i, μ (disjointed s i)) = μ (s n),
{ rw this, exact le_supr _ n },
rw [← Union_disjointed_of_mono hs, measure_Union, tsum_eq_sum],
{ apply sum_congr rfl, intros i hi,
simp [finset.mem_range.1 hi] },
{ intros i hi, simp [mt finset.mem_range.2 hi] },
{ rintro i j ij x ⟨⟨_, ⟨_, rfl⟩, h₁⟩, ⟨_, ⟨_, rfl⟩, h₂⟩⟩,
exact disjoint_disjointed i j ij ⟨h₁, h₂⟩ },
{ intro i,
by_cases h' : i < n.succ; simp [h', is_measurable.empty],
apply is_measurable.disjointed h }
end
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i)
(hfin : ∃i, μ (s i) < ⊤) :
μ (⋂i, s i) = (⨅i, μ (s i)) :=
begin
rcases hfin with ⟨k, hk⟩,
rw [← ennreal.sub_sub_cancel (by exact hk) (infi_le _ k),
ennreal.sub_infi,
← ennreal.sub_sub_cancel (by exact hk) (measure_mono (Inter_subset _ k)),
← measure_diff (Inter_subset _ k) (h k) (is_measurable.Inter h)
(lt_of_le_of_lt (measure_mono (Inter_subset _ k)) hk),
diff_Inter, measure_Union_eq_supr_nat],
{ congr, funext i,
cases le_total k i with ik ik,
{ exact measure_diff (hs _ _ ik) (h k) (h i)
(lt_of_le_of_lt (measure_mono (hs _ _ ik)) hk) },
{ rw [diff_eq_empty.2 (hs _ _ ik), measure_empty,
ennreal.sub_eq_zero_of_le (measure_mono (hs _ _ ik))] } },
{ exact λ i, (h k).diff (h i) },
{ exact λ i j ij, diff_subset_diff_right (hs _ _ ij) }
end
lemma measure_eq_inter_diff {μ : measure α} {s t : set α}
(hs : is_measurable s) (ht : is_measurable t) :
μ s = μ (s ∩ t) + μ (s \ t) :=
have hd : disjoint (s ∩ t) (s \ t) := assume a ⟨⟨_, hs⟩, _, hns⟩, hns hs ,
by rw [← measure_union hd (hs.inter ht) (hs.diff ht), inter_union_diff s t]
lemma tendsto_measure_Union {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : monotone s) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋃n, s n))) :=
begin
rw measure_Union_eq_supr_nat hs hm,
exact tendsto_at_top_supr_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm $ hnm)
end
lemma tendsto_measure_Inter {μ : measure α} {s : ℕ → set α}
(hs : ∀n, is_measurable (s n)) (hm : ∀n m, n ≤ m → s m ⊆ s n) (hf : ∃i, μ (s i) < ⊤) :
tendsto (μ ∘ s) at_top (𝓝 (μ (⋂n, s n))) :=
begin
rw measure_Inter_eq_infi_nat hs hm hf,
exact tendsto_at_top_infi_nat (μ ∘ s) (assume n m hnm, measure_mono $ hm _ _ $ hnm),
end
end
def outer_measure.to_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure α :=
measure.of_measurable (λ s _, m s) m.empty
(λ f hf hd, m.Union_eq_of_caratheodory (λ i, h _ (hf i)) hd)
lemma le_to_outer_measure_caratheodory {α} [ms : measurable_space α]
(μ : measure α) : ms ≤ μ.to_outer_measure.caratheodory :=
begin
assume s hs,
rw to_outer_measure_eq_outer_measure',
refine outer_measure.caratheodory_is_measurable (λ t, le_infi $ λ ht, _),
rw [← measure_eq_measure' (ht.inter hs),
← measure_eq_measure' (ht.diff hs),
← measure_union _ (ht.inter hs) (ht.diff hs),
inter_union_diff],
exact le_refl _,
exact λ x ⟨⟨_, h₁⟩, _, h₂⟩, h₂ h₁
end
lemma to_measure_to_outer_measure {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory) :
(m.to_measure h).to_outer_measure = m.trim := rfl
@[simp] lemma to_measure_apply {α} (m : outer_measure α)
[ms : measurable_space α] (h : ms ≤ m.caratheodory)
{s : set α} (hs : is_measurable s) :
m.to_measure h s = m s := m.trim_eq hs
lemma to_outer_measure_to_measure {α : Type*} [ms : measurable_space α] {μ : measure α} :
μ.to_outer_measure.to_measure (le_to_outer_measure_caratheodory _) = μ :=
measure.ext $ λ s, μ.to_outer_measure.trim_eq
namespace measure
variables {α : Type*} {β : Type*} {γ : Type*}
[measurable_space α] [measurable_space β] [measurable_space γ]
instance : has_zero (measure α) :=
⟨{ to_outer_measure := 0,
m_Union := λ f hf hd, tsum_zero.symm,
trimmed := outer_measure.trim_zero }⟩
@[simp] theorem zero_to_outer_measure :
(0 : measure α).to_outer_measure = 0 := rfl
@[simp] theorem zero_apply (s : set α) : (0 : measure α) s = 0 := rfl
instance : inhabited (measure α) := ⟨0⟩
instance : has_add (measure α) :=
⟨λμ₁ μ₂, {
to_outer_measure := μ₁.to_outer_measure + μ₂.to_outer_measure,
m_Union := λs hs hd,
show μ₁ (⋃ i, s i) + μ₂ (⋃ i, s i) = ∑ i, μ₁ (s i) + μ₂ (s i),
by rw [ennreal.tsum_add, measure_Union hd hs, measure_Union hd hs],
trimmed := by rw [outer_measure.trim_add, μ₁.trimmed, μ₂.trimmed] }⟩
@[simp] theorem add_to_outer_measure (μ₁ μ₂ : measure α) :
(μ₁ + μ₂).to_outer_measure = μ₁.to_outer_measure + μ₂.to_outer_measure := rfl
@[simp] theorem add_apply (μ₁ μ₂ : measure α) (s : set α) :
(μ₁ + μ₂) s = μ₁ s + μ₂ s := rfl
instance add_comm_monoid : add_comm_monoid (measure α) :=
{ zero := 0,
add := (+),
add_assoc := assume a b c, ext $ assume s hs, add_assoc _ _ _,
add_comm := assume a b, ext $ assume s hs, add_comm _ _,
zero_add := assume a, ext $ assume s hs, zero_add _,
add_zero := assume a, ext $ assume s hs, add_zero _ }
instance : partial_order (measure α) :=
{ le := λm₁ m₂, ∀ s, is_measurable s → m₁ s ≤ m₂ s,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, ext $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
theorem le_iff {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, is_measurable s → μ₁ s ≤ μ₂ s := iff.rfl
theorem to_outer_measure_le {μ₁ μ₂ : measure α} :
μ₁.to_outer_measure ≤ μ₂.to_outer_measure ↔ μ₁ ≤ μ₂ :=
by rw [← μ₂.trimmed, outer_measure.le_trim_iff]; refl
theorem le_iff' {μ₁ μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ s, μ₁ s ≤ μ₂ s :=
to_outer_measure_le.symm
section
variables {m : set (measure α)} {μ : measure α}
lemma Inf_caratheodory (s : set α) (hs : is_measurable s) :
(Inf (measure.to_outer_measure '' m)).caratheodory.is_measurable s :=
begin
rw [outer_measure.Inf_eq_of_function_Inf_gen],
refine outer_measure.caratheodory_is_measurable (assume t, _),
by_cases ht : t = ∅, { simp [ht] },
simp only [outer_measure.Inf_gen_nonempty1 _ _ ht, le_infi_iff, ball_image_iff,
to_outer_measure_apply, measure_eq_infi t],
assume μ hμ u htu hu,
have hm : ∀{s t}, s ⊆ t → outer_measure.Inf_gen (to_outer_measure '' m) s ≤ μ t,
{ assume s t hst,
rw [outer_measure.Inf_gen_nonempty2 _ _ (mem_image_of_mem _ hμ)],
refine infi_le_of_le (μ.to_outer_measure) (infi_le_of_le (mem_image_of_mem _ hμ) _),
rw [to_outer_measure_apply],
refine measure_mono hst },
rw [measure_eq_inter_diff hu hs],
refine add_le_add' (hm $ inter_subset_inter_left _ htu) (hm $ diff_subset_diff_left htu)
end
instance : has_Inf (measure α) :=
⟨λm, (Inf (to_outer_measure '' m)).to_measure $ Inf_caratheodory⟩
lemma Inf_apply {m : set (measure α)} {s : set α} (hs : is_measurable s) :
Inf m s = Inf (to_outer_measure '' m) s :=
to_measure_apply _ _ hs
private lemma Inf_le (h : μ ∈ m) : Inf m ≤ μ :=
have Inf (to_outer_measure '' m) ≤ μ.to_outer_measure := Inf_le (mem_image_of_mem _ h),
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
private lemma le_Inf (h : ∀μ' ∈ m, μ ≤ μ') : μ ≤ Inf m :=
have μ.to_outer_measure ≤ Inf (to_outer_measure '' m) :=
le_Inf $ ball_image_of_ball $ assume μ hμ, to_outer_measure_le.2 $ h _ hμ,
assume s hs, by rw [Inf_apply hs, ← to_outer_measure_apply]; exact this s
instance : has_Sup (measure α) := ⟨λs, Inf {μ' | ∀μ∈s, μ ≤ μ' }⟩
private lemma le_Sup (h : μ ∈ m) : μ ≤ Sup m := le_Inf $ assume μ' h', h' _ h
private lemma Sup_le (h : ∀μ' ∈ m, μ' ≤ μ) : Sup m ≤ μ := Inf_le h
instance : order_bot (measure α) :=
{ bot := 0, bot_le := assume a s hs, bot_le, .. measure.partial_order }
instance : order_top (measure α) :=
{ top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by by_cases s = ∅; simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
.. measure.partial_order }
instance : complete_lattice (measure α) :=
{ Inf := Inf,
Sup := Sup,
inf := λa b, Inf {a, b},
sup := λa b, Sup {a, b},
le_Sup := assume s μ h, le_Sup h,
Sup_le := assume s μ h, Sup_le h,
Inf_le := assume s μ h, Inf_le h,
le_Inf := assume s μ h, le_Inf h,
le_sup_left := assume a b, le_Sup $ by simp,
le_sup_right := assume a b, le_Sup $ by simp,
sup_le := assume a b c hac hbc, Sup_le $ by simp [*, or_imp_distrib] {contextual := tt},
inf_le_left := assume a b, Inf_le $ by simp,
inf_le_right := assume a b, Inf_le $ by simp,
le_inf := assume a b c hac hbc, le_Inf $ by simp [*, or_imp_distrib] {contextual := tt},
.. measure.partial_order, .. measure.lattice.order_top, .. measure.lattice.order_bot }
end
def map (f : α → β) (μ : measure α) : measure β :=
if hf : measurable f then
(μ.to_outer_measure.map f).to_measure $ λ s hs t,
le_to_outer_measure_caratheodory μ _ (hf _ hs) (f ⁻¹' t)
else 0
variables {μ ν : measure α}
@[simp] theorem map_apply {f : α → β} (hf : measurable f)
{s : set β} (hs : is_measurable s) :
(map f μ : measure β) s = μ (f ⁻¹' s) :=
by rw [map, dif_pos hf, to_measure_apply _ _ hs]; refl
@[simp] lemma map_id : map id μ = μ :=
ext $ λ s, map_apply measurable_id
lemma map_map {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) :
map g (map f μ) = map (g ∘ f) μ :=
ext $ λ s hs,
by simp [hf, hg, hs, hg.preimage hs, hg.comp hf];
rw ← preimage_comp
/-- The dirac measure. -/
def dirac (a : α) : measure α :=
(outer_measure.dirac a).to_measure (by simp)
@[simp] lemma dirac_apply (a : α) {s : set α} (hs : is_measurable s) :
(dirac a : measure α) s = ⨆ h : a ∈ s, 1 :=
to_measure_apply _ _ hs
/-- Sum of an indexed family of measures. -/
def sum {ι : Type*} (f : ι → measure α) : measure α :=
(outer_measure.sum (λ i, (f i).to_outer_measure)).to_measure $
le_trans
(by exact le_infi (λ i, le_to_outer_measure_caratheodory _))
(outer_measure.le_sum_caratheodory _)
/-- Counting measure on any measurable space. -/
def count : measure α := sum dirac
@[class] def is_complete {α} {_:measurable_space α} (μ : measure α) : Prop :=
∀ s, μ s = 0 → is_measurable s
/-- The "almost everywhere" filter of co-null sets. -/
def a_e (μ : measure α) : filter α :=
{ sets := {s | μ (-s) = 0},
univ_sets := by simp [measure_empty],
inter_sets := λ s t hs ht, by simp [compl_inter]; exact measure_union_null hs ht,
sets_of_superset := λ s t hs hst, measure_mono_null (set.compl_subset_compl.2 hst) hs }
lemma mem_a_e_iff (s : set α) : s ∈ μ.a_e.sets ↔ μ (- s) = 0 := iff.rfl
end measure
end measure_theory
section is_complete
open measure_theory
variables {α : Type*} [measurable_space α] (μ : measure α)
def is_null_measurable (s : set α) : Prop :=
∃ t z, s = t ∪ z ∧ is_measurable t ∧ μ z = 0
theorem is_null_measurable_iff {μ : measure α} {s : set α} :
is_null_measurable μ s ↔
∃ t, t ⊆ s ∧ is_measurable t ∧ μ (s \ t) = 0 :=
begin
split,
{ rintro ⟨t, z, rfl, ht, hz⟩,
refine ⟨t, set.subset_union_left _ _, ht, measure_mono_null _ hz⟩,
simp [union_diff_left, diff_subset] },
{ rintro ⟨t, st, ht, hz⟩,
exact ⟨t, _, (union_diff_cancel st).symm, ht, hz⟩ }
end
theorem is_null_measurable_measure_eq {μ : measure α} {s t : set α}
(st : t ⊆ s) (hz : μ (s \ t) = 0) : μ s = μ t :=
begin
refine le_antisymm _ (measure_mono st),
have := measure_union_le t (s \ t),
rw [union_diff_cancel st, hz] at this, simpa
end
theorem is_measurable.is_null_measurable
{s : set α} (hs : is_measurable s) : is_null_measurable μ s :=
⟨s, ∅, by simp, hs, μ.empty⟩
theorem is_null_measurable_of_complete [c : μ.is_complete]
{s : set α} : is_null_measurable μ s ↔ is_measurable s :=
⟨by rintro ⟨t, z, rfl, ht, hz⟩; exact
is_measurable.union ht (c _ hz),
λ h, h.is_null_measurable _⟩
variables {μ}
theorem is_null_measurable.union_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s ∪ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
exact ⟨t, z' ∪ z, set.union_assoc _ _ _, ht, le_zero_iff_eq.1
(le_trans (measure_union_le _ _) $ by simp [hz, hz'])⟩
end
theorem null_is_null_measurable {z : set α}
(hz : μ z = 0) : is_null_measurable μ z :=
by simpa using (is_measurable.empty.is_null_measurable _).union_null hz
theorem is_null_measurable.Union_nat {s : ℕ → set α}
(hs : ∀ i, is_null_measurable μ (s i)) :
is_null_measurable μ (Union s) :=
begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht,
rcases ht with ⟨st, ht, hz⟩,
refine is_null_measurable_iff.2
⟨Union t, Union_subset_Union st, is_measurable.Union ht,
measure_mono_null _ (measure_Union_null hz)⟩,
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff)
end
theorem is_measurable.diff_null {s z : set α}
(hs : is_measurable s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rw measure_eq_infi at hz,
choose f hf using show ∀ q : {q:ℚ//q>0}, ∃ t:set α,
z ⊆ t ∧ is_measurable t ∧ μ t < (nnreal.of_real q.1 : ennreal),
{ rintro ⟨ε, ε0⟩,
have : 0 < (nnreal.of_real ε : ennreal), { simpa using ε0 },
rw ← hz at this, simpa [infi_lt_iff] },
refine is_null_measurable_iff.2 ⟨s \ Inter f,
diff_subset_diff_right (subset_Inter (λ i, (hf i).1)),
hs.diff (is_measurable.Inter (λ i, (hf i).2.1)),
measure_mono_null _ (le_zero_iff_eq.1 $ le_of_not_lt $ λ h, _)⟩,
{ exact Inter f },
{ rw [diff_subset_iff, diff_union_self],
exact subset.trans (diff_subset _ _) (subset_union_left _ _) },
rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨ε, ε0', ε0, h⟩,
simp at ε0,
apply not_le_of_lt (lt_trans (hf ⟨ε, ε0⟩).2.2 h),
exact measure_mono (Inter_subset _ _)
end
theorem is_null_measurable.diff_null {s z : set α}
(hs : is_null_measurable μ s) (hz : μ z = 0) :
is_null_measurable μ (s \ z) :=
begin
rcases hs with ⟨t, z', rfl, ht, hz'⟩,
rw [set.union_diff_distrib],
exact (ht.diff_null hz).union_null (measure_mono_null (diff_subset _ _) hz')
end
theorem is_null_measurable.compl {s : set α}
(hs : is_null_measurable μ s) :
is_null_measurable μ (-s) :=
begin
rcases hs with ⟨t, z, rfl, ht, hz⟩,
rw compl_union,
exact ht.compl.diff_null hz
end
def null_measurable {α : Type u} [measurable_space α]
(μ : measure α) : measurable_space α :=
{ is_measurable := is_null_measurable μ,
is_measurable_empty := is_measurable.empty.is_null_measurable _,
is_measurable_compl := λ s hs, hs.compl,
is_measurable_Union := λ f, is_null_measurable.Union_nat }
def completion {α : Type u} [measurable_space α] (μ : measure α) :
@measure_theory.measure α (null_measurable μ) :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, show μ (Union s) = ∑ i, μ (s i), begin
choose t ht using assume i, is_null_measurable_iff.1 (hs i),
simp [forall_and_distrib] at ht, rcases ht with ⟨st, ht, hz⟩,
rw is_null_measurable_measure_eq (Union_subset_Union st),
{ rw measure_Union _ ht,
{ congr, funext i,
exact (is_null_measurable_measure_eq (st i) (hz i)).symm },
{ rintro i j ij x ⟨h₁, h₂⟩,
exact hd i j ij ⟨st i h₁, st j h₂⟩ } },
{ refine measure_mono_null _ (measure_Union_null hz),
rw [diff_subset_iff, ← Union_union_distrib],
exact Union_subset_Union (λ i, by rw ← diff_subset_iff) }
end,
trimmed := begin
letI := null_measurable μ,
refine le_antisymm (λ s, _) (outer_measure.trim_ge _),
rw outer_measure.trim_eq_infi,
dsimp, clear _inst,
rw measure_eq_infi s,
exact infi_le_infi (λ t, infi_le_infi $ λ st,
infi_le_infi2 $ λ ht, ⟨ht.is_null_measurable _, le_refl _⟩)
end }
instance completion.is_complete {α : Type u} [measurable_space α] (μ : measure α) :
(completion μ).is_complete :=
λ z hz, null_is_null_measurable hz
end is_complete
namespace measure_theory
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type*) extends measurable_space α :=
(μ {} : measure α)
end prio
section measure_space
variables {α : Type*} [measure_space α] {s₁ s₂ : set α}
open measure_space
def volume : set α → ennreal := @μ α _
@[simp] lemma volume_empty : volume (∅ : set α) = 0 := μ.empty
lemma volume_mono : s₁ ⊆ s₂ → volume s₁ ≤ volume s₂ := measure_mono
lemma volume_mono_null : s₁ ⊆ s₂ → volume s₂ = 0 → volume s₁ = 0 :=
measure_mono_null
theorem volume_Union_le {β} [encodable β] :
∀ (s : β → set α), volume (⋃i, s i) ≤ (∑i, volume (s i)) :=
measure_Union_le
lemma volume_Union_null {β} [encodable β] {s : β → set α} :
(∀ i, volume (s i) = 0) → volume (⋃i, s i) = 0 :=
measure_Union_null
theorem volume_union_le : ∀ (s₁ s₂ : set α), volume (s₁ ∪ s₂) ≤ volume s₁ + volume s₂ :=
measure_union_le
lemma volume_union_null : volume s₁ = 0 → volume s₂ = 0 → volume (s₁ ∪ s₂) = 0 :=
measure_union_null
lemma volume_Union {β} [encodable β] {f : β → set α} :
pairwise (disjoint on f) → (∀i, is_measurable (f i)) →
volume (⋃i, f i) = (∑i, volume (f i)) :=
measure_Union
lemma volume_union : disjoint s₁ s₂ → is_measurable s₁ → is_measurable s₂ →
volume (s₁ ∪ s₂) = volume s₁ + volume s₂ :=
measure_union
lemma volume_bUnion {β} {s : set β} {f : β → set α} : countable s →
pairwise_on s (disjoint on f) → (∀b∈s, is_measurable (f b)) →
volume (⋃b∈s, f b) = ∑p:s, volume (f p.1) :=
measure_bUnion
lemma volume_sUnion {S : set (set α)} : countable S →
pairwise_on S disjoint → (∀s∈S, is_measurable s) →
volume (⋃₀ S) = ∑s:S, volume s.1 :=
measure_sUnion
lemma volume_bUnion_finset {β} {s : finset β} {f : β → set α}
(hd : pairwise_on ↑s (disjoint on f)) (hm : ∀b∈s, is_measurable (f b)) :
volume (⋃b∈s, f b) = s.sum (λp, volume (f p)) :=
show volume (⋃b∈(↑s : set β), f b) = s.sum (λp, volume (f p)),
begin
rw [volume_bUnion (countable_finite (finset.finite_to_set s)) hd hm, tsum_eq_sum],
{ show s.attach.sum (λb:(↑s : set β), volume (f b)) = s.sum (λb, volume (f b)),
exact @finset.sum_attach _ _ s _ (λb, volume (f b)) },
simp
end
lemma volume_diff : s₂ ⊆ s₁ → is_measurable s₁ → is_measurable s₂ →
volume s₂ < ⊤ → volume (s₁ \ s₂) = volume s₁ - volume s₂ :=
measure_diff
/-- `∀ₘ a:α, p a` states that the property `p` is almost everywhere true in the measure space
associated with `α`. This means that the measure of the complementary of `p` is `0`.
In a probability measure, the measure of `p` is `1`, when `p` is measurable.
-/
def all_ae (p : α → Prop) : Prop := { a | p a } ∈ (@measure_space.μ α _).a_e
notation `∀ₘ` binders `, ` r:(scoped P, all_ae P) := r
lemma all_ae_congr {p q : α → Prop} (h : ∀ₘ a, p a ↔ q a) : (∀ₘ a, p a) ↔ (∀ₘ a, q a) :=
iff.intro
(assume h', by filter_upwards [h, h'] assume a hpq hp, hpq.1 hp)
(assume h', by filter_upwards [h, h'] assume a hpq hq, hpq.2 hq)
lemma all_ae_iff {p : α → Prop} : (∀ₘ a, p a) ↔ volume { a | ¬ p a } = 0 := iff.rfl
lemma all_ae_of_all {p : α → Prop} : (∀a, p a) → ∀ₘ a, p a := assume h,
by {rw all_ae_iff, convert volume_empty, simp only [h, not_true], reflexivity}
lemma all_ae_all_iff {ι : Type*} [encodable ι] {p : α → ι → Prop} :
(∀ₘ a, ∀i, p a i) ↔ (∀i, ∀ₘ a, p a i) :=
begin
refine iff.intro (assume h i, _) (assume h, _),
{ filter_upwards [h] assume a ha, ha i },
{ have h := measure_Union_null h,
rw [← compl_Inter] at h,
filter_upwards [h] assume a, mem_Inter.1 }
end
variables {β : Type*}
lemma all_ae_eq_refl (f : α → β) : ∀ₘ a, f a = f a :=
by { filter_upwards [], assume a, apply eq.refl }
lemma all_ae_eq_symm {f g : α → β} : (∀ₘ a, f a = g a) → (∀ₘ a, g a = f a) :=
by { assume h, filter_upwards [h], assume a, apply eq.symm }
lemma all_ae_eq_trans {f g h: α → β} (h₁ : ∀ₘ a, f a = g a) (h₂ : ∀ₘ a, g a = h a) :
∀ₘ a, f a = h a :=
by { filter_upwards [h₁, h₂], intro a, exact eq.trans }
end measure_space
end measure_theory
|
506f20c404e2df85de3402542eb19f6cecf9b55d | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/linear_algebra/finite_dimensional.lean | f45665f59398d272a028999cac9cdd86535f63b6 | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 57,256 | lean | /-
Copyright (c) 2019 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import linear_algebra.dimension
import ring_theory.principal_ideal_domain
import algebra.algebra.subalgebra
/-!
# Finite dimensional vector spaces
Definition and basic properties of finite dimensional vector spaces, of their dimensions, and
of linear maps on such spaces.
## Main definitions
Assume `V` is a vector space over a field `K`. There are (at least) three equivalent definitions of
finite-dimensionality of `V`:
- it admits a finite basis.
- it is finitely generated.
- it is noetherian, i.e., every subspace is finitely generated.
We introduce a typeclass `finite_dimensional K V` capturing this property. For ease of transfer of
proof, it is defined using the third point of view, i.e., as `is_noetherian`. However, we prove
that all these points of view are equivalent, with the following lemmas
(in the namespace `finite_dimensional`):
- `exists_is_basis_finite` states that a finite-dimensional vector space has a finite basis
- `of_fintype_basis` states that the existence of a basis indexed by a finite type implies
finite-dimensionality
- `of_finset_basis` states that the existence of a basis indexed by a `finset` implies
finite-dimensionality
- `of_finite_basis` states that the existence of a basis indexed by a finite set implies
finite-dimensionality
- `iff_fg` states that the space is finite-dimensional if and only if it is finitely generated
Also defined is `findim`, the dimension of a finite dimensional space, returning a `nat`,
as opposed to `dim`, which returns a `cardinal`. When the space has infinite dimension, its
`findim` is by convention set to `0`.
Preservation of finite-dimensionality and formulas for the dimension are given for
- submodules
- quotients (for the dimension of a quotient, see `findim_quotient_add_findim`)
- linear equivs, in `linear_equiv.finite_dimensional` and `linear_equiv.findim_eq`
- image under a linear map (the rank-nullity formula is in `findim_range_add_findim_ker`)
Basic properties of linear maps of a finite-dimensional vector space are given. Notably, the
equivalence of injectivity and surjectivity is proved in `linear_map.injective_iff_surjective`,
and the equivalence between left-inverse and right-inverse in `mul_eq_one_comm` and
`comp_eq_id_comm`.
## Implementation notes
Most results are deduced from the corresponding results for the general dimension (as a cardinal),
in `dimension.lean`. Not all results have been ported yet.
One of the characterizations of finite-dimensionality is in terms of finite generation. This
property is currently defined only for submodules, so we express it through the fact that the
maximal submodule (which, as a set, coincides with the whole space) is finitely generated. This is
not very convenient to use, although there are some helper functions. However, this becomes very
convenient when speaking of submodules which are finite-dimensional, as this notion coincides with
the fact that the submodule is finitely generated (as a submodule of the whole space). This
equivalence is proved in `submodule.fg_iff_finite_dimensional`.
-/
universes u v v' w
open_locale classical
open vector_space cardinal submodule module function
variables {K : Type u} {V : Type v} [field K] [add_comm_group V] [vector_space K V]
{V₂ : Type v'} [add_comm_group V₂] [vector_space K V₂]
/-- `finite_dimensional` vector spaces are defined to be noetherian modules.
Use `finite_dimensional.iff_fg` or `finite_dimensional.of_fintype_basis` to prove finite dimension
from a conventional definition. -/
@[reducible] def finite_dimensional (K V : Type*) [field K]
[add_comm_group V] [vector_space K V] := is_noetherian K V
namespace finite_dimensional
open is_noetherian
/-- A vector space is finite-dimensional if and only if its dimension (as a cardinal) is strictly
less than the first infinite cardinal `omega`. -/
lemma finite_dimensional_iff_dim_lt_omega : finite_dimensional K V ↔ dim K V < omega.{v} :=
begin
cases exists_is_basis K V with b hb,
have := is_basis.mk_eq_dim hb,
simp only [lift_id] at this,
rw [← this, lt_omega_iff_fintype, ← @set.set_of_mem_eq _ b, ← subtype.range_coe_subtype],
split,
{ intro, resetI, convert finite_of_linear_independent hb.1, simp },
{ assume hbfinite,
refine @is_noetherian_of_linear_equiv K (⊤ : submodule K V) V _
_ _ _ _ (linear_equiv.of_top _ rfl) (id _),
refine is_noetherian_of_fg_of_noetherian _ ⟨set.finite.to_finset hbfinite, _⟩,
rw [set.finite.coe_to_finset, ← hb.2], refl }
end
/-- The dimension of a finite-dimensional vector space, as a cardinal, is strictly less than the
first infinite cardinal `omega`. -/
lemma dim_lt_omega (K V : Type*) [field K] [add_comm_group V] [vector_space K V] :
∀ [finite_dimensional K V], dim K V < omega.{v} :=
finite_dimensional_iff_dim_lt_omega.1
/-- In a finite dimensional space, there exists a finite basis. A basis is in general given as a
function from an arbitrary type to the vector space. Here, we think of a basis as a set (instead of
a function), and use as parametrizing type this set (and as a function the coercion
`coe : s → V`).
-/
variables (K V)
lemma exists_is_basis_finite [finite_dimensional K V] :
∃ s : set V, (is_basis K (coe : s → V)) ∧ s.finite :=
begin
cases exists_is_basis K V with s hs,
exact ⟨s, hs, finite_of_linear_independent hs.1⟩
end
/-- In a finite dimensional space, there exists a finite basis. Provides the basis as a finset.
This is in contrast to `exists_is_basis_finite`, which provides a set and a `set.finite`.
-/
lemma exists_is_basis_finset [finite_dimensional K V] :
∃ b : finset V, is_basis K (coe : (↑b : set V) → V) :=
begin
obtain ⟨s, s_basis, s_finite⟩ := exists_is_basis_finite K V,
refine ⟨s_finite.to_finset, _⟩,
rw set.finite.coe_to_finset,
exact s_basis,
end
/-- A finite dimensional vector space over a finite field is finite -/
noncomputable def fintype_of_fintype [fintype K] [finite_dimensional K V] : fintype V :=
module.fintype_of_fintype (classical.some_spec (finite_dimensional.exists_is_basis_finset K V) : _)
variables {K V}
/-- A vector space is finite-dimensional if and only if it is finitely generated. As the
finitely-generated property is a property of submodules, we formulate this in terms of the
maximal submodule, equal to the whole space as a set by definition.-/
lemma iff_fg :
finite_dimensional K V ↔ (⊤ : submodule K V).fg :=
begin
split,
{ introI h,
rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩,
exact ⟨s_finite.to_finset, by { convert s_basis.2, simp }⟩ },
{ rintros ⟨s, hs⟩,
rw [finite_dimensional_iff_dim_lt_omega, ← dim_top, ← hs],
exact lt_of_le_of_lt (dim_span_le _) (lt_omega_iff_finite.2 (set.finite_mem_finset s)) }
end
/-- If a vector space has a finite basis, then it is finite-dimensional. -/
lemma of_fintype_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) :
finite_dimensional K V :=
iff_fg.2 $ ⟨finset.univ.image b, by {convert h.2, simp} ⟩
/-- If a vector space has a basis indexed by elements of a finite set, then it is
finite-dimensional. -/
lemma of_finite_basis {ι} {s : set ι} {b : s → V} (h : is_basis K b) (hs : set.finite s) :
finite_dimensional K V :=
by haveI := hs.fintype; exact of_fintype_basis h
/-- If a vector space has a finite basis, then it is finite-dimensional, finset style. -/
lemma of_finset_basis {ι} {s : finset ι} {b : (↑s : set ι) → V} (h : is_basis K b) :
finite_dimensional K V :=
of_finite_basis h s.finite_to_set
/-- A subspace of a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_submodule [finite_dimensional K V] (S : submodule K V) :
finite_dimensional K S :=
finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_submodule_le _) (dim_lt_omega K V))
/-- A quotient of a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_quotient [finite_dimensional K V] (S : submodule K V) :
finite_dimensional K (quotient S) :=
finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_quotient_le _) (dim_lt_omega K V))
/-- The dimension of a finite-dimensional vector space as a natural number. Defined by convention to
be `0` if the space is infinite-dimensional. -/
noncomputable def findim (K V : Type*) [field K]
[add_comm_group V] [vector_space K V] : ℕ :=
(dim K V).to_nat
/-- In a finite-dimensional space, its dimension (seen as a cardinal) coincides with its
`findim`. -/
lemma findim_eq_dim (K : Type u) (V : Type v) [field K]
[add_comm_group V] [vector_space K V] [finite_dimensional K V] :
(findim K V : cardinal.{v}) = dim K V :=
by rw [findim, cast_to_nat_of_lt_omega (dim_lt_omega K V)]
lemma findim_eq_of_dim_eq {n : ℕ} (h : dim K V = ↑ n) : findim K V = n :=
begin
apply_fun to_nat at h,
rw to_nat_cast at h,
exact_mod_cast h,
end
lemma findim_of_infinite_dimensional {K V : Type*} [field K] [add_comm_group V] [vector_space K V]
(h : ¬finite_dimensional K V) : findim K V = 0 :=
dif_neg $ mt finite_dimensional_iff_dim_lt_omega.2 h
lemma finite_dimensional_of_findim {K V : Type*} [field K] [add_comm_group V] [vector_space K V]
(h : 0 < findim K V) : finite_dimensional K V :=
by { contrapose h, simp [findim_of_infinite_dimensional h] }
/-- We can infer `finite_dimensional K V` in the presence of `[fact (findim K V = n + 1)]`. Declare
this as a local instance where needed. -/
lemma finite_dimensional_of_findim_eq_succ {K V : Type*} [field K] [add_comm_group V]
[vector_space K V] (n : ℕ) [fact (findim K V = n + 1)] :
finite_dimensional K V :=
finite_dimensional_of_findim $ by convert nat.succ_pos n
/-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the
cardinality of the basis. -/
lemma dim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) :
dim K V = fintype.card ι :=
by rw [←h.mk_range_eq_dim, cardinal.fintype_card,
set.card_range_of_injective h.injective]
/-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the
basis. -/
lemma findim_eq_card_basis {ι : Type w} [fintype ι] {b : ι → V} (h : is_basis K b) :
findim K V = fintype.card ι :=
begin
haveI : finite_dimensional K V := of_fintype_basis h,
have := dim_eq_card_basis h,
rw ← findim_eq_dim at this,
exact_mod_cast this
end
/-- If a vector space is finite-dimensional, then the cardinality of any basis is equal to its
`findim`. -/
lemma findim_eq_card_basis' [finite_dimensional K V] {ι : Type w} {b : ι → V} (h : is_basis K b) :
(findim K V : cardinal.{w}) = cardinal.mk ι :=
begin
rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩,
letI: fintype s := s_finite.fintype,
have A : cardinal.mk s = fintype.card s := fintype_card _,
have B : findim K V = fintype.card s := findim_eq_card_basis s_basis,
have C : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{v w} (cardinal.mk s) :=
mk_eq_mk_of_basis h s_basis,
rw [A, ← B, lift_nat_cast] at C,
have : cardinal.lift.{w v} (cardinal.mk ι) = cardinal.lift.{w v} (findim K V),
by { simp, exact C },
exact (lift_inj.mp this).symm
end
/-- If a vector space has a finite basis, then its dimension is equal to the cardinality of the
basis. This lemma uses a `finset` instead of indexed types. -/
lemma findim_eq_card_finset_basis {b : finset V}
(h : is_basis K (subtype.val : (↑b : set V) -> V)) :
findim K V = finset.card b :=
by { rw [findim_eq_card_basis h, fintype.subtype_card], intros x, refl }
lemma equiv_fin {ι : Type*} [finite_dimensional K V] {v : ι → V} (hv : is_basis K v) :
∃ g : fin (findim K V) ≃ ι, is_basis K (v ∘ g) :=
begin
have : (cardinal.mk (fin $ findim K V)).lift = (cardinal.mk ι).lift,
{ simp [cardinal.mk_fin (findim K V), ← findim_eq_card_basis' hv] },
rcases cardinal.lift_mk_eq.mp this with ⟨g⟩,
exact ⟨g, hv.comp _ g.bijective⟩
end
lemma equiv_fin_of_dim_eq {ι : Type*} [finite_dimensional K V] {n : ℕ} (hn : findim K V = n)
{v : ι → V} (hv : is_basis K v) :
∃ g : fin n ≃ ι, is_basis K (v ∘ g) :=
let ⟨g₁, hg₁⟩ := equiv_fin hv, ⟨g₂⟩ := fin.equiv_iff_eq.mpr hn in
⟨g₂.symm.trans g₁, hv.comp _ (g₂.symm.trans g₁).bijective⟩
variables (K V)
lemma fin_basis [finite_dimensional K V] : ∃ v : fin (findim K V) → V, is_basis K v :=
let ⟨B, hB, B_fin⟩ := exists_is_basis_finite K V, ⟨g, hg⟩ := finite_dimensional.equiv_fin hB in
⟨coe ∘ g, hg⟩
variables {K V}
lemma cardinal_mk_le_findim_of_linear_independent
[finite_dimensional K V] {ι : Type w} {b : ι → V} (h : linear_independent K b) :
cardinal.mk ι ≤ findim K V :=
begin
rw ← lift_le.{_ (max v w)},
simpa [← findim_eq_dim K V] using
cardinal_lift_le_dim_of_linear_independent.{_ _ _ (max v w)} h
end
lemma fintype_card_le_findim_of_linear_independent
[finite_dimensional K V] {ι : Type*} [fintype ι] {b : ι → V} (h : linear_independent K b) :
fintype.card ι ≤ findim K V :=
by simpa [fintype_card] using cardinal_mk_le_findim_of_linear_independent h
lemma finset_card_le_findim_of_linear_independent [finite_dimensional K V] {b : finset V}
(h : linear_independent K (λ x, x : (↑b : set V) → V)) :
b.card ≤ findim K V :=
begin
rw ←fintype.card_coe,
exact fintype_card_le_findim_of_linear_independent h,
end
lemma lt_omega_of_linear_independent {ι : Type w} [finite_dimensional K V]
{v : ι → V} (h : linear_independent K v) :
cardinal.mk ι < cardinal.omega :=
begin
apply cardinal.lift_lt.1,
apply lt_of_le_of_lt,
apply linear_independent_le_dim h,
rw [←findim_eq_dim, cardinal.lift_omega, cardinal.lift_nat_cast],
apply cardinal.nat_lt_omega,
end
lemma not_linear_independent_of_infinite {ι : Type w} [inf : infinite ι] [finite_dimensional K V]
(v : ι → V) : ¬ linear_independent K v :=
begin
intro h_lin_indep,
have : ¬ omega ≤ mk ι := not_le.mpr (lt_omega_of_linear_independent h_lin_indep),
have : omega ≤ mk ι := infinite_iff.mp inf,
contradiction
end
/-- A finite dimensional space has positive `findim` iff it has a nonzero element. -/
lemma findim_pos_iff_exists_ne_zero [finite_dimensional K V] : 0 < findim K V ↔ ∃ x : V, x ≠ 0 :=
iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_exists_ne_zero K V _ _ _)
/-- A finite dimensional space has positive `findim` iff it is nontrivial. -/
lemma findim_pos_iff [finite_dimensional K V] : 0 < findim K V ↔ nontrivial V :=
iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_pos_iff_nontrivial K V _ _ _)
/-- A nontrivial finite dimensional space has positive `findim`. -/
lemma findim_pos [finite_dimensional K V] [h : nontrivial V] : 0 < findim K V :=
findim_pos_iff.mpr h
/-- A finite dimensional space has zero `findim` iff it is a subsingleton.
This is the `findim` version of `dim_zero_iff`. -/
lemma findim_zero_iff [finite_dimensional K V] :
findim K V = 0 ↔ subsingleton V :=
iff.trans (by { rw ← findim_eq_dim, norm_cast }) (@dim_zero_iff K V _ _ _)
/-- A finite dimensional space that is a subsingleton has zero `findim`. -/
lemma findim_zero_of_subsingleton [finite_dimensional K V] [h : subsingleton V] :
findim K V = 0 :=
findim_zero_iff.2 h
section
open_locale big_operators
open finset
/--
If a finset has cardinality larger than the dimension of the space,
then there is a nontrivial linear relation amongst its elements.
-/
lemma exists_nontrivial_relation_of_dim_lt_card
[finite_dimensional K V] {t : finset V} (h : findim K V < t.card) :
∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∃ x ∈ t, f x ≠ 0 :=
begin
have := mt finset_card_le_findim_of_linear_independent (by { simpa using h }),
rw linear_dependent_iff at this,
obtain ⟨s, g, sum, z, zm, nonzero⟩ := this,
-- Now we have to extend `g` to all of `t`, then to all of `V`.
let f : V → K :=
λ x, if h : x ∈ t then if (⟨x, h⟩ : (↑t : set V)) ∈ s then g ⟨x, h⟩ else 0 else 0,
-- and finally clean up the mess caused by the extension.
refine ⟨f, _, _⟩,
{ dsimp [f],
rw ← sum,
fapply sum_bij_ne_zero (λ v hvt _, (⟨v, hvt⟩ : {v // v ∈ t})),
{ intros v hvt H, dsimp,
rw [dif_pos hvt] at H,
contrapose! H,
rw [if_neg H, zero_smul], },
{ intros _ _ _ _ _ _, exact subtype.mk.inj, },
{ intros b hbs hb,
use b,
simpa only [hbs, exists_prop, dif_pos, finset.mk_coe, and_true, if_true, finset.coe_mem,
eq_self_iff_true, exists_prop_of_true, ne.def] using hb, },
{ intros a h₁, dsimp, rw [dif_pos h₁],
intro h₂, rw [if_pos], contrapose! h₂,
rw [if_neg h₂, zero_smul], }, },
{ refine ⟨z, z.2, _⟩, dsimp only [f], erw [dif_pos z.2, if_pos]; rwa [subtype.coe_eta] },
end
/--
If a finset has cardinality larger than `findim + 1`,
then there is a nontrivial linear relation amongst its elements,
such that the coefficients of the relation sum to zero.
-/
lemma exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card
[finite_dimensional K V] {t : finset V} (h : findim K V + 1 < t.card) :
∃ f : V → K, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, f x ≠ 0 :=
begin
-- Pick an element x₀ ∈ t,
have card_pos : 0 < t.card := lt_trans (nat.succ_pos _) h,
obtain ⟨x₀, m⟩ := (finset.card_pos.1 card_pos).bex,
-- and apply the previous lemma to the {xᵢ - x₀}
let shift : V ↪ V := ⟨λ x, x - x₀, sub_left_injective⟩,
let t' := (t.erase x₀).map shift,
have h' : findim K V < t'.card,
{ simp only [t', card_map, finset.card_erase_of_mem m],
exact nat.lt_pred_iff.mpr h, },
-- to obtain a function `g`.
obtain ⟨g, gsum, x₁, x₁_mem, nz⟩ := exists_nontrivial_relation_of_dim_lt_card h',
-- Then obtain `f` by translating back by `x₀`,
-- and setting the value of `f` at `x₀` to ensure `∑ e in t, f e = 0`.
let f : V → K := λ z, if z = x₀ then - ∑ z in (t.erase x₀), g (z - x₀) else g (z - x₀),
refine ⟨f, _ ,_ ,_⟩,
-- After this, it's a matter of verifiying the properties,
-- based on the corresponding properties for `g`.
{ show ∑ (e : V) in t, f e • e = 0,
-- We prove this by splitting off the `x₀` term of the sum,
-- which is itself a sum over `t.erase x₀`,
-- combining the two sums, and
-- observing that after reindexing we have exactly
-- ∑ (x : V) in t', g x • x = 0.
simp only [f],
conv_lhs { apply_congr, skip, rw [ite_smul], },
rw [finset.sum_ite],
conv { congr, congr, apply_congr, simp [filter_eq', m], },
conv { congr, congr, skip, apply_congr, simp [filter_ne'], },
rw [sum_singleton, neg_smul, add_comm, ←sub_eq_add_neg, sum_smul, ←sum_sub_distrib],
simp only [←smul_sub],
-- At the end we have to reindex the sum, so we use `change` to
-- express the summand using `shift`.
change (∑ (x : V) in t.erase x₀, (λ e, g e • e) (shift x)) = 0,
rw ←sum_map _ shift,
exact gsum, },
{ show ∑ (e : V) in t, f e = 0,
-- Again we split off the `x₀` term,
-- observing that it exactly cancels the other terms.
rw [← insert_erase m, sum_insert (not_mem_erase x₀ t)],
dsimp [f],
rw [if_pos rfl],
conv_lhs { congr, skip, apply_congr, skip, rw if_neg (show x ≠ x₀, from (mem_erase.mp H).1), },
exact neg_add_self _, },
{ show ∃ (x : V) (H : x ∈ t), f x ≠ 0,
-- We can use x₁ + x₀.
refine ⟨x₁ + x₀, _, _⟩,
{ rw finset.mem_map at x₁_mem,
rcases x₁_mem with ⟨x₁, x₁_mem, rfl⟩,
rw mem_erase at x₁_mem,
simp only [x₁_mem, sub_add_cancel, function.embedding.coe_fn_mk], },
{ dsimp only [f],
rwa [if_neg, add_sub_cancel],
rw [add_left_eq_self], rintro rfl,
simpa only [sub_eq_zero, exists_prop, finset.mem_map, embedding.coe_fn_mk, eq_self_iff_true,
mem_erase, not_true, exists_eq_right, ne.def, false_and] using x₁_mem, } },
end
section
variables {L : Type*} [linear_ordered_field L]
variables {W : Type v} [add_comm_group W] [vector_space L W]
/--
A slight strengthening of `exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card`
available when working over an ordered field:
we can ensure a positive coefficient, not just a nonzero coefficient.
-/
lemma exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card
[finite_dimensional L W] {t : finset W} (h : findim L W + 1 < t.card) :
∃ f : W → L, ∑ e in t, f e • e = 0 ∧ ∑ e in t, f e = 0 ∧ ∃ x ∈ t, 0 < f x :=
begin
obtain ⟨f, sum, total, nonzero⟩ := exists_nontrivial_relation_sum_zero_of_dim_succ_lt_card h,
exact ⟨f, sum, total, exists_pos_of_sum_zero_of_exists_nonzero f total nonzero⟩,
end
end
end
/-- If a submodule has maximal dimension in a finite dimensional space, then it is equal to the
whole space. -/
lemma eq_top_of_findim_eq [finite_dimensional K V] {S : submodule K V}
(h : findim K S = findim K V) : S = ⊤ :=
begin
cases exists_is_basis K S with bS hbS,
have : linear_independent K (subtype.val : (subtype.val '' bS : set V) → V),
from @linear_independent.image_subtype _ _ _ _ _ _ _ _ _
(submodule.subtype S) hbS.1 (by simp),
cases exists_subset_is_basis this with b hb,
letI : fintype b := classical.choice (finite_of_linear_independent hb.2.1),
letI : fintype (subtype.val '' bS) := classical.choice (finite_of_linear_independent this),
letI : fintype bS := classical.choice (finite_of_linear_independent hbS.1),
have : subtype.val '' bS = b, from set.eq_of_subset_of_card_le hb.1
(by rw [set.card_image_of_injective _ subtype.val_injective, ← findim_eq_card_basis hbS,
← findim_eq_card_basis hb.2, h]; apply_instance),
erw [← hb.2.2, subtype.range_coe, ← this, ← subtype_eq_val, span_image],
have := hbS.2,
erw [subtype.range_coe] at this,
rw [this, map_top (submodule.subtype S), range_subtype],
end
variable (K)
/-- A field is one-dimensional as a vector space over itself. -/
@[simp] lemma findim_of_field : findim K K = 1 :=
begin
have := dim_of_field K,
rw [← findim_eq_dim] at this,
exact_mod_cast this
end
instance finite_dimensional_self : finite_dimensional K K :=
by apply_instance
/-- The vector space of functions on a fintype ι has findim equal to the cardinality of ι. -/
@[simp] lemma findim_fintype_fun_eq_card {ι : Type v} [fintype ι] :
findim K (ι → K) = fintype.card ι :=
begin
have : vector_space.dim K (ι → K) = fintype.card ι := dim_fun',
rwa [← findim_eq_dim, nat_cast_inj] at this,
end
/-- The vector space of functions on `fin n` has findim equal to `n`. -/
@[simp] lemma findim_fin_fun {n : ℕ} : findim K (fin n → K) = n :=
by simp
/-- The submodule generated by a finite set is finite-dimensional. -/
theorem span_of_finite {A : set V} (hA : set.finite A) :
finite_dimensional K (submodule.span K A) :=
is_noetherian_span_of_finite K hA
/-- The submodule generated by a single element is finite-dimensional. -/
instance (x : V) : finite_dimensional K (K ∙ x) := by {apply span_of_finite, simp}
end finite_dimensional
section zero_dim
open vector_space finite_dimensional
lemma finite_dimensional_of_dim_eq_zero (h : vector_space.dim K V = 0) : finite_dimensional K V :=
by rw [finite_dimensional_iff_dim_lt_omega, h]; exact cardinal.omega_pos
lemma finite_dimensional_of_dim_eq_one (h : vector_space.dim K V = 1) : finite_dimensional K V :=
by rw [finite_dimensional_iff_dim_lt_omega, h]; exact one_lt_omega
lemma findim_eq_zero_of_dim_eq_zero [finite_dimensional K V] (h : vector_space.dim K V = 0) :
findim K V = 0 :=
begin
convert findim_eq_dim K V,
rw h, norm_cast
end
variables (K V)
lemma finite_dimensional_bot : finite_dimensional K (⊥ : submodule K V) :=
finite_dimensional_of_dim_eq_zero $ by simp
@[simp] lemma findim_bot : findim K (⊥ : submodule K V) = 0 :=
begin
haveI := finite_dimensional_bot K V,
convert findim_eq_dim K (⊥ : submodule K V),
rw dim_bot, norm_cast
end
variables {K V}
lemma bot_eq_top_of_dim_eq_zero (h : vector_space.dim K V = 0) : (⊥ : submodule K V) = ⊤ :=
begin
haveI := finite_dimensional_of_dim_eq_zero h,
apply eq_top_of_findim_eq,
rw [findim_bot, findim_eq_zero_of_dim_eq_zero h]
end
@[simp] theorem dim_eq_zero {S : submodule K V} : dim K S = 0 ↔ S = ⊥ :=
⟨λ h, (submodule.eq_bot_iff _).2 $ λ x hx, congr_arg subtype.val $
((submodule.eq_bot_iff _).1 $ eq.symm $ bot_eq_top_of_dim_eq_zero h) ⟨x, hx⟩ submodule.mem_top,
λ h, by rw [h, dim_bot]⟩
@[simp] theorem findim_eq_zero {S : submodule K V} [finite_dimensional K S] :
findim K S = 0 ↔ S = ⊥ :=
by rw [← dim_eq_zero, ← findim_eq_dim, ← @nat.cast_zero cardinal, cardinal.nat_cast_inj]
end zero_dim
namespace submodule
open finite_dimensional
/-- A submodule is finitely generated if and only if it is finite-dimensional -/
theorem fg_iff_finite_dimensional (s : submodule K V) :
s.fg ↔ finite_dimensional K s :=
⟨λh, is_noetherian_of_fg_of_noetherian s h,
λh, by { rw ← map_subtype_top s, exact fg_map (iff_fg.1 h) }⟩
/-- A submodule contained in a finite-dimensional submodule is
finite-dimensional. -/
lemma finite_dimensional_of_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (h : S₁ ≤ S₂) :
finite_dimensional K S₁ :=
finite_dimensional_iff_dim_lt_omega.2 (lt_of_le_of_lt (dim_le_of_submodule _ _ h)
(dim_lt_omega K S₂))
/-- The inf of two submodules, the first finite-dimensional, is
finite-dimensional. -/
instance finite_dimensional_inf_left (S₁ S₂ : submodule K V) [finite_dimensional K S₁] :
finite_dimensional K (S₁ ⊓ S₂ : submodule K V) :=
finite_dimensional_of_le inf_le_left
/-- The inf of two submodules, the second finite-dimensional, is
finite-dimensional. -/
instance finite_dimensional_inf_right (S₁ S₂ : submodule K V) [finite_dimensional K S₂] :
finite_dimensional K (S₁ ⊓ S₂ : submodule K V) :=
finite_dimensional_of_le inf_le_right
/-- The sup of two finite-dimensional submodules is
finite-dimensional. -/
instance finite_dimensional_sup (S₁ S₂ : submodule K V) [h₁ : finite_dimensional K S₁]
[h₂ : finite_dimensional K S₂] : finite_dimensional K (S₁ ⊔ S₂ : submodule K V) :=
begin
rw ←submodule.fg_iff_finite_dimensional at *,
exact submodule.fg_sup h₁ h₂
end
/-- In a finite-dimensional vector space, the dimensions of a submodule and of the corresponding
quotient add up to the dimension of the space. -/
theorem findim_quotient_add_findim [finite_dimensional K V] (s : submodule K V) :
findim K s.quotient + findim K s = findim K V :=
begin
have := dim_quotient_add_dim s,
rw [← findim_eq_dim, ← findim_eq_dim, ← findim_eq_dim] at this,
exact_mod_cast this
end
/-- The dimension of a submodule is bounded by the dimension of the ambient space. -/
lemma findim_le [finite_dimensional K V] (s : submodule K V) : findim K s ≤ findim K V :=
by { rw ← s.findim_quotient_add_findim, exact nat.le_add_left _ _ }
/-- The dimension of a strict submodule is strictly bounded by the dimension of the ambient
space. -/
lemma findim_lt [finite_dimensional K V] {s : submodule K V} (h : s < ⊤) :
findim K s < findim K V :=
begin
rw [← s.findim_quotient_add_findim, add_comm],
exact nat.lt_add_of_zero_lt_left _ _ (findim_pos_iff.mpr (quotient.nontrivial_of_lt_top _ h))
end
/-- The dimension of a quotient is bounded by the dimension of the ambient space. -/
lemma findim_quotient_le [finite_dimensional K V] (s : submodule K V) :
findim K s.quotient ≤ findim K V :=
by { rw ← s.findim_quotient_add_findim, exact nat.le_add_right _ _ }
/-- The sum of the dimensions of s + t and s ∩ t is the sum of the dimensions of s and t -/
theorem dim_sup_add_dim_inf_eq (s t : submodule K V) [finite_dimensional K s]
[finite_dimensional K t] : findim K ↥(s ⊔ t) + findim K ↥(s ⊓ t) = findim K ↥s + findim K ↥t :=
begin
have key : dim K ↥(s ⊔ t) + dim K ↥(s ⊓ t) = dim K s + dim K t := dim_sup_add_dim_inf_eq s t,
repeat { rw ←findim_eq_dim at key },
norm_cast at key,
exact key
end
lemma eq_top_of_disjoint [finite_dimensional K V] (s t : submodule K V)
(hdim : findim K s + findim K t = findim K V)
(hdisjoint : disjoint s t) : s ⊔ t = ⊤ :=
begin
have h_findim_inf : findim K ↥(s ⊓ t) = 0,
{ rw [disjoint, le_bot_iff] at hdisjoint,
rw [hdisjoint, findim_bot] },
apply eq_top_of_findim_eq,
rw ←hdim,
convert s.dim_sup_add_dim_inf_eq t,
rw h_findim_inf,
refl,
end
end submodule
namespace linear_equiv
open finite_dimensional
/-- Finite dimensionality is preserved under linear equivalence. -/
protected theorem finite_dimensional (f : V ≃ₗ[K] V₂) [finite_dimensional K V] :
finite_dimensional K V₂ :=
is_noetherian_of_linear_equiv f
/-- The dimension of a finite dimensional space is preserved under linear equivalence. -/
theorem findim_eq (f : V ≃ₗ[K] V₂) [finite_dimensional K V] :
findim K V = findim K V₂ :=
begin
haveI : finite_dimensional K V₂ := f.finite_dimensional,
simpa [← findim_eq_dim] using f.lift_dim_eq
end
end linear_equiv
namespace finite_dimensional
/--
Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension.
-/
theorem nonempty_linear_equiv_of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂]
(cond : findim K V = findim K V₂) : nonempty (V ≃ₗ[K] V₂) :=
nonempty_linear_equiv_of_lift_dim_eq $ by simp only [← findim_eq_dim, cond, lift_nat_cast]
/--
Two finite-dimensional vector spaces are isomorphic if and only if they have the same (finite)
dimension.
-/
theorem nonempty_linear_equiv_iff_findim_eq [finite_dimensional K V] [finite_dimensional K V₂] :
nonempty (V ≃ₗ[K] V₂) ↔ findim K V = findim K V₂ :=
⟨λ ⟨h⟩, h.findim_eq, λ h, nonempty_linear_equiv_of_findim_eq h⟩
section
variables (V V₂)
/--
Two finite-dimensional vector spaces are isomorphic if they have the same (finite) dimension.
-/
noncomputable def linear_equiv.of_findim_eq [finite_dimensional K V] [finite_dimensional K V₂]
(cond : findim K V = findim K V₂) : V ≃ₗ[K] V₂ :=
classical.choice $ nonempty_linear_equiv_of_findim_eq cond
end
lemma eq_of_le_of_findim_le {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂)
(hd : findim K S₂ ≤ findim K S₁) : S₁ = S₂ :=
begin
rw ←linear_equiv.findim_eq (submodule.comap_subtype_equiv_of_le hle) at hd,
exact le_antisymm hle (submodule.comap_subtype_eq_top.1 (eq_top_of_findim_eq
(le_antisymm (comap (submodule.subtype S₂) S₁).findim_le hd))),
end
/-- If a submodule is less than or equal to a finite-dimensional
submodule with the same dimension, they are equal. -/
lemma eq_of_le_of_findim_eq {S₁ S₂ : submodule K V} [finite_dimensional K S₂] (hle : S₁ ≤ S₂)
(hd : findim K S₁ = findim K S₂) : S₁ = S₂ :=
eq_of_le_of_findim_le hle hd.ge
variables [finite_dimensional K V] [finite_dimensional K V₂]
/-- Given isomorphic subspaces `p q` of vector spaces `V` and `V₁` respectively,
`p.quotient` is isomorphic to `q.quotient`. -/
noncomputable def linear_equiv.quot_equiv_of_equiv
{p : subspace K V} {q : subspace K V₂}
(f₁ : p ≃ₗ[K] q) (f₂ : V ≃ₗ[K] V₂) : p.quotient ≃ₗ[K] q.quotient :=
linear_equiv.of_findim_eq _ _
begin
rw [← @add_right_cancel_iff _ _ (findim K p), submodule.findim_quotient_add_findim,
linear_equiv.findim_eq f₁, submodule.findim_quotient_add_findim, linear_equiv.findim_eq f₂],
end
/-- Given the subspaces `p q`, if `p.quotient ≃ₗ[K] q`, then `q.quotient ≃ₗ[K] p` -/
noncomputable def linear_equiv.quot_equiv_of_quot_equiv
{p q : subspace K V} (f : p.quotient ≃ₗ[K] q) : q.quotient ≃ₗ[K] p :=
linear_equiv.of_findim_eq _ _
begin
rw [← @add_right_cancel_iff _ _ (findim K q), submodule.findim_quotient_add_findim,
← linear_equiv.findim_eq f, add_comm, submodule.findim_quotient_add_findim]
end
end finite_dimensional
namespace linear_map
open finite_dimensional
/-- On a finite-dimensional space, an injective linear map is surjective. -/
lemma surjective_of_injective [finite_dimensional K V] {f : V →ₗ[K] V}
(hinj : injective f) : surjective f :=
begin
have h := dim_eq_of_injective _ hinj,
rw [← findim_eq_dim, ← findim_eq_dim, nat_cast_inj] at h,
exact range_eq_top.1 (eq_top_of_findim_eq h.symm)
end
/-- On a finite-dimensional space, a linear map is injective if and only if it is surjective. -/
lemma injective_iff_surjective [finite_dimensional K V] {f : V →ₗ[K] V} :
injective f ↔ surjective f :=
⟨surjective_of_injective,
λ hsurj, let ⟨g, hg⟩ := f.exists_right_inverse_of_surjective (range_eq_top.2 hsurj) in
have function.right_inverse g f, from linear_map.ext_iff.1 hg,
(left_inverse_of_surjective_of_right_inverse
(surjective_of_injective this.injective) this).injective⟩
lemma ker_eq_bot_iff_range_eq_top [finite_dimensional K V] {f : V →ₗ[K] V} :
f.ker = ⊥ ↔ f.range = ⊤ :=
by rw [range_eq_top, ker_eq_bot, injective_iff_surjective]
/-- In a finite-dimensional space, if linear maps are inverse to each other on one side then they
are also inverse to each other on the other side. -/
lemma mul_eq_one_of_mul_eq_one [finite_dimensional K V] {f g : V →ₗ[K] V} (hfg : f * g = 1) :
g * f = 1 :=
have ginj : injective g, from has_left_inverse.injective
⟨f, (λ x, show (f * g) x = (1 : V →ₗ[K] V) x, by rw hfg; refl)⟩,
let ⟨i, hi⟩ := g.exists_right_inverse_of_surjective
(range_eq_top.2 (injective_iff_surjective.1 ginj)) in
have f * (g * i) = f * 1, from congr_arg _ hi,
by rw [← mul_assoc, hfg, one_mul, mul_one] at this; rwa ← this
/-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if
they are inverse to each other on the other side. -/
lemma mul_eq_one_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f * g = 1 ↔ g * f = 1 :=
⟨mul_eq_one_of_mul_eq_one, mul_eq_one_of_mul_eq_one⟩
/-- In a finite-dimensional space, linear maps are inverse to each other on one side if and only if
they are inverse to each other on the other side. -/
lemma comp_eq_id_comm [finite_dimensional K V] {f g : V →ₗ[K] V} : f.comp g = id ↔ g.comp f = id :=
mul_eq_one_comm
/-- The image under an onto linear map of a finite-dimensional space is also finite-dimensional. -/
lemma finite_dimensional_of_surjective [h : finite_dimensional K V]
(f : V →ₗ[K] V₂) (hf : f.range = ⊤) : finite_dimensional K V₂ :=
is_noetherian_of_surjective V f hf
/-- The range of a linear map defined on a finite-dimensional space is also finite-dimensional. -/
instance finite_dimensional_range [h : finite_dimensional K V] (f : V →ₗ[K] V₂) :
finite_dimensional K f.range :=
f.quot_ker_equiv_range.finite_dimensional
/-- rank-nullity theorem : the dimensions of the kernel and the range of a linear map add up to
the dimension of the source space. -/
theorem findim_range_add_findim_ker [finite_dimensional K V] (f : V →ₗ[K] V₂) :
findim K f.range + findim K f.ker = findim K V :=
by { rw [← f.quot_ker_equiv_range.findim_eq], exact submodule.findim_quotient_add_findim _ }
end linear_map
namespace linear_equiv
open finite_dimensional
variables [finite_dimensional K V]
/-- The linear equivalence corresponging to an injective endomorphism. -/
noncomputable def of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) : V ≃ₗ[K] V :=
(linear_equiv.of_injective f h_inj).trans
(linear_equiv.of_top _ (linear_map.ker_eq_bot_iff_range_eq_top.1 h_inj))
@[simp] lemma coe_of_injective_endo (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) :
⇑(of_injective_endo f h_inj) = f := rfl
@[simp] lemma of_injective_endo_right_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) :
f * (of_injective_endo f h_inj).symm = 1 :=
linear_map.ext $ (of_injective_endo f h_inj).apply_symm_apply
@[simp] lemma of_injective_endo_left_inv (f : V →ₗ[K] V) (h_inj : f.ker = ⊥) :
((of_injective_endo f h_inj).symm : V →ₗ[K] V) * f = 1 :=
linear_map.ext $ (of_injective_endo f h_inj).symm_apply_apply
end linear_equiv
namespace linear_map
lemma is_unit_iff [finite_dimensional K V] (f : V →ₗ[K] V): is_unit f ↔ f.ker = ⊥ :=
begin
split,
{ rintro ⟨u, rfl⟩,
exact linear_map.ker_eq_bot_of_inverse u.inv_mul },
{ intro h_inj,
exact ⟨⟨f, (linear_equiv.of_injective_endo f h_inj).symm.to_linear_map,
linear_equiv.of_injective_endo_right_inv f h_inj,
linear_equiv.of_injective_endo_left_inv f h_inj⟩, rfl⟩ }
end
end linear_map
open vector_space finite_dimensional
section top
@[simp]
theorem findim_top : findim K (⊤ : submodule K V) = findim K V :=
by { unfold findim, simp [dim_top] }
end top
lemma findim_zero_iff_forall_zero [finite_dimensional K V] :
findim K V = 0 ↔ ∀ x : V, x = 0 :=
findim_zero_iff.trans (subsingleton_iff_forall_eq 0)
lemma is_basis_of_findim_zero [finite_dimensional K V]
{ι : Type*} (h : ¬ nonempty ι) (hV : findim K V = 0) :
is_basis K (λ x : ι, (0 : V)) :=
begin
haveI : subsingleton V := findim_zero_iff.1 hV,
exact is_basis_empty _ h
end
lemma is_basis_of_findim_zero' [finite_dimensional K V]
(hV : findim K V = 0) : is_basis K (λ x : fin 0, (0 : V)) :=
is_basis_of_findim_zero (finset.univ_eq_empty.mp rfl) hV
namespace linear_map
theorem injective_iff_surjective_of_findim_eq_findim [finite_dimensional K V]
[finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} :
function.injective f ↔ function.surjective f :=
begin
have := findim_range_add_findim_ker f,
rw [← ker_eq_bot, ← range_eq_top], refine ⟨λ h, _, λ h, _⟩,
{ rw [h, findim_bot, add_zero, H] at this, exact eq_top_of_findim_eq this },
{ rw [h, findim_top, H] at this, exact findim_eq_zero.1 (add_right_injective _ this) }
end
lemma ker_eq_bot_iff_range_eq_top_of_findim_eq_findim [finite_dimensional K V]
[finite_dimensional K V₂] (H : findim K V = findim K V₂) {f : V →ₗ[K] V₂} :
f.ker = ⊥ ↔ f.range = ⊤ :=
by rw [range_eq_top, ker_eq_bot, injective_iff_surjective_of_findim_eq_findim H]
theorem findim_le_findim_of_injective [finite_dimensional K V] [finite_dimensional K V₂]
{f : V →ₗ[K] V₂} (hf : function.injective f) : findim K V ≤ findim K V₂ :=
calc findim K V
= findim K f.range + findim K f.ker : (findim_range_add_findim_ker f).symm
... = findim K f.range : by rw [ker_eq_bot.2 hf, findim_bot, add_zero]
... ≤ findim K V₂ : submodule.findim_le _
/-- Given a linear map `f` between two vector spaces with the same dimension, if
`ker f = ⊥` then `linear_equiv_of_ker_eq_bot` is the induced isomorphism
between the two vector spaces. -/
noncomputable def linear_equiv_of_ker_eq_bot
[finite_dimensional K V] [finite_dimensional K V₂]
(f : V →ₗ[K] V₂) (hf : f.ker = ⊥) (hdim : findim K V = findim K V₂) : V ≃ₗ[K] V₂ :=
linear_equiv.of_bijective f hf (linear_map.range_eq_top.2 $
(linear_map.injective_iff_surjective_of_findim_eq_findim hdim).1 (linear_map.ker_eq_bot.1 hf))
@[simp] lemma linear_equiv_of_ker_eq_bot_apply
[finite_dimensional K V] [finite_dimensional K V₂]
{f : V →ₗ[K] V₂} (hf : f.ker = ⊥) (hdim : findim K V = findim K V₂) (x : V) :
f.linear_equiv_of_ker_eq_bot hf hdim x = f x := rfl
end linear_map
namespace alg_hom
lemma bijective {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
[finite_dimensional F E] (ϕ : E →ₐ[F] E) : function.bijective ϕ :=
have inj : function.injective ϕ.to_linear_map := ϕ.to_ring_hom.injective,
⟨inj, (linear_map.injective_iff_surjective_of_findim_eq_findim rfl).mp inj⟩
end alg_hom
/-- Bijection between algebra equivalences and algebra homomorphisms -/
noncomputable def alg_equiv_equiv_alg_hom (F : Type u) [field F] (E : Type v) [field E]
[algebra F E] [finite_dimensional F E] : (E ≃ₐ[F] E) ≃ (E →ₐ[F] E) :=
{ to_fun := λ ϕ, ϕ.to_alg_hom,
inv_fun := λ ϕ, alg_equiv.of_bijective ϕ ϕ.bijective,
left_inv := λ _, by {ext, refl},
right_inv := λ _, by {ext, refl} }
section
/-- An integral domain that is module-finite as an algebra over a field is a field. -/
noncomputable def field_of_finite_dimensional (F K : Type*) [field F] [integral_domain K]
[algebra F K] [finite_dimensional F K] : field K :=
{ inv := λ x, if H : x = 0 then 0 else classical.some $
(show function.surjective (algebra.lmul_left F x), from
linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' H).1) 1,
mul_inv_cancel := λ x hx, show x * dite _ _ _ = _, by { rw dif_neg hx,
exact classical.some_spec ((show function.surjective (algebra.lmul_left F x), from
linear_map.injective_iff_surjective.1 $ λ _ _, (mul_right_inj' hx).1) 1) },
inv_zero := dif_pos rfl,
.. ‹integral_domain K› }
end
namespace submodule
lemma findim_mono [finite_dimensional K V] :
monotone (λ (s : submodule K V), findim K s) :=
λ s t hst,
calc findim K s = findim K (comap t.subtype s)
: linear_equiv.findim_eq (comap_subtype_equiv_of_le hst).symm
... ≤ findim K t : submodule.findim_le _
lemma lt_of_le_of_findim_lt_findim {s t : submodule K V}
(le : s ≤ t) (lt : findim K s < findim K t) : s < t :=
lt_of_le_of_ne le (λ h, ne_of_lt lt (by rw h))
lemma lt_top_of_findim_lt_findim {s : submodule K V}
(lt : findim K s < findim K V) : s < ⊤ :=
begin
rw ← @findim_top K V at lt,
exact lt_of_le_of_findim_lt_findim le_top lt
end
lemma findim_lt_findim_of_lt [finite_dimensional K V] {s t : submodule K V} (hst : s < t) :
findim K s < findim K t :=
begin
rw linear_equiv.findim_eq (comap_subtype_equiv_of_le (le_of_lt hst)).symm,
refine findim_lt (lt_of_le_of_ne le_top _),
intro h_eq_top,
rw comap_subtype_eq_top at h_eq_top,
apply not_le_of_lt hst h_eq_top,
end
lemma findim_add_eq_of_is_compl
[finite_dimensional K V] {U W : submodule K V} (h : is_compl U W) :
findim K U + findim K W = findim K V :=
begin
rw [← submodule.dim_sup_add_dim_inf_eq, top_le_iff.1 h.2, le_bot_iff.1 h.1,
findim_bot, add_zero],
exact findim_top
end
end submodule
section span
open submodule
lemma findim_span_le_card (s : set V) [fin : fintype s] :
findim K (span K s) ≤ s.to_finset.card :=
begin
haveI := span_of_finite K ⟨fin⟩,
have : dim K (span K s) ≤ (mk s : cardinal) := dim_span_le s,
rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this,
exact_mod_cast this
end
lemma findim_span_eq_card {ι : Type*} [fintype ι] {b : ι → V}
(hb : linear_independent K b) :
findim K (span K (set.range b)) = fintype.card ι :=
begin
haveI : finite_dimensional K (span K (set.range b)) := span_of_finite K (set.finite_range b),
have : dim K (span K (set.range b)) = (mk (set.range b) : cardinal) := dim_span hb,
rwa [←findim_eq_dim, ←lift_inj, mk_range_eq_of_injective hb.injective,
cardinal.fintype_card, lift_nat_cast, lift_nat_cast, nat_cast_inj] at this,
end
lemma findim_span_set_eq_card (s : set V) [fin : fintype s]
(hs : linear_independent K (coe : s → V)) :
findim K (span K s) = s.to_finset.card :=
begin
haveI := span_of_finite K ⟨fin⟩,
have : dim K (span K s) = (mk s : cardinal) := dim_span_set hs,
rw [←findim_eq_dim, cardinal.fintype_card, ←set.to_finset_card] at this,
exact_mod_cast this
end
lemma span_lt_of_subset_of_card_lt_findim {s : set V} [fintype s] {t : submodule K V}
(subset : s ⊆ t) (card_lt : s.to_finset.card < findim K t) : span K s < t :=
lt_of_le_of_findim_lt_findim (span_le.mpr subset) (lt_of_le_of_lt (findim_span_le_card _) card_lt)
lemma span_lt_top_of_card_lt_findim {s : set V} [fintype s]
(card_lt : s.to_finset.card < findim K V) : span K s < ⊤ :=
lt_top_of_findim_lt_findim (lt_of_le_of_lt (findim_span_le_card _) card_lt)
lemma findim_span_singleton {v : V} (hv : v ≠ 0) : findim K (K ∙ v) = 1 :=
begin
apply le_antisymm,
{ exact findim_span_le_card ({v} : set V) },
{ rw [nat.succ_le_iff, findim_pos_iff],
use [⟨v, mem_span_singleton_self v⟩, 0],
simp [hv] }
end
end span
section is_basis
lemma linear_independent_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V}
(span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) :
linear_independent K b :=
linear_independent_iff'.mpr $ λ s g dependent i i_mem_s,
begin
by_contra gx_ne_zero,
-- We'll derive a contradiction by showing `b '' (univ \ {i})` of cardinality `n - 1`
-- spans a vector space of dimension `n`.
refine ne_of_lt (span_lt_top_of_card_lt_findim
(show (b '' (set.univ \ {i})).to_finset.card < findim K V, from _)) _,
{ calc (b '' (set.univ \ {i})).to_finset.card = ((set.univ \ {i}).to_finset.image b).card
: by rw [set.to_finset_card, fintype.card_of_finset]
... ≤ (set.univ \ {i}).to_finset.card : finset.card_image_le
... = (finset.univ.erase i).card : congr_arg finset.card (finset.ext (by simp [and_comm]))
... < finset.univ.card : finset.card_erase_lt_of_mem (finset.mem_univ i)
... = findim K V : card_eq },
-- We already have that `b '' univ` spans the whole space,
-- so we only need to show that the span of `b '' (univ \ {i})` contains each `b j`.
refine trans (le_antisymm (span_mono (set.image_subset_range _ _)) (span_le.mpr _)) span_eq,
rintros _ ⟨j, rfl, rfl⟩,
-- The case that `j ≠ i` is easy because `b j ∈ b '' (univ \ {i})`.
by_cases j_eq : j = i,
swap,
{ refine subset_span ⟨j, (set.mem_diff _).mpr ⟨set.mem_univ _, _⟩, rfl⟩,
exact mt set.mem_singleton_iff.mp j_eq },
-- To show `b i ∈ span (b '' (univ \ {i}))`, we use that it's a weighted sum
-- of the other `b j`s.
rw [j_eq, mem_coe, show b i = -((g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)), from _],
{ refine submodule.neg_mem _ (smul_mem _ _ (sum_mem _ (λ k hk, _))),
obtain ⟨k_ne_i, k_mem⟩ := finset.mem_erase.mp hk,
refine smul_mem _ _ (subset_span ⟨k, _, rfl⟩),
simpa using k_mem },
-- To show `b i` is a weighted sum of the other `b j`s, we'll rewrite this sum
-- to have the form of the assumption `dependent`.
apply eq_neg_of_add_eq_zero,
calc b i + (g i)⁻¹ • (s.erase i).sum (λ j, g j • b j)
= (g i)⁻¹ • (g i • b i + (s.erase i).sum (λ j, g j • b j))
: by rw [smul_add, ←mul_smul, inv_mul_cancel gx_ne_zero, one_smul]
... = (g i)⁻¹ • 0 : congr_arg _ _
... = 0 : smul_zero _,
-- And then it's just a bit of manipulation with finite sums.
rwa [← finset.insert_erase i_mem_s, finset.sum_insert (finset.not_mem_erase _ _)] at dependent
end
/-- A finite family of vectors is linearly independent if and only if
its cardinality equals the dimension of its span. -/
lemma linear_independent_iff_card_eq_findim_span {ι : Type*} [fintype ι] {b : ι → V} :
linear_independent K b ↔ fintype.card ι = findim K (span K (set.range b)) :=
begin
split,
{ intro h,
exact (findim_span_eq_card h).symm },
{ intro hc,
let f := (submodule.subtype (span K (set.range b))),
let b' : ι → span K (set.range b) :=
λ i, ⟨b i, mem_span.2 (λ p hp, hp (set.mem_range_self _))⟩,
have hs : span K (set.range b') = ⊤,
{ rw eq_top_iff',
intro x,
have h : span K (f '' (set.range b')) = map f (span K (set.range b')) := span_image f,
have hf : f '' (set.range b') = set.range b, { ext x, simp [set.mem_image, set.mem_range] },
rw hf at h,
have hx : (x : V) ∈ span K (set.range b) := x.property,
conv at hx { congr, skip, rw h },
simpa [mem_map] using hx },
have hi : f.ker = ⊥ := ker_subtype _,
convert (linear_independent_of_span_eq_top_of_card_eq_findim hs hc).map' _ hi }
end
lemma is_basis_of_span_eq_top_of_card_eq_findim {ι : Type*} [fintype ι] {b : ι → V}
(span_eq : span K (set.range b) = ⊤) (card_eq : fintype.card ι = findim K V) :
is_basis K b :=
⟨linear_independent_of_span_eq_top_of_card_eq_findim span_eq card_eq, span_eq⟩
lemma finset_is_basis_of_span_eq_top_of_card_eq_findim {s : finset V}
(span_eq : span K (↑s : set V) = ⊤) (card_eq : s.card = findim K V) :
is_basis K (coe : (↑s : set V) → V) :=
is_basis_of_span_eq_top_of_card_eq_findim
((@subtype.range_coe_subtype _ (λ x, x ∈ s)).symm ▸ span_eq)
(trans (fintype.card_coe _) card_eq)
lemma set_is_basis_of_span_eq_top_of_card_eq_findim {s : set V} [fintype s]
(span_eq : span K s = ⊤) (card_eq : s.to_finset.card = findim K V) :
is_basis K (λ (x : s), (x : V)) :=
is_basis_of_span_eq_top_of_card_eq_findim
((@subtype.range_coe_subtype _ s).symm ▸ span_eq)
(trans s.to_finset_card.symm card_eq)
lemma span_eq_top_of_linear_independent_of_card_eq_findim
{ι : Type*} [hι : nonempty ι] [fintype ι] {b : ι → V}
(lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) :
span K (set.range b) = ⊤ :=
begin
by_cases fin : (finite_dimensional K V),
{ haveI := fin,
by_contra ne_top,
have lt_top : span K (set.range b) < ⊤ := lt_of_le_of_ne le_top ne_top,
exact ne_of_lt (submodule.findim_lt lt_top) (trans (findim_span_eq_card lin_ind) card_eq) },
{ exfalso,
apply ne_of_lt (fintype.card_pos_iff.mpr hι),
symmetry,
calc fintype.card ι = findim K V : card_eq
... = 0 : dif_neg (mt finite_dimensional_iff_dim_lt_omega.mpr fin) }
end
lemma is_basis_of_linear_independent_of_card_eq_findim
{ι : Type*} [nonempty ι] [fintype ι] {b : ι → V}
(lin_ind : linear_independent K b) (card_eq : fintype.card ι = findim K V) :
is_basis K b :=
⟨lin_ind, span_eq_top_of_linear_independent_of_card_eq_findim lin_ind card_eq⟩
lemma finset_is_basis_of_linear_independent_of_card_eq_findim
{s : finset V} (hs : s.nonempty)
(lin_ind : linear_independent K (coe : (↑s : set V) → V)) (card_eq : s.card = findim K V) :
is_basis K (coe : (↑s : set V) → V) :=
@is_basis_of_linear_independent_of_card_eq_findim _ _ _ _ _ _
⟨(⟨hs.some, hs.some_spec⟩ : (↑s : set V))⟩ _ _
lin_ind
(trans (fintype.card_coe _) card_eq)
lemma set_is_basis_of_linear_independent_of_card_eq_findim
{s : set V} [nonempty s] [fintype s]
(lin_ind : linear_independent K (coe : s → V)) (card_eq : s.to_finset.card = findim K V) :
is_basis K (coe : s → V) :=
is_basis_of_linear_independent_of_card_eq_findim lin_ind (trans s.to_finset_card.symm card_eq)
end is_basis
section subalgebra_dim
open vector_space
variables {F E : Type*} [field F] [field E] [algebra F E]
lemma subalgebra.dim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : dim F S = 1 :=
begin
rw [← S.to_submodule_equiv.dim_eq, h,
(linear_equiv.of_eq ↑(⊥ : subalgebra F E) _ algebra.to_submodule_bot).dim_eq, dim_span_set],
exacts [mk_singleton _, linear_independent_singleton one_ne_zero]
end
@[simp]
lemma subalgebra.dim_bot : dim F (⊥ : subalgebra F E) = 1 :=
subalgebra.dim_eq_one_of_eq_bot rfl
lemma subalgebra_top_dim_eq_submodule_top_dim :
dim F (⊤ : subalgebra F E) = dim F (⊤ : submodule F E) :=
by { rw ← algebra.coe_top, refl }
lemma subalgebra_top_findim_eq_submodule_top_findim :
findim F (⊤ : subalgebra F E) = findim F (⊤ : submodule F E) :=
by { rw ← algebra.coe_top, refl }
lemma subalgebra.dim_top : dim F (⊤ : subalgebra F E) = dim F E :=
by { rw subalgebra_top_dim_eq_submodule_top_dim, exact dim_top }
lemma subalgebra.finite_dimensional_bot : finite_dimensional F (⊥ : subalgebra F E) :=
finite_dimensional_of_dim_eq_one subalgebra.dim_bot
@[simp]
lemma subalgebra.findim_bot : findim F (⊥ : subalgebra F E) = 1 :=
begin
haveI : finite_dimensional F (⊥ : subalgebra F E) := subalgebra.finite_dimensional_bot,
have : dim F (⊥ : subalgebra F E) = 1 := subalgebra.dim_bot,
rw ← findim_eq_dim at this,
norm_cast at *,
simp *,
end
lemma subalgebra.findim_eq_one_of_eq_bot {S : subalgebra F E} (h : S = ⊥) : findim F S = 1 :=
by { rw h, exact subalgebra.findim_bot }
lemma subalgebra.eq_bot_of_findim_one {S : subalgebra F E} (h : findim F S = 1) : S = ⊥ :=
begin
rw eq_bot_iff,
let b : set S := {1},
have : fintype b := unique.fintype,
have b_lin_ind : linear_independent F (coe : b → S) := linear_independent_singleton one_ne_zero,
have b_card : fintype.card b = 1 := fintype.card_of_subsingleton _,
obtain ⟨_, b_spans⟩ := set_is_basis_of_linear_independent_of_card_eq_findim
b_lin_ind (by simp only [*, set.to_finset_card]),
intros x hx,
rw [subalgebra.mem_coe, algebra.mem_bot],
have x_in_span_b : (⟨x, hx⟩ : S) ∈ submodule.span F b,
{ rw subtype.range_coe at b_spans,
rw b_spans,
exact submodule.mem_top, },
obtain ⟨a, ha⟩ := submodule.mem_span_singleton.mp x_in_span_b,
replace ha : a • 1 = x := by injections with ha,
exact ⟨a, by rw [← ha, algebra.smul_def, mul_one]⟩,
end
lemma subalgebra.eq_bot_of_dim_one {S : subalgebra F E} (h : dim F S = 1) : S = ⊥ :=
begin
haveI : finite_dimensional F S := finite_dimensional_of_dim_eq_one h,
rw ← findim_eq_dim at h,
norm_cast at h,
exact subalgebra.eq_bot_of_findim_one h,
end
@[simp]
lemma subalgebra.bot_eq_top_of_dim_eq_one (h : dim F E = 1) : (⊥ : subalgebra F E) = ⊤ :=
begin
rw [← dim_top, ← subalgebra_top_dim_eq_submodule_top_dim] at h,
exact eq.symm (subalgebra.eq_bot_of_dim_one h),
end
@[simp]
lemma subalgebra.bot_eq_top_of_findim_eq_one (h : findim F E = 1) : (⊥ : subalgebra F E) = ⊤ :=
begin
rw [← findim_top, ← subalgebra_top_findim_eq_submodule_top_findim] at h,
exact eq.symm (subalgebra.eq_bot_of_findim_one h),
end
@[simp]
theorem subalgebra.dim_eq_one_iff {S : subalgebra F E} : dim F S = 1 ↔ S = ⊥ :=
⟨subalgebra.eq_bot_of_dim_one, subalgebra.dim_eq_one_of_eq_bot⟩
@[simp]
theorem subalgebra.findim_eq_one_iff {S : subalgebra F E} : findim F S = 1 ↔ S = ⊥ :=
⟨subalgebra.eq_bot_of_findim_one, subalgebra.findim_eq_one_of_eq_bot⟩
end subalgebra_dim
namespace module
namespace End
lemma exists_ker_pow_eq_ker_pow_succ [finite_dimensional K V] (f : End K V) :
∃ (k : ℕ), k ≤ findim K V ∧ (f ^ k).ker = (f ^ k.succ).ker :=
begin
classical,
by_contradiction h_contra,
simp_rw [not_exists, not_and] at h_contra,
have h_le_ker_pow : ∀ (n : ℕ), n ≤ (findim K V).succ → n ≤ findim K (f ^ n).ker,
{ intros n hn,
induction n with n ih,
{ exact zero_le (findim _ _) },
{ have h_ker_lt_ker : (f ^ n).ker < (f ^ n.succ).ker,
{ refine lt_of_le_of_ne _ (h_contra n (nat.le_of_succ_le_succ hn)),
rw pow_succ,
apply linear_map.ker_le_ker_comp },
have h_findim_lt_findim : findim K (f ^ n).ker < findim K (f ^ n.succ).ker,
{ apply submodule.findim_lt_findim_of_lt h_ker_lt_ker },
calc
n.succ ≤ (findim K ↥(linear_map.ker (f ^ n))).succ :
nat.succ_le_succ (ih (nat.le_of_succ_le hn))
... ≤ findim K ↥(linear_map.ker (f ^ n.succ)) :
nat.succ_le_of_lt h_findim_lt_findim } },
have h_le_findim_V : ∀ n, findim K (f ^ n).ker ≤ findim K V :=
λ n, submodule.findim_le _,
have h_any_n_lt: ∀ n, n ≤ (findim K V).succ → n ≤ findim K V :=
λ n hn, (h_le_ker_pow n hn).trans (h_le_findim_V n),
show false,
from nat.not_succ_le_self _ (h_any_n_lt (findim K V).succ (findim K V).succ.le_refl),
end
lemma ker_pow_constant {f : End K V} {k : ℕ} (h : (f ^ k).ker = (f ^ k.succ).ker) :
∀ m, (f ^ k).ker = (f ^ (k + m)).ker
| 0 := by simp
| (m + 1) :=
begin
apply le_antisymm,
{ rw [add_comm, pow_add],
apply linear_map.ker_le_ker_comp },
{ rw [ker_pow_constant m, add_comm m 1, ←add_assoc, pow_add, pow_add f k m],
change linear_map.ker ((f ^ (k + 1)).comp (f ^ m)) ≤ linear_map.ker ((f ^ k).comp (f ^ m)),
rw [linear_map.ker_comp, linear_map.ker_comp, h, nat.add_one],
exact le_refl _, }
end
lemma ker_pow_eq_ker_pow_findim_of_le [finite_dimensional K V]
{f : End K V} {m : ℕ} (hm : findim K V ≤ m) :
(f ^ m).ker = (f ^ findim K V).ker :=
begin
obtain ⟨k, h_k_le, hk⟩ :
∃ k, k ≤ findim K V ∧ linear_map.ker (f ^ k) = linear_map.ker (f ^ k.succ) :=
exists_ker_pow_eq_ker_pow_succ f,
calc (f ^ m).ker = (f ^ (k + (m - k))).ker :
by rw nat.add_sub_of_le (h_k_le.trans hm)
... = (f ^ k).ker : by rw ker_pow_constant hk _
... = (f ^ (k + (findim K V - k))).ker : ker_pow_constant hk (findim K V - k)
... = (f ^ findim K V).ker : by rw nat.add_sub_of_le h_k_le
end
lemma ker_pow_le_ker_pow_findim [finite_dimensional K V] (f : End K V) (m : ℕ) :
(f ^ m).ker ≤ (f ^ findim K V).ker :=
begin
by_cases h_cases: m < findim K V,
{ rw [←nat.add_sub_of_le (nat.le_of_lt h_cases), add_comm, pow_add],
apply linear_map.ker_le_ker_comp },
{ rw [ker_pow_eq_ker_pow_findim_of_le (le_of_not_lt h_cases)],
exact le_refl _ }
end
end End
end module
|
0736907eede25cdab23caa7bdef82ecbb4056c17 | 38bf3fd2bb651ab70511408fcf70e2029e2ba310 | /src/category_theory/yoneda.lean | 3cce67c690e0313ad497b8806bda955e1a82284f | [
"Apache-2.0"
] | permissive | JaredCorduan/mathlib | 130392594844f15dad65a9308c242551bae6cd2e | d5de80376088954d592a59326c14404f538050a1 | refs/heads/master | 1,595,862,206,333 | 1,570,816,457,000 | 1,570,816,457,000 | 209,134,499 | 0 | 0 | Apache-2.0 | 1,568,746,811,000 | 1,568,746,811,000 | null | UTF-8 | Lean | false | false | 7,518 | 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.opposites
import category_theory.hom_functor
/-!
# The Yoneda embedding
The Yoneda embedding as a functor `yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁)`,
along with an instance that it is `fully_faithful`.
Also the Yoneda lemma, `yoneda_lemma : (yoneda_pairing C) ≅ (yoneda_evaluation C)`.
-/
namespace category_theory
open opposite
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
variables {C : Type u₁} [𝒞 : category.{v₁} C]
include 𝒞
def yoneda : C ⥤ (Cᵒᵖ ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop Y ⟶ X,
map := λ Y Y' f g, f.unop ≫ g,
map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext1, dsimp, erw [category.id_comp] end },
map := λ X X' f, { app := λ Y g, g ≫ f } }
def coyoneda : Cᵒᵖ ⥤ (C ⥤ Type v₁) :=
{ obj := λ X,
{ obj := λ Y, unop X ⟶ Y,
map := λ Y Y' f g, g ≫ f,
map_comp' := λ _ _ _ f g, begin ext1, dsimp, erw [category.assoc] end,
map_id' := λ Y, begin ext1, dsimp, erw [category.comp_id] end },
map := λ X X' f, { app := λ Y g, f.unop ≫ g },
map_comp' := λ _ _ _ f g, begin ext1, ext1, dsimp, erw [category.assoc] end,
map_id' := λ X, begin ext1, ext1, dsimp, erw [category.id_comp] end }
namespace yoneda
@[simp] lemma obj_obj (X : C) (Y : Cᵒᵖ) : (yoneda.obj X).obj Y = (unop Y ⟶ X) := rfl
@[simp] lemma obj_map (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') :
(yoneda.obj X).map f = λ g, f.unop ≫ g := rfl
@[simp] lemma map_app {X X' : C} (f : X ⟶ X') (Y : Cᵒᵖ) :
(yoneda.map f).app Y = λ g, g ≫ f := rfl
lemma obj_map_id {X Y : C} (f : op X ⟶ op Y) :
((@yoneda C _).obj X).map f (𝟙 X) = ((@yoneda C _).map f.unop).app (op Y) (𝟙 Y) :=
by obviously
@[simp] lemma naturality {X Y : C} (α : yoneda.obj X ⟶ yoneda.obj Y)
{Z Z' : C} (f : Z ⟶ Z') (h : Z' ⟶ X) : f ≫ α.app (op Z') h = α.app (op Z) (f ≫ h) :=
begin erw [functor_to_types.naturality], refl end
instance yoneda_full : full (@yoneda C _) :=
{ preimage := λ X Y f, (f.app (op X)) (𝟙 X) }
instance yoneda_faithful : faithful (@yoneda C _) :=
{ injectivity' := λ X Y f g p,
begin
injection p with h,
convert (congr_fun (congr_fun h (op X)) (𝟙 X)); dsimp; simp,
end }
/-- Extensionality via Yoneda. The typical usage would be
```
-- Goal is `X ≅ Y`
apply yoneda.ext,
-- Goals are now functions `(Z ⟶ X) → (Z ⟶ Y)`, `(Z ⟶ Y) → (Z ⟶ X)`, and the fact that these
functions are inverses and natural in `Z`.
```
-/
def ext (X Y : C)
(p : Π {Z : C}, (Z ⟶ X) → (Z ⟶ Y)) (q : Π {Z : C}, (Z ⟶ Y) → (Z ⟶ X))
(h₁ : Π {Z : C} (f : Z ⟶ X), q (p f) = f) (h₂ : Π {Z : C} (f : Z ⟶ Y), p (q f) = f)
(n : Π {Z Z' : C} (f : Z' ⟶ Z) (g : Z ⟶ X), p (f ≫ g) = f ≫ p g) : X ≅ Y :=
@preimage_iso _ _ _ _ yoneda _ _ _ _
(nat_iso.of_components (λ Z, { hom := p, inv := q, }) (by tidy))
def is_iso {X Y : C} (f : X ⟶ Y) [is_iso (yoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful yoneda f
end yoneda
namespace coyoneda
@[simp] lemma obj_obj (X : Cᵒᵖ) (Y : C) : (coyoneda.obj X).obj Y = (unop X ⟶ Y) := rfl
@[simp] lemma obj_map {X' X : C} (f : X' ⟶ X) (Y : Cᵒᵖ) :
(coyoneda.obj Y).map f = λ g, g ≫ f := rfl
@[simp] lemma map_app (X : C) {Y Y' : Cᵒᵖ} (f : Y ⟶ Y') :
(coyoneda.map f).app X = λ g, f.unop ≫ g := rfl
@[simp] lemma naturality {X Y : Cᵒᵖ} (α : coyoneda.obj X ⟶ coyoneda.obj Y)
{Z Z' : C} (f : Z' ⟶ Z) (h : unop X ⟶ Z') : (α.app Z' h) ≫ f = α.app Z (h ≫ f) :=
begin erw [functor_to_types.naturality], refl end
instance coyoneda_full : full (@coyoneda C _) :=
{ preimage := λ X Y f, ((f.app (unop X)) (𝟙 _)).op }
instance coyoneda_faithful : faithful (@coyoneda C _) :=
{ injectivity' := λ X Y f g p,
begin
injection p with h,
have t := (congr_fun (congr_fun h (unop X)) (𝟙 _)),
simpa using congr_arg has_hom.hom.op t,
end }
def is_iso {X Y : Cᵒᵖ} (f : X ⟶ Y) [is_iso (coyoneda.map f)] : is_iso f :=
is_iso_of_fully_faithful coyoneda f
end coyoneda
class representable (F : Cᵒᵖ ⥤ Type v₁) :=
(X : C)
(w : yoneda.obj X ≅ F)
end category_theory
namespace category_theory
-- For the rest of the file, we are using product categories,
-- so need to restrict to the case morphisms are in 'Type', not 'Sort'.
universes v₁ u₁ u₂ -- declare the `v`'s first; see `category_theory.category` for an explanation
open opposite
variables (C : Type u₁) [𝒞 : category.{v₁} C]
include 𝒞
-- We need to help typeclass inference with some awkward universe levels here.
instance prod_category_instance_1 : category ((Cᵒᵖ ⥤ Type v₁) × Cᵒᵖ) :=
category_theory.prod.{(max u₁ v₁) v₁} (Cᵒᵖ ⥤ Type v₁) Cᵒᵖ
instance prod_category_instance_2 : category (Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) :=
category_theory.prod.{v₁ (max u₁ v₁)} Cᵒᵖ (Cᵒᵖ ⥤ Type v₁)
open yoneda
def yoneda_evaluation : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
evaluation_uncurried Cᵒᵖ (Type v₁) ⋙ ulift_functor.{u₁}
@[simp] lemma yoneda_evaluation_map_down
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (x : (yoneda_evaluation C).obj P) :
((yoneda_evaluation C).map α x).down = α.2.app Q.1 (P.2.map α.1 x.down) := rfl
def yoneda_pairing : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁) ⥤ Type (max u₁ v₁) :=
functor.prod yoneda.op (𝟭 (Cᵒᵖ ⥤ Type v₁)) ⋙ functor.hom (Cᵒᵖ ⥤ Type v₁)
@[simp] lemma yoneda_pairing_map
(P Q : Cᵒᵖ × (Cᵒᵖ ⥤ Type v₁)) (α : P ⟶ Q) (β : (yoneda_pairing C).obj P) :
(yoneda_pairing C).map α β = yoneda.map α.1.unop ≫ β ≫ α.2 := rfl
def yoneda_lemma : yoneda_pairing C ≅ yoneda_evaluation C :=
{ hom :=
{ app := λ F x, ulift.up ((x.app F.1) (𝟙 (unop F.1))),
naturality' :=
begin
intros X Y f, ext1, ext1,
cases f, cases Y, cases X,
dsimp,
erw [category.id_comp,
←functor_to_types.naturality,
obj_map_id,
functor_to_types.naturality,
functor_to_types.map_id]
end },
inv :=
{ app := λ F x,
{ app := λ X a, (F.2.map a.op) x.down,
naturality' :=
begin
intros X Y f, ext1,
cases x, cases F,
dsimp,
erw [functor_to_types.map_comp]
end },
naturality' :=
begin
intros X Y f, ext1, ext1, ext1,
cases x, cases f, cases Y, cases X,
dsimp,
erw [←functor_to_types.naturality, functor_to_types.map_comp]
end },
hom_inv_id' :=
begin
ext1, ext1, ext1, ext1, cases X, dsimp,
erw [←functor_to_types.naturality,
obj_map_id,
functor_to_types.naturality,
functor_to_types.map_id],
refl,
end,
inv_hom_id' :=
begin
ext1, ext1, ext1,
cases x, cases X,
dsimp,
erw [functor_to_types.map_id]
end }.
variables {C}
@[simp] def yoneda_sections (X : C) (F : Cᵒᵖ ⥤ Type v₁) :
(yoneda.obj X ⟶ F) ≅ ulift.{u₁} (F.obj (op X)) :=
(yoneda_lemma C).app (op X, F)
omit 𝒞
@[simp] def yoneda_sections_small {C : Type u₁} [small_category C] (X : C) (F : Cᵒᵖ ⥤ Type u₁) :
(yoneda.obj X ⟶ F) ≅ F.obj (op X) :=
yoneda_sections X F ≪≫ ulift_trivial _
end category_theory
|
e56b72e132ed4c55e7085069e4963a7cde605bbb | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/data/set/equinumerosity.lean | 93a64198cc3281380cbfc1fa7176f765427c9ee3 | [
"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 | 8,911 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Two sets are equinumerous, or equipollent, if there is a bijection between them. It is sometimes
said that two such sets "have the same cardinality."
-/
import .classical_inverse data.nat
open eq.ops classical nat
/- two versions of Cantor's theorem -/
namespace set
variables {X : Type} {A : set X}
theorem not_surj_on_pow (f : X → set X) : ¬ surj_on f A (𝒫 A) :=
let diag := {x ∈ A | x ∉ f x} in
have diag ⊆ A, from sep_subset _ _,
assume H : surj_on f A (𝒫 A),
obtain x [(xA : x ∈ A) (Hx : f x = diag)], from H `diag ⊆ A`,
have x ∉ f x, from
suppose x ∈ f x,
have x ∈ diag, from Hx ▸ this,
have x ∉ f x, from and.right this,
show false, from this `x ∈ f x`,
have x ∈ diag, from and.intro xA this,
have x ∈ f x, from Hx⁻¹ ▸ this,
show false, from `x ∉ f x` this
theorem not_inj_on_pow {f : set X → X} (H : maps_to f (𝒫 A) A) : ¬ inj_on f (𝒫 A) :=
let diag := f ' {x ∈ 𝒫 A | f x ∉ x} in
have diag ⊆ A, from image_subset_of_maps_to_of_subset H (sep_subset _ _),
assume H₁ : inj_on f (𝒫 A),
have f diag ∈ diag, from by_contradiction
(suppose f diag ∉ diag,
have diag ∈ {x ∈ 𝒫 A | f x ∉ x}, from and.intro `diag ⊆ A` this,
have f diag ∈ diag, from mem_image_of_mem f this,
show false, from `f diag ∉ diag` this),
obtain x [(Hx : x ∈ 𝒫 A ∧ f x ∉ x) (fxeq : f x = f diag)], from this,
have x = diag, from H₁ (and.left Hx) `diag ⊆ A` fxeq,
have f diag ∉ diag, from this ▸ and.right Hx,
show false, from this `f diag ∈ diag`
end set
/-
The Schröder-Bernstein theorem. The proof below is nonconstructive, in three ways:
(1) We need a left inverse to g (we could get around this by supplying one).
(2) The definition of h below assumes that membership in Union U is decidable.
(3) We ultimately case split on whether B is empty, and choose an element if it isn't.
Rather than mark every auxiliary construction as "private", we put them all in a
separate namespace.
-/
namespace schroeder_bernstein
section
open set
parameters {X Y : Type}
parameter {A : set X}
parameter {B : set Y}
parameter {f : X → Y}
parameter (f_maps_to : maps_to f A B)
parameter (finj : inj_on f A)
parameter {g : Y → X}
parameter (g_maps_to : maps_to g B A)
parameter (ginj : inj_on g B)
parameter {dflt : Y} -- for now, assume B is nonempty
parameter (dfltB : dflt ∈ B)
/- g⁻¹ : A → B -/
noncomputable definition ginv : X → Y := inv_fun g B dflt
lemma ginv_maps_to : maps_to ginv A B :=
maps_to_inv_fun dfltB
lemma ginv_g_eq {b : Y} (bB : b ∈ B) : ginv (g b) = b :=
left_inv_on_inv_fun_of_inj_on dflt ginj bB
/- define a sequence of sets U -/
definition U : ℕ → set X
| U 0 := A \ (g ' B)
| U (n + 1) := g ' (f ' (U n))
lemma U_subset_A : ∀ n, U n ⊆ A
| 0 := show U 0 ⊆ A,
from diff_subset _ _
| (n + 1) := have f ' (U n) ⊆ B,
from image_subset_of_maps_to_of_subset f_maps_to (U_subset_A n),
show U (n + 1) ⊆ A,
from image_subset_of_maps_to_of_subset g_maps_to this
lemma g_ginv_eq {a : X} (aA : a ∈ A) (anU : a ∉ Union U) : g (ginv a) = a :=
using ginj,
have a ∈ g ' B, from by_contradiction
(suppose a ∉ g ' B,
have a ∈ U 0, from and.intro aA this,
have a ∈ Union U, from exists.intro 0 this,
show false, from anU this),
obtain b [(bB : b ∈ B) (gbeq : g b = a)], from this,
calc
g (ginv a) = g (ginv (g b)) : gbeq
... = g b : ginv_g_eq bB
... = a : gbeq
/- h : A → B -/
noncomputable definition h x := if x ∈ Union U then f x else ginv x
lemma h_maps_to : maps_to h A B :=
using f_maps_to dfltB,
take a,
suppose a ∈ A,
show h a ∈ B, from
by_cases
(suppose a ∈ Union U,
begin rewrite [↑h, if_pos this], exact f_maps_to `a ∈ A` end)
(suppose a ∉ Union U,
begin rewrite [↑h, if_neg this], exact ginv_maps_to `a ∈ A` end)
/- h is injective -/
lemma aux {a₁ a₂ : X} (H₁ : a₁ ∈ Union U) (a₂A : a₂ ∈ A) (heq : h a₁ = h a₂) : a₂ ∈ Union U :=
using ginj,
obtain n (a₁Un : a₁ ∈ U n), from H₁,
have ha₁eq : h a₁ = f a₁,
from dif_pos H₁,
show a₂ ∈ Union U, from by_contradiction
(suppose a₂ ∉ Union U,
have ha₂eq : h a₂ = ginv a₂,
from dif_neg this,
have g (f a₁) = a₂, from calc
g (f a₁) = g (h a₁) : ha₁eq
... = g (h a₂) : heq
... = g (ginv a₂) : ha₂eq
... = a₂ : g_ginv_eq a₂A `a₂ ∉ Union U`,
have g (f a₁) ∈ g ' (f ' (U n)),
from mem_image_of_mem g (mem_image_of_mem f a₁Un),
have a₂ ∈ U (n + 1),
from `g (f a₁) = a₂` ▸ this,
have a₂ ∈ Union U,
from exists.intro _ this,
show false, from `a₂ ∉ Union U` `a₂ ∈ Union U`)
lemma h_inj : inj_on h A :=
take a₁ a₂,
suppose a₁ ∈ A,
suppose a₂ ∈ A,
assume heq : h a₁ = h a₂,
show a₁ = a₂, from
by_cases
(assume a₁UU : a₁ ∈ Union U,
have a₂UU : a₂ ∈ Union U,
from aux a₁UU `a₂ ∈ A` heq,
have f a₁ = f a₂, from calc
f a₁ = h a₁ : dif_pos a₁UU
... = h a₂ : heq
... = f a₂ : dif_pos a₂UU,
show a₁ = a₂, from
finj `a₁ ∈ A` `a₂ ∈ A` this)
(assume a₁nUU : a₁ ∉ Union U,
have a₂nUU : a₂ ∉ Union U,
from assume H, a₁nUU (aux H `a₁ ∈ A` heq⁻¹),
have eq₁ : g (ginv a₁) = a₁, from g_ginv_eq `a₁ ∈ A` a₁nUU,
have eq₂ : g (ginv a₂) = a₂, from g_ginv_eq `a₂ ∈ A` a₂nUU,
have ginv a₁ = ginv a₂, from calc
ginv a₁ = h a₁ : dif_neg a₁nUU
... = h a₂ : heq
... = ginv a₂ : dif_neg a₂nUU,
show a₁ = a₂, from calc
a₁ = g (ginv a₁) : eq₁ -- g_ginv_eq `a₁ ∈ A` a₁nUU
... = g (ginv a₂) : this
... = a₂ : eq₂) -- g_ginv_eq `a₂ ∈ A` a₂nUU)
/- h is surjective -/
lemma h_surj : surj_on h A B :=
take b,
suppose b ∈ B,
using f_maps_to,
by_cases
(suppose g b ∈ Union U,
obtain n (gbUn : g b ∈ U n), from this,
begin
cases n with n,
{have g b ∈ U 0, from gbUn,
have g b ∉ g ' B, from and.right this,
have g b ∈ g ' B, from mem_image_of_mem g `b ∈ B`,
show b ∈ h ' A, from absurd `g b ∈ g ' B` `g b ∉ g ' B`},
{have g b ∈ U (succ n), from gbUn,
have g b ∈ g ' (f ' (U n)), from this,
obtain b' [(b'fUn : b' ∈ f ' (U n)) (geq : g b' = g b)], from this,
obtain a [(aUn : a ∈ U n) (faeq : f a = b')], from b'fUn,
have g (f a) = g b, by rewrite [faeq, geq],
have a ∈ A, from U_subset_A n aUn,
have f a ∈ B, from f_maps_to this,
have f a = b, from ginj `f a ∈ B` `b ∈ B` `g (f a) = g b`,
have a ∈ Union U, from exists.intro n aUn,
have h a = f a, from dif_pos this,
show b ∈ h ' A, from mem_image `a ∈ A` (`h a = f a` ⬝ `f a = b`)}
end)
(suppose g b ∉ Union U,
have eq₁ : h (g b) = ginv (g b), from dif_neg this,
have eq₂ : ginv (g b) = b, from ginv_g_eq `b ∈ B`,
have g b ∈ A, from g_maps_to `b ∈ B`,
show b ∈ h ' A, from mem_image `g b ∈ A` (eq₁ ⬝ eq₂))
end
end schroeder_bernstein
namespace set
section
parameters {X Y : Type}
parameter {A : set X}
parameter {B : set Y}
parameter {f : X → Y}
parameter (f_maps_to : maps_to f A B)
parameter (finj : inj_on f A)
parameter {g : Y → X}
parameter (g_maps_to : maps_to g B A)
parameter (ginj : inj_on g B)
include g g_maps_to ginj
theorem schroeder_bernstein : ∃ h, bij_on h A B :=
by_cases
(assume H : ∀ b, b ∉ B,
have fsurj : surj_on f A B, from take b, suppose b ∈ B, absurd this !H,
exists.intro f (and.intro f_maps_to (and.intro finj fsurj)))
(assume H : ¬ ∀ b, b ∉ B,
have ∃ b, b ∈ B, from exists_of_not_forall_not H,
obtain b bB, from this,
let h := @schroeder_bernstein.h X Y A B f g b in
have h_maps_to : maps_to h A B, from schroeder_bernstein.h_maps_to f_maps_to bB,
have hinj : inj_on h A, from schroeder_bernstein.h_inj finj ginj, -- ginj,
have hsurj : surj_on h A B, from schroeder_bernstein.h_surj f_maps_to g_maps_to ginj,
exists.intro h (and.intro h_maps_to (and.intro hinj hsurj)))
end
end set
|
879682f9c825678257a0347f796d7d63723af66e | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/ring_theory/noetherian.lean | a63c5282785fa846146c53f1d6b4686f9ae41d43 | [
"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 | 39,174 | lean | /-
Copyright (c) 2018 Mario Carneiro, Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Buzzard
-/
import group_theory.finiteness
import data.multiset.finset_ops
import algebra.algebra.tower
import order.order_iso_nat
import ring_theory.ideal.operations
import order.compactly_generated
import linear_algebra.linear_independent
import algebra.ring.idempotents
/-!
# Noetherian rings and modules
The following are equivalent for a module M over a ring R:
1. Every increasing chain of submodules M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises.
2. Every submodule is finitely generated.
A module satisfying these equivalent conditions is said to be a *Noetherian* R-module.
A ring is a *Noetherian ring* if it is Noetherian as a module over itself.
(Note that we do not assume yet that our rings are commutative,
so perhaps this should be called "left Noetherian".
To avoid cumbersome names once we specialize to the commutative case,
we don't make this explicit in the declaration names.)
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `submodule.fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module.
* `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
## Main statements
* `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form:
if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R
such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0.
* `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff
`>` is well-founded on `submodule R M`.
Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X],
is proved in `ring_theory.polynomial`.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel1967]
## Tags
Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module
-/
open set
open_locale big_operators pointwise
namespace submodule
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
/-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/
def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N
theorem fg_def {N : submodule R M} :
N.fg ↔ ∃ S : set M, S.finite ∧ span R S = N :=
⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin
rintro ⟨t', h, rfl⟩,
rcases finite.exists_finset_coe h with ⟨t, rfl⟩,
exact ⟨t, rfl⟩
end⟩
lemma fg_iff_add_submonoid_fg (P : submodule ℕ M) :
P.fg ↔ P.to_add_submonoid.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_nat_eq_add_submonoid_closure] using hS⟩⟩
lemma fg_iff_add_subgroup_fg {G : Type*} [add_comm_group G] (P : submodule ℤ G) :
P.fg ↔ P.to_add_subgroup.fg :=
⟨λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩,
λ ⟨S, hS⟩, ⟨S, by simpa [← span_int_eq_add_subgroup_closure] using hS⟩⟩
lemma fg_iff_exists_fin_generating_family {N : submodule R M} :
N.fg ↔ ∃ (n : ℕ) (s : fin n → M), span R (range s) = N :=
begin
rw fg_def,
split,
{ rintros ⟨S, Sfin, hS⟩,
obtain ⟨n, f, rfl⟩ := Sfin.fin_embedding,
exact ⟨n, f, hS⟩, },
{ rintros ⟨n, s, hs⟩,
refine ⟨range s, finite_range s, hs⟩ },
end
/-- **Nakayama's Lemma**. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2,
[Stacks 00DV](https://stacks.math.columbia.edu/tag/00DV) -/
theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R]
{M : Type*} [add_comm_group M] [module R M]
(I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) :
∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) :=
begin
rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩,
have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N,
{ refine ⟨1, _, _, _⟩,
{ rw sub_self, exact I.zero_mem },
{ rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn },
{ rw [← span_le, hs], exact le_refl N } },
clear hin hs, revert this,
refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _),
{ rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn,
rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn },
apply ih, rcases H with ⟨r, hr1, hrn, hs⟩,
rw [← set.singleton_union, span_union, smul_sup] at hrn,
rw [set.insert_subset] at hs,
have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s,
{ specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩,
use r-c, split,
{ rw [sub_right_comm], exact I.sub_mem hr1 hci },
{ rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } },
rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩,
{ rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢,
rw [ring_hom.map_mul, hc1, hr1, mul_one] },
{ intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn,
rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz,
rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩,
change _ • _ ∈ I • span R s,
rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul],
exact add_mem (smul_mem _ _ hci) (smul_mem _ _ hz) }
end
theorem exists_mem_and_smul_eq_self_of_fg_of_le_smul {R : Type*} [comm_ring R]
{M : Type*} [add_comm_group M] [module R M]
(I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) :
∃ r ∈ I, ∀ n ∈ N, r • n = n :=
begin
obtain ⟨r, hr, hr'⟩ := N.exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul I hn hin,
exact ⟨-(r-1), I.neg_mem hr, λ n hn, by simpa [sub_smul] using hr' n hn⟩,
end
theorem fg_bot : (⊥ : submodule R M).fg :=
⟨∅, by rw [finset.coe_empty, span_empty]⟩
lemma _root_.subalgebra.fg_bot_to_submodule {R A : Type*}
[comm_semiring R] [semiring A] [algebra R A] :
(⊥ : subalgebra R A).to_submodule.fg :=
⟨{1}, by simp [algebra.to_submodule_bot] ⟩
theorem fg_span {s : set M} (hs : s.finite) : fg (span R s) :=
⟨hs.to_finset, by rw [hs.coe_to_finset]⟩
theorem fg_span_singleton (x : M) : fg (R ∙ x) :=
fg_span (finite_singleton x)
theorem fg.sup {N₁ N₂ : submodule R M}
(hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg :=
let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in
fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩
lemma fg_finset_sup {ι : Type*} (s : finset ι) (N : ι → submodule R M) (h : ∀ i ∈ s, (N i).fg) :
(s.sup N).fg :=
finset.sup_induction fg_bot (λ a ha b hb, ha.sup hb) h
lemma fg_bsupr {ι : Type*} (s : finset ι) (N : ι → submodule R M) (h : ∀ i ∈ s, (N i).fg) :
(⨆ i ∈ s, N i).fg :=
by simpa only [finset.sup_eq_supr] using fg_finset_sup s N h
lemma fg_supr {ι : Type*} [fintype ι] (N : ι → submodule R M) (h : ∀ i, (N i).fg) :
(supr N).fg :=
by simpa using fg_bsupr finset.univ N (λ i hi, h i)
variables {P : Type*} [add_comm_monoid P] [module R P]
variables (f : M →ₗ[R] P)
theorem fg.map {N : submodule R M} (hs : N.fg) : (N.map f).fg :=
let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩
variables {f}
lemma fg_of_fg_map_injective (f : M →ₗ[R] P) (hf : function.injective f) {N : submodule R M}
(hfn : (N.map f).fg) : N.fg :=
let ⟨t, ht⟩ := hfn in ⟨t.preimage f $ λ x _ y _ h, hf h,
submodule.map_injective_of_injective hf $ by { rw [f.map_span, finset.coe_preimage,
set.image_preimage_eq_inter_range, set.inter_eq_self_of_subset_left, ht],
rw [← linear_map.range_coe, ← span_le, ht, ← map_top], exact map_mono le_top }⟩
lemma fg_of_fg_map {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) {N : submodule R M}
(hfn : (N.map f).fg) : N.fg :=
fg_of_fg_map_injective f (linear_map.ker_eq_bot.1 hf) hfn
lemma fg_top (N : submodule R M) : (⊤ : submodule R N).fg ↔ N.fg :=
⟨λ h, N.range_subtype ▸ map_top N.subtype ▸ h.map _,
λ h, fg_of_fg_map_injective N.subtype subtype.val_injective $ by rwa [map_top, range_subtype]⟩
lemma fg_of_linear_equiv (e : M ≃ₗ[R] P) (h : (⊤ : submodule R P).fg) :
(⊤ : submodule R M).fg :=
e.symm.range ▸ map_top (e.symm : P →ₗ[R] M) ▸ h.map _
theorem fg.prod {sb : submodule R M} {sc : submodule R P}
(hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg :=
let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in
fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc,
(htb.1.image _).union (htc.1.image _),
by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩
theorem fg_pi {ι : Type*} {M : ι → Type*} [fintype ι] [Π i, add_comm_monoid (M i)]
[Π i, module R (M i)] {p : Π i, submodule R (M i)} (hsb : ∀ i, (p i).fg) :
(submodule.pi set.univ p).fg :=
begin
classical,
simp_rw fg_def at hsb ⊢,
choose t htf hts using hsb,
refine ⟨
⋃ i, (linear_map.single i : _ →ₗ[R] _) '' t i, set.finite_Union $ λ i, (htf i).image _, _⟩,
simp_rw [span_Union, span_image, hts, submodule.supr_map_single],
end
/-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are
finitely generated then so is M. -/
theorem fg_of_fg_map_of_fg_inf_ker {R M P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group P] [module R P] (f : M →ₗ[R] P)
{s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg :=
begin
haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P,
cases hs1 with t1 ht1, cases hs2 with t2 ht2,
have : ∀ y ∈ t1, ∃ x ∈ s, f x = y,
{ intros y hy,
have : y ∈ map f s, { rw ← ht1, exact subset_span hy },
rcases mem_map.1 this with ⟨x, hx1, hx2⟩,
exact ⟨x, hx1, hx2⟩ },
have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y,
{ choose g hg1 hg2,
existsi λ y, if H : y ∈ t1 then g y H else 0,
intros y H, split,
{ simp only [dif_pos H], apply hg1 },
{ simp only [dif_pos H], apply hg2 } },
cases this with g hg, clear this,
existsi t1.image g ∪ t2,
rw [finset.coe_union, span_union, finset.coe_image],
apply le_antisymm,
{ refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _),
{ intros y hy, exact (hg y hy).1 },
{ intros x hx, have := subset_span hx,
rw ht2 at this,
exact this.1 } },
intros x hx,
have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ },
rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_image_iff_total] at this,
rcases this with ⟨l, hl1, hl2⟩,
refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun
((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _,
x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l),
_, add_sub_cancel'_right _ _⟩,
{ rw [← set.image_id (g '' ↑t1), finsupp.mem_span_image_iff_total], refine ⟨_, _, rfl⟩,
haveI : inhabited P := ⟨0⟩,
rw [← finsupp.lmap_domain_supported _ _ g, mem_map],
refine ⟨l, hl1, _⟩,
refl, },
rw [ht2, mem_inf], split,
{ apply s.sub_mem hx,
rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index],
refine s.sum_mem _,
{ intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 },
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } },
{ rw [linear_map.mem_ker, f.map_sub, ← hl2],
rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply],
rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum],
rw sub_eq_zero,
refine finset.sum_congr rfl (λ y hy, _),
unfold id,
rw [f.map_smul, (hg y (hl1 hy)).2],
{ exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }
end
lemma fg_induction (R M : Type*) [semiring R] [add_comm_monoid M] [module R M]
(P : submodule R M → Prop)
(h₁ : ∀ x, P (submodule.span R {x})) (h₂ : ∀ M₁ M₂, P M₁ → P M₂ → P (M₁ ⊔ M₂))
(N : submodule R M) (hN : N.fg) : P N :=
begin
classical,
obtain ⟨s, rfl⟩ := hN,
induction s using finset.induction,
{ rw [finset.coe_empty, submodule.span_empty, ← submodule.span_zero_singleton], apply h₁ },
{ rw [finset.coe_insert, submodule.span_insert], apply h₂; apply_assumption }
end
/-- The kernel of the composition of two linear maps is finitely generated if both kernels are and
the first morphism is surjective. -/
lemma fg_ker_comp {R M N P : Type*} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P] (f : M →ₗ[R] N)
(g : N →ₗ[R] P) (hf1 : f.ker.fg) (hf2 : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
rw linear_map.ker_comp,
apply fg_of_fg_map_of_fg_inf_ker f,
{ rwa [submodule.map_comap_eq, linear_map.range_eq_top.2 hsur, top_inf_eq] },
{ rwa [inf_of_le_right (show f.ker ≤ (comap f g.ker), from comap_mono bot_le)] }
end
lemma fg_restrict_scalars {R S M : Type*} [comm_semiring R] [semiring S] [algebra R S]
[add_comm_group M] [module S M] [module R M] [is_scalar_tower R S M] (N : submodule S M)
(hfin : N.fg) (h : function.surjective (algebra_map R S)) : (submodule.restrict_scalars R N).fg :=
begin
obtain ⟨X, rfl⟩ := hfin,
use X,
exact submodule.span_eq_restrict_scalars R S M X h
end
/-- Finitely generated submodules are precisely compact elements in the submodule lattice. -/
theorem fg_iff_compact (s : submodule R M) : s.fg ↔ complete_lattice.is_compact_element s :=
begin
classical,
-- Introduce shorthand for span of an element
let sp : M → submodule R M := λ a, span R {a},
-- Trivial rewrite lemma; a small hack since simp (only) & rw can't accomplish this smoothly.
have supr_rw : ∀ t : finset M, (⨆ x ∈ t, sp x) = (⨆ x ∈ (↑t : set M), sp x), from λ t, by refl,
split,
{ rintro ⟨t, rfl⟩,
rw [span_eq_supr_of_singleton_spans, ←supr_rw, ←(finset.sup_eq_supr t sp)],
apply complete_lattice.finset_sup_compact_of_compact,
exact λ n _, singleton_span_is_compact_element n, },
{ intro h,
-- s is the Sup of the spans of its elements.
have sSup : s = Sup (sp '' ↑s),
by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, eq_comm, span_eq],
-- by h, s is then below (and equal to) the sup of the spans of finitely many elements.
obtain ⟨u, ⟨huspan, husup⟩⟩ := h (sp '' ↑s) (le_of_eq sSup),
have ssup : s = u.sup id,
{ suffices : u.sup id ≤ s, from le_antisymm husup this,
rw [sSup, finset.sup_id_eq_Sup], exact Sup_le_Sup huspan, },
obtain ⟨t, ⟨hts, rfl⟩⟩ := finset.subset_image_iff.mp huspan,
rw [finset.sup_finset_image, function.comp.left_id, finset.sup_eq_supr, supr_rw,
←span_eq_supr_of_singleton_spans, eq_comm] at ssup,
exact ⟨t, ssup⟩, },
end
end submodule
namespace ideal
variables {R : Type*} {M : Type*} [semiring R] [add_comm_monoid M] [module R M]
/-- An ideal of `R` is finitely generated if it is the span of a finite subset of `R`.
This is defeq to `submodule.fg`, but unfolds more nicely. -/
def fg (I : ideal R) : Prop := ∃ S : finset R, ideal.span ↑S = I
/-- The image of a finitely generated ideal is finitely generated.
This is the `ideal` version of `submodule.fg.map`. -/
lemma fg.map {R S : Type*} [semiring R] [semiring S] {I : ideal R} (h : I.fg)
(f : R →+* S) : (I.map f).fg :=
begin
classical,
obtain ⟨s, hs⟩ := h,
refine ⟨s.image f, _⟩,
rw [finset.coe_image, ←ideal.map_span, hs],
end
lemma fg_ker_comp {R S A : Type*} [comm_ring R] [comm_ring S] [comm_ring A]
(f : R →+* S) (g : S →+* A) (hf : f.ker.fg) (hg : g.ker.fg) (hsur : function.surjective f) :
(g.comp f).ker.fg :=
begin
letI : algebra R S := ring_hom.to_algebra f,
letI : algebra R A := ring_hom.to_algebra (g.comp f),
letI : algebra S A := ring_hom.to_algebra g,
letI : is_scalar_tower R S A := is_scalar_tower.of_algebra_map_eq (λ _, rfl),
let f₁ := algebra.linear_map R S,
let g₁ := (is_scalar_tower.to_alg_hom R S A).to_linear_map,
exact submodule.fg_ker_comp f₁ g₁ hf (submodule.fg_restrict_scalars g.ker hg hsur) hsur
end
/-- A finitely generated idempotent ideal is generated by an idempotent element -/
lemma is_idempotent_elem_iff_of_fg {R : Type*} [comm_ring R] (I : ideal R)
(h : I.fg) :
is_idempotent_elem I ↔ ∃ e : R, is_idempotent_elem e ∧ I = R ∙ e :=
begin
split,
{ intro e,
obtain ⟨r, hr, hr'⟩ := submodule.exists_mem_and_smul_eq_self_of_fg_of_le_smul I I h
(by { rw [smul_eq_mul], exact e.ge }),
simp_rw smul_eq_mul at hr',
refine ⟨r, hr' r hr, antisymm _ ((submodule.span_singleton_le_iff_mem _ _).mpr hr)⟩,
intros x hx,
rw ← hr' x hx,
exact ideal.mem_span_singleton'.mpr ⟨_, mul_comm _ _⟩ },
{ rintros ⟨e, he, rfl⟩,
simp [is_idempotent_elem, ideal.span_singleton_mul_span_singleton, he.eq] }
end
lemma is_idempotent_elem_iff_eq_bot_or_top {R : Type*} [comm_ring R] [is_domain R]
(I : ideal R) (h : I.fg) :
is_idempotent_elem I ↔ I = ⊥ ∨ I = ⊤ :=
begin
split,
{ intro H,
obtain ⟨e, he, rfl⟩ := (I.is_idempotent_elem_iff_of_fg h).mp H,
simp only [ideal.submodule_span_eq, ideal.span_singleton_eq_bot],
apply or_of_or_of_imp_of_imp (is_idempotent_elem.iff_eq_zero_or_one.mp he) id,
rintro rfl,
simp },
{ rintro (rfl|rfl); simp [is_idempotent_elem] }
end
end ideal
/--
`is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
-/
class is_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop :=
(noetherian : ∀ (s : submodule R M), s.fg)
section
variables {R : Type*} {M : Type*} {P : Type*}
variables [semiring R] [add_comm_monoid M] [add_comm_monoid P]
variables [module R M] [module R P]
open is_noetherian
include R
/-- An R-module is Noetherian iff all its submodules are finitely-generated. -/
lemma is_noetherian_def : is_noetherian R M ↔ ∀ (s : submodule R M), s.fg :=
⟨λ h, h.noetherian, is_noetherian.mk⟩
theorem is_noetherian_submodule {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg :=
begin
refine ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs,
submodule.map_comap_eq_self this ▸ (hn _).map _, λ h, ⟨λ s, _⟩⟩,
have f := (submodule.equiv_map_of_injective N.subtype subtype.val_injective s).symm,
have h₁ := h (s.map N.subtype) (submodule.map_subtype_le N s),
have h₂ : (⊤ : submodule R (s.map N.subtype)).map (↑f : _ →ₗ[R] s) = ⊤ := by simp,
have h₃ := ((submodule.fg_top _).2 h₁).map (↑f : _ →ₗ[R] s),
exact (submodule.fg_top _).1 (h₂ ▸ h₃),
end
theorem is_noetherian_submodule_left {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩
theorem is_noetherian_submodule_right {N : submodule R M} :
is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg :=
is_noetherian_submodule.trans
⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩
instance is_noetherian_submodule' [is_noetherian R M] (N : submodule R M) : is_noetherian R N :=
is_noetherian_submodule.2 $ λ _ _, is_noetherian.noetherian _
lemma is_noetherian_of_le {s t : submodule R M} [ht : is_noetherian R t]
(h : s ≤ t) : is_noetherian R s :=
is_noetherian_submodule.mpr (λ s' hs', is_noetherian_submodule.mp ht _ (le_trans hs' h))
variable (M)
theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤)
[is_noetherian R M] : is_noetherian R P :=
⟨λ s, have (s.comap f).map f = s, from submodule.map_comap_eq_self $ hf.symm ▸ le_top,
this ▸ (noetherian _).map _⟩
variable {M}
theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P)
[is_noetherian R M] : is_noetherian R P :=
is_noetherian_of_surjective _ f.to_linear_map f.range
lemma is_noetherian_top_iff :
is_noetherian R (⊤ : submodule R M) ↔ is_noetherian R M :=
begin
unfreezingI { split; assume h },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl) },
{ exact is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl).symm },
end
lemma is_noetherian_of_injective [is_noetherian R P] (f : M →ₗ[R] P) (hf : function.injective f) :
is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.of_injective f hf).symm
lemma fg_of_injective [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P)
(hf : function.injective f) : N.fg :=
@@is_noetherian.noetherian _ _ _ (is_noetherian_of_injective f hf) N
end
section
variables {R : Type*} {M : Type*} {P : Type*}
variables [ring R] [add_comm_group M] [add_comm_group P]
variables [module R M] [module R P]
open is_noetherian
include R
lemma is_noetherian_of_ker_bot [is_noetherian R P] (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.of_injective f $ linear_map.ker_eq_bot.mp hf).symm
lemma fg_of_ker_bot [is_noetherian R P] {N : submodule R M} (f : M →ₗ[R] P) (hf : f.ker = ⊥) :
N.fg :=
@@is_noetherian.noetherian _ _ _ (is_noetherian_of_ker_bot f hf) N
instance is_noetherian_prod [is_noetherian R M]
[is_noetherian R P] : is_noetherian R (M × P) :=
⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $
have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P),
from λ x ⟨hx1, hx2⟩, ⟨x.1, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩,
submodule.map_comap_eq_self this ▸ (noetherian _).map _⟩
instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R]
[Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι]
[∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) :=
begin
haveI := classical.dec_eq ι,
suffices on_finset : ∀ s : finset ι, is_noetherian R (Π i : s, M i),
{ let coe_e := equiv.subtype_univ_equiv finset.mem_univ,
letI : is_noetherian R (Π i : finset.univ, M (coe_e i)) := on_finset finset.univ,
exact is_noetherian_of_linear_equiv (linear_equiv.Pi_congr_left R M coe_e), },
intro s,
induction s using finset.induction with a s has ih,
{ split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2,
intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 },
refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _
_ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih),
fconstructor,
{ exact λ f i, or.by_cases (finset.mem_insert.1 i.2)
(λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1))
(λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) },
{ intros f g, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = _ + _, simp only [dif_pos], refl },
{ change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ intros c f, ext i, unfold or.by_cases, cases i with i hi,
rcases finset.mem_insert.1 hi with rfl | h,
{ change _ = c • _, simp only [dif_pos], refl },
{ change _ = c • _, have : ¬i = a, { rintro rfl, exact has h },
simp only [dif_neg this, dif_pos h], refl } },
{ exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) },
{ intro f, apply prod.ext,
{ simp only [or.by_cases, dif_pos] },
{ ext ⟨i, his⟩,
have : ¬i = a, { rintro rfl, exact has his },
dsimp only [or.by_cases], change i ∈ s at his,
rw [dif_neg this, dif_pos his] } },
{ intro f, ext ⟨i, hi⟩,
rcases finset.mem_insert.1 hi with rfl | h,
{ simp only [or.by_cases, dif_pos], },
{ have : ¬i = a, { rintro rfl, exact has h },
simp only [or.by_cases, dif_neg this, dif_pos h], } }
end
/-- A version of `is_noetherian_pi` for non-dependent functions. We need this instance because
sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to
prove that `ι → ℝ` is finite dimensional over `ℝ`). -/
instance is_noetherian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι]
[is_noetherian R M] : is_noetherian R (ι → M) :=
is_noetherian_pi
end
open is_noetherian submodule function
section
universe w
variables {R M P : Type*} {N : Type w} [semiring R] [add_comm_monoid M] [module R M]
[add_comm_monoid N] [module R N] [add_comm_monoid P] [module R P]
theorem is_noetherian_iff_well_founded :
is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) :=
begin
rw (complete_lattice.well_founded_characterisations $ submodule R M).out 0 3,
exact ⟨λ ⟨h⟩, λ k, (fg_iff_compact k).mp (h k), λ h, ⟨λ k, (fg_iff_compact k).mpr (h k)⟩⟩,
end
lemma is_noetherian_iff_fg_well_founded :
is_noetherian R M ↔ well_founded
((>) : { N : submodule R M // N.fg } → { N : submodule R M // N.fg } → Prop) :=
begin
let α := { N : submodule R M // N.fg },
split,
{ introI H,
let f : α ↪o submodule R M := order_embedding.subtype _,
exact order_embedding.well_founded f.dual (is_noetherian_iff_well_founded.mp H) },
{ intro H,
constructor,
intro N,
obtain ⟨⟨N₀, h₁⟩, e : N₀ ≤ N, h₂⟩ := well_founded.well_founded_iff_has_max'.mp
H { N' : α | N'.1 ≤ N } ⟨⟨⊥, submodule.fg_bot⟩, bot_le⟩,
convert h₁,
refine (e.antisymm _).symm,
by_contra h₃,
obtain ⟨x, hx₁ : x ∈ N, hx₂ : x ∉ N₀⟩ := set.not_subset.mp h₃,
apply hx₂,
have := h₂ ⟨(R ∙ x) ⊔ N₀, _⟩ _ _,
{ injection this with eq,
rw ← eq,
exact (le_sup_left : (R ∙ x) ≤ (R ∙ x) ⊔ N₀) (submodule.mem_span_singleton_self _) },
{ exact submodule.fg.sup ⟨{x}, by rw [finset.coe_singleton]⟩ h₁ },
{ exact sup_le ((submodule.span_singleton_le_iff_mem _ _).mpr hx₁) e },
{ show N₀ ≤ (R ∙ x) ⊔ N₀, from le_sup_right } }
end
variables (R M)
lemma well_founded_submodule_gt (R M) [semiring R] [add_comm_monoid M] [module R M] :
∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) :=
is_noetherian_iff_well_founded.mp
variables {R M}
/-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them.
-/
theorem set_has_maximal_iff_noetherian :
(∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔
is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max']
/-- A module is Noetherian iff every increasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_noetherian :
(∀ (f : ℕ →o submodule R M), ∃ n, ∀ m, n ≤ m → f n = f m)
↔ is_noetherian R M :=
by rw [is_noetherian_iff_well_founded, well_founded.monotone_chain_condition]
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
lemma is_noetherian.induction [is_noetherian R M] {P : submodule R M → Prop}
(hgt : ∀ I, (∀ J > I, P J) → P I) (I : submodule R M) : P I :=
well_founded.recursion (well_founded_submodule_gt R M) I hgt
end
section
universe w
variables {R M P : Type*} {N : Type w} [ring R] [add_comm_group M] [module R M]
[add_comm_group N] [module R N] [add_comm_group P] [module R P]
lemma finite_of_linear_independent [nontrivial R] [is_noetherian R M]
{s : set M} (hs : linear_independent R (coe : s → M)) : s.finite :=
begin
refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1
(well_founded_submodule_gt R M)).elim' _),
have f : ℕ ↪ s, from set.infinite.nat_embedding s hf,
have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s,
{ rintros n x ⟨y, hy₁, rfl⟩, exact (f y).2 },
have : ∀ a b : ℕ, a ≤ b ↔
span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}),
{ assume a b,
rw [span_le_span_iff hs (this a) (this b),
set.image_subset_image_iff (subtype.coe_injective.comp f.injective),
set.subset_def],
exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ },
exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}),
λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩,
by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩
end
/-- If the first and final modules in a short exact sequence are noetherian,
then the middle module is also noetherian. -/
theorem is_noetherian_of_range_eq_ker
[is_noetherian R M] [is_noetherian R P]
(f : M →ₗ[R] N) (g : N →ₗ[R] P)
(hf : function.injective f)
(hg : function.surjective g)
(h : f.range = g.ker) :
is_noetherian R N :=
is_noetherian_iff_well_founded.2 $
well_founded_gt_exact_sequence
(well_founded_submodule_gt R M)
(well_founded_submodule_gt R P)
f.range
(submodule.map f)
(submodule.comap f)
(submodule.comap g)
(submodule.map g)
(submodule.gci_map_comap hf)
(submodule.gi_map_comap hg)
(by simp [submodule.map_comap_eq, inf_comm])
(by simp [submodule.comap_map_eq, h])
/--
For any endomorphism of a Noetherian module, there is some nontrivial iterate
with disjoint kernel and range.
-/
theorem is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot
[I : is_noetherian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊓ (f ^ n).range = ⊥ :=
begin
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I
(f.iterate_ker.comp ⟨λ n, n+1, λ n m w, by linarith⟩),
specialize w (2 * n + 1) (by linarith),
dsimp at w,
refine ⟨n+1, nat.succ_ne_zero _, _⟩,
rw eq_bot_iff,
rintros - ⟨h, ⟨y, rfl⟩⟩,
rw [mem_bot, ←linear_map.mem_ker, w],
erw linear_map.mem_ker at h ⊢,
change ((f ^ (n + 1)) * (f ^ (n + 1))) y = 0 at h,
rw ←pow_add at h,
convert h using 3,
linarith,
end
/-- Any surjective endomorphism of a Noetherian module is injective. -/
theorem is_noetherian.injective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : injective f :=
begin
obtain ⟨n, ne, w⟩ := is_noetherian.exists_endomorphism_iterate_ker_inf_range_eq_bot f,
rw [linear_map.range_eq_top.mpr (linear_map.iterate_surjective s n), inf_top_eq,
linear_map.ker_eq_bot] at w,
exact linear_map.injective_of_iterate_injective ne w,
end
/-- Any surjective endomorphism of a Noetherian module is bijective. -/
theorem is_noetherian.bijective_of_surjective_endomorphism [is_noetherian R M]
(f : M →ₗ[R] M) (s : surjective f) : bijective f :=
⟨is_noetherian.injective_of_surjective_endomorphism f s, s⟩
/--
A sequence `f` of submodules of a noetherian module,
with `f (n+1)` disjoint from the supremum of `f 0`, ..., `f n`,
is eventually zero.
-/
lemma is_noetherian.disjoint_partial_sups_eventually_bot [I : is_noetherian R M]
(f : ℕ → submodule R M) (h : ∀ n, disjoint (partial_sups f n) (f (n+1))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊥ :=
begin
-- A little off-by-one cleanup first:
suffices t : ∃ n : ℕ, ∀ m, n ≤ m → f (m+1) = ⊥,
{ obtain ⟨n, w⟩ := t,
use n+1,
rintros (_|m) p,
{ cases p, },
{ apply w,
exact nat.succ_le_succ_iff.mp p }, },
obtain ⟨n, w⟩ := monotone_stabilizes_iff_noetherian.mpr I (partial_sups f),
exact ⟨n, λ m p, (h m).eq_bot_of_ge $ sup_eq_left.1 $ (w (m + 1) $ le_add_right p).symm.trans $
w m p⟩
end
/--
If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial.
-/
noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M]
(f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} :=
begin
apply nonempty.some,
obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i)
(f.tailings_disjoint_tailing i),
specialize w n (le_refl n),
apply nonempty.intro,
refine (f.tailing_linear_equiv i n).symm ≪≫ₗ _,
rw w,
exact submodule.bot_equiv_punit,
end
end
/--
A (semi)ring is Noetherian if it is Noetherian as a module over itself,
i.e. all its ideals are finitely generated.
-/
@[reducible] def is_noetherian_ring (R) [semiring R] := is_noetherian R R
theorem is_noetherian_ring_iff {R} [semiring R] : is_noetherian_ring R ↔ is_noetherian R R :=
iff.rfl
/-- A ring is Noetherian if and only if all its ideals are finitely-generated. -/
lemma is_noetherian_ring_iff_ideal_fg (R : Type*) [semiring R] :
is_noetherian_ring R ↔ ∀ I : ideal R, I.fg :=
is_noetherian_ring_iff.trans is_noetherian_def
@[priority 80] -- see Note [lower instance priority]
instance is_noetherian_of_finite (R M) [finite M] [semiring R] [add_comm_monoid M] [module R M] :
is_noetherian R M :=
⟨λ s, ⟨(s : set M).to_finite.to_finset, by rw [set.finite.coe_to_finset, submodule.span_eq]⟩⟩
/-- Modules over the trivial ring are Noetherian. -/
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_of_subsingleton (R M) [subsingleton R] [semiring R] [add_comm_monoid M]
[module R M] : is_noetherian R M :=
by { haveI := module.subsingleton R M, exact is_noetherian_of_finite R M }
theorem is_noetherian_of_submodule_of_noetherian (R M) [semiring R] [add_comm_monoid M] [module R M]
(N : submodule R M) (h : is_noetherian R M) : is_noetherian R N :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h,
end
instance submodule.quotient.is_noetherian {R} [ring R] {M} [add_comm_group M] [module R M]
(N : submodule R M) [h : is_noetherian R M] : is_noetherian R (M ⧸ N) :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h,
end
/-- If `M / S / R` is a scalar tower, and `M / R` is Noetherian, then `M / S` is
also noetherian. -/
theorem is_noetherian_of_tower (R) {S M} [semiring R] [semiring S]
[add_comm_monoid M] [has_smul R S] [module S M] [module R M] [is_scalar_tower R S M]
(h : is_noetherian R M) : is_noetherian S M :=
begin
rw is_noetherian_iff_well_founded at h ⊢,
refine (submodule.restrict_scalars_embedding R S M).dual.well_founded h
end
instance ideal.quotient.is_noetherian_ring {R : Type*} [comm_ring R] [h : is_noetherian_ring R]
(I : ideal R) : is_noetherian_ring (R ⧸ I) :=
is_noetherian_ring_iff.mpr $ is_noetherian_of_tower R $ submodule.quotient.is_noetherian _
theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
haveI := classical.dec_eq R,
letI : is_noetherian R R := by apply_instance,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _)
_ _ _ is_noetherian_pi,
{ fapply linear_map.mk,
{ exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ },
{ intros f g, apply subtype.eq,
change ∑ i in s.attach, (f i + g i) • _ = _,
simp only [add_smul, finset.sum_add_distrib], refl },
{ intros c f, apply subtype.eq,
change ∑ i in s.attach, (c • f i) • _ = _,
simp only [smul_eq_mul, mul_smul],
exact finset.smul_sum.symm } },
rw linear_map.range_eq_top,
rintro ⟨n, hn⟩, change n ∈ N at hn,
rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn,
rcases hn with ⟨l, hl1, hl2⟩,
refine ⟨λ x, l x, subtype.ext _⟩,
change ∑ i in s.attach, l i • (i : M) = n,
rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2,
finsupp.total_apply, finsupp.sum, eq_comm],
refine finset.sum_subset hl1 (λ x _ hx, _),
rw [finsupp.not_mem_support_iff.1 hx, zero_smul]
end
lemma is_noetherian_of_fg_of_noetherian' {R M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] (h : (⊤ : submodule R M).fg) : is_noetherian R M :=
have is_noetherian R (⊤ : submodule R M), from is_noetherian_of_fg_of_noetherian _ h,
by exactI is_noetherian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl)
/-- In a module over a noetherian ring, the submodule generated by finitely many vectors is
noetherian. -/
theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M]
[is_noetherian_ring R] {A : set M} (hA : A.finite) : is_noetherian R (submodule.span R A) :=
is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem is_noetherian_ring_of_surjective (R) [ring R] (S) [ring S]
(f : R →+* S) (hf : function.surjective f)
[H : is_noetherian_ring R] : is_noetherian_ring S :=
begin
rw [is_noetherian_ring_iff, is_noetherian_iff_well_founded] at H ⊢,
exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H,
end
instance is_noetherian_ring_range {R} [ring R] {S} [ring S] (f : R →+* S)
[is_noetherian_ring R] : is_noetherian_ring f.range :=
is_noetherian_ring_of_surjective R f.range f.range_restrict
f.range_restrict_surjective
theorem is_noetherian_ring_of_ring_equiv (R) [ring R] {S} [ring S]
(f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S :=
is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective
namespace submodule
section map₂
variables {R M N P : Type*}
variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
variables [module R M] [module R N] [module R P]
theorem fg.map₂ (f : M →ₗ[R] N →ₗ[R] P) {p : submodule R M} {q : submodule R N}
(hp : p.fg) (hq : q.fg) : (map₂ f p q).fg :=
let ⟨sm, hfm, hm⟩ := fg_def.1 hp, ⟨sn, hfn, hn⟩ := fg_def.1 hq in
fg_def.2 ⟨set.image2 (λ m n, f m n) sm sn,
hfm.image2 _ hfn, map₂_span_span R f sm sn ▸ hm ▸ hn ▸ rfl⟩
end map₂
section mul
variables {R : Type*} {A : Type*} [comm_semiring R] [semiring A] [algebra R A]
variables {M N : submodule R A}
theorem fg.mul (hm : M.fg) (hn : N.fg) : (M * N).fg := hm.map₂ _ hn
lemma fg.pow (h : M.fg) (n : ℕ) : (M ^ n).fg :=
nat.rec_on n
(⟨{1}, by simp [one_eq_span]⟩)
(λ n ih, by simpa [pow_succ] using h.mul ih)
end mul
end submodule
|
628c04173d2da353011675bb8fcd349fcb48f7fd | d642a6b1261b2cbe691e53561ac777b924751b63 | /src/analysis/normed_space/banach.lean | 1838ef8062ebeb7d9cff5695d8cf11049c7edf0f | [
"Apache-2.0"
] | permissive | cipher1024/mathlib | fee56b9954e969721715e45fea8bcb95f9dc03fe | d077887141000fefa5a264e30fa57520e9f03522 | refs/heads/master | 1,651,806,490,504 | 1,573,508,694,000 | 1,573,508,694,000 | 107,216,176 | 0 | 0 | Apache-2.0 | 1,647,363,136,000 | 1,508,213,014,000 | Lean | UTF-8 | Lean | false | false | 10,503 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Banach spaces, i.e., complete vector spaces.
This file contains the Banach open mapping theorem, i.e., the fact that a bijective
bounded linear map between Banach spaces has a bounded inverse.
-/
import topology.metric_space.baire analysis.normed_space.bounded_linear_maps
open function metric set filter finset
open_locale classical
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [complete_space E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [complete_space F] [normed_space 𝕜 F]
{f : E → F}
include 𝕜
set_option class.instance_max_depth 70
/-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then
any point has a preimage with controlled norm. -/
theorem exists_preimage_norm_le (hf : is_bounded_linear_map 𝕜 f) (surj : surjective f) :
∃C, 0 < C ∧ ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ :=
begin
have lin := hf.to_is_linear_map,
haveI : nonempty F := ⟨0⟩,
/- First step of the proof (using completeness of `F`): by Baire's theorem, there exists a
ball in E whose image closure has nonempty interior. Rescaling everything, it follows that
any `y ∈ F` is arbitrarily well approached by images of elements of norm at
most `C * ∥y∥`. For further use, we will only need such an element whose image
is within distance ∥y∥/2 of y, to apply an iterative process. -/
have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ,
{ refine subset.antisymm (subset_univ _) (λy hy, _),
rcases surj y with ⟨x, hx⟩,
rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩,
refine mem_Union.2 ⟨n, subset_closure _⟩,
refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩,
rwa [mem_ball, dist_eq_norm, sub_zero] },
have : ∃(n:ℕ) y ε, 0 < ε ∧ ball y ε ⊆ closure (f '' (ball 0 n)) :=
nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A,
have : ∃C, 0 ≤ C ∧ ∀y, ∃x, dist (f x) y ≤ (1/2) * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥,
{ rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩,
rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩,
refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩,
{ refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _,
refine inv_nonneg.2 (div_nonneg' (le_of_lt εpos) (by norm_num)),
exact nat.cast_nonneg n },
{ by_cases hy : y = 0,
{ use 0, simp [hy, lin.map_zero] },
{ rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydle, leyd, dinv⟩,
let δ := ∥d∥ * ∥y∥/4,
have δpos : 0 < δ :=
div_pos (mul_pos ((norm_pos_iff _).2 hd) ((norm_pos_iff _).2 hy)) (by norm_num),
have : a + d • y ∈ ball a ε,
by simp [dist_eq_norm, lt_of_le_of_lt ydle (half_lt_self εpos)],
rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩,
rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩,
rw ← xz₁ at h₁,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₁,
have : a ∈ ball a ε, by { simp, exact εpos },
rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩,
rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩,
rw ← xz₂ at h₂,
rw [mem_ball, dist_eq_norm, sub_zero] at hx₂,
let x := x₁ - x₂,
have I : ∥f x - d • y∥ ≤ 2 * δ := calc
∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ :
by { congr' 1, simp only [x, lin.map_sub], abel }
... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ :
norm_triangle_sub
... ≤ δ + δ : begin
apply add_le_add,
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ },
{ rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ }
end
... = 2 * δ : (two_mul _).symm,
have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc
∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ :
by rwa [lin.smul, inv_mul_cancel, one_smul]
... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub]
... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, normed_field.norm_inv]
... ≤ ∥d∥⁻¹ * (2 * δ) : begin
apply mul_le_mul_of_nonneg_left I,
rw inv_nonneg,
exact norm_nonneg _
end
... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring }
... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] }
... = (1/2) * ∥y∥ : by ring,
rw ← dist_eq_norm at J,
have 𝕜 : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc
∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, normed_field.norm_inv]
... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin
refine mul_le_mul dinv _ (norm_nonneg _) _,
{ exact le_trans (norm_triangle_sub) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) },
{ apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _),
exact inv_nonneg.2 (le_of_lt (half_pos εpos)) }
end
... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring,
exact ⟨d⁻¹ • x, J, 𝕜⟩ } } },
rcases this with ⟨C, C0, hC⟩,
/- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be
the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that
has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`,
leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage
of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a
preimage of `y`. This uses completeness of `E`. -/
choose g hg using hC,
let h := λy, y - f (g y),
have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥,
{ assume y,
rw [← dist_eq_norm, dist_comm],
exact (hg y).1 },
refine ⟨2 * C + 1, by linarith, λy, _⟩,
have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥,
{ assume n,
induction n with n IH,
{ simp only [one_div_eq_inv, nat.nat_zero_eq_zero, one_mul, nat.iterate_zero, pow_zero] },
{ rw [nat.iterate_succ'],
apply le_trans (hle _) _,
rw [pow_succ, mul_assoc],
apply mul_le_mul_of_nonneg_left IH,
norm_num } },
let u := λn, g((h^[n]) y),
have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥),
{ assume n,
apply le_trans (hg _).2 _,
calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0
... = (1 / 2) ^ n * (C * ∥y∥) : by ring },
have sNu : summable (λn, ∥u n∥),
{ refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _,
exact summable_mul_right _ (summable_geometric (by norm_num) (by norm_num)) },
have su : summable u := summable_of_summable_norm sNu,
let x := tsum u,
have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc
∥x∥ ≤ (∑n, ∥u n∥) : norm_tsum_le_tsum_norm sNu
... ≤ (∑n, (1/2)^n * (C * ∥y∥)) :
tsum_le_tsum ule sNu (summable_mul_right _ summable_geometric_two)
... = (∑n, (1/2)^n) * (C * ∥y∥) : by { rw tsum_mul_right, exact summable_geometric_two }
... = 2 * (C * ∥y∥) : by rw tsum_geometric_two
... = 2 * C * ∥y∥ + 0 : by rw [add_zero, mul_assoc]
... ≤ 2 * C * ∥y∥ + ∥y∥ : add_le_add (le_refl _) (norm_nonneg _)
... = (2 * C + 1) * ∥y∥ : by ring,
have fsumeq : ∀n:ℕ, f((range n).sum u) = y - (h^[n]) y,
{ assume n,
induction n with n IH,
{ simp [lin.map_zero] },
{ rw [sum_range_succ, lin.add, IH, nat.iterate_succ'],
simp [u, h] } },
have : tendsto (λn, (range n).sum u) at_top (nhds x) :=
tendsto_sum_nat_of_has_sum (has_sum_tsum su),
have L₁ : tendsto (λn, f((range n).sum u)) at_top (nhds (f x)) :=
tendsto.comp (hf.continuous.tendsto _) this,
simp only [fsumeq] at L₁,
have L₂ : tendsto (λn, y - (h^[n]) y) at_top (nhds (y - 0)),
{ refine tendsto_sub tendsto_const_nhds _,
rw tendsto_iff_norm_tendsto_zero,
simp only [sub_zero],
refine squeeze_zero (λ_, norm_nonneg _) hnle _,
have : 0 = 0 * ∥y∥, by rw zero_mul,
rw this,
refine tendsto_mul _ tendsto_const_nhds,
exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) },
have feq : f x = y - 0,
{ apply tendsto_nhds_unique _ L₁ L₂,
simp },
rw sub_zero at feq,
exact ⟨x, feq, x_ineq⟩
end
/-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/
theorem open_mapping (hf : is_bounded_linear_map 𝕜 f) (surj : surjective f) : is_open_map f :=
begin
assume s hs,
have lin := hf.to_is_linear_map,
rcases exists_preimage_norm_le hf surj with ⟨C, Cpos, hC⟩,
refine is_open_iff.2 (λy yfs, _),
rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩,
rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩,
refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩,
rcases hC (z-y) with ⟨w, wim, wnorm⟩,
have : f (x + w) = z, by { rw [lin.add, wim, fxy], abel },
rw ← this,
have : x + w ∈ ball x ε := calc
dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp }
... ≤ C * ∥z - y∥ : wnorm
... < C * (ε/C) : begin
apply mul_lt_mul_of_pos_left _ Cpos,
rwa [mem_ball, dist_eq_norm] at hz,
end
... = ε : mul_div_cancel' _ (ne_of_gt Cpos),
exact set.mem_image_of_mem _ (hε this)
end
/-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/
theorem linear_equiv.is_bounded_inv (e : linear_equiv 𝕜 E F) (h : is_bounded_linear_map 𝕜 e.to_fun) :
is_bounded_linear_map 𝕜 e.inv_fun :=
{ bound := begin
have : surjective e.to_fun := (equiv.bijective e.to_equiv).2,
rcases exists_preimage_norm_le h this with ⟨M, Mpos, hM⟩,
refine ⟨M, Mpos, λy, _⟩,
rcases hM y with ⟨x, hx, xnorm⟩,
have : x = e.inv_fun y, by { rw ← hx, exact (e.symm_apply_apply _).symm },
rwa ← this
end,
..e.symm }
|
e84e2cd3ef1cde711a36d85b56493b6acf608129 | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/linear_algebra/determinant.lean | 90cc855d5481cbce6f39d759fd1a02fc891ce787 | [
"Apache-2.0"
] | permissive | mcncm/mathlib | 8d25099344d9d2bee62822cb9ed43aa3e09fa05e | fde3d78cadeec5ef827b16ae55664ef115e66f57 | refs/heads/master | 1,672,743,316,277 | 1,602,618,514,000 | 1,602,618,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,469 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Tim Baanen
-/
import data.matrix.pequiv
import data.fintype.card
import group_theory.perm.sign
import algebra.algebra.basic
import tactic.ring
universes u v w z
open equiv equiv.perm finset function
namespace matrix
open_locale matrix big_operators
variables {n : Type u} [decidable_eq n] [fintype n] {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
/-- The determinant of a matrix given by the Leibniz formula. -/
definition det (M : matrix n n R) : R :=
∑ σ : perm n, ε σ * ∏ i, M (σ i) i
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i :=
begin
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt equiv.ext h2) with x h3,
convert mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
by rw [← diagonal_zero, det_diagonal, finset.prod_const, ← fintype.card,
zero_pow (fintype.card_pos_iff.2 h)]
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 :=
begin
have perm_eq : (univ : finset (perm n)) = {1} :=
univ_eq_singleton_of_card_one (1 : perm n) (by simp [card_univ, fintype.card_perm, h]),
simp [det, card_eq_zero.mp h, perm_eq],
end
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← fintype.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∀ a, p (swap i j a) = p a := λ a, by simp only [swap_apply_def]; split_ifs; cc,
have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x),
from prod_bij (λ a _, swap i j a) (λ _ _, mem_univ _) (by simp [this])
(λ _ _ _ _ h, (swap i j).injective h)
(λ b _, ⟨swap i j b, mem_univ _, by simp⟩),
by simp [sign_mul, this, sign_swap hij, prod_mul_distrib])
(λ σ _ _ h, hij (σ.injective $ by conv {to_lhs, rw ← h}; simp))
(λ _ _, mem_univ _)
(λ _ _, equiv.ext $ by simp)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N :=
calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
by simp only [det, mul_apply, prod_univ_sum, mul_sum,
fintype.pi_finset_univ]; rw [finset.sum_comm]
... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n,
ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
eq.symm $ sum_subset (filter_subset _)
(λ f _ hbij, det_mul_aux $ by simpa using hbij)
... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) :
sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩)
... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) :
by simp [mul_sum, det, mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) :
sum_congr rfl (λ σ _, sum_bij (λ τ _, τ * σ⁻¹) (λ _ _, mem_univ _)
(λ τ _,
have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j,
by rw ← σ⁻¹.prod_comp; simp [mul_apply],
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by rw [mul_comm, sign_mul (τ * σ⁻¹)]; simp [sign_mul]
... = ε τ : by simp,
by rw h; simp [this, mul_comm, mul_assoc, mul_left_comm])
(λ _ _ _ _, mul_right_cancel) (λ τ _, ⟨τ * σ, by simp⟩))
... = det M * det N : by simp [det, mul_assoc, mul_sum, mul_comm, mul_left_comm]
instance : is_monoid_hom (det : matrix n n R → R) :=
{ map_one := det_one,
map_mul := det_mul }
/-- Transposing a matrix preserves the determinant. -/
@[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det :=
begin
apply sum_bij (λ σ _, σ⁻¹),
{ intros σ _, apply mem_univ },
{ intros σ _,
rw [sign_inv],
congr' 1,
apply prod_bij (λ i _, σ i),
{ intros i _, apply mem_univ },
{ intros i _, simp },
{ intros i j _ _ h, simp at h, assumption },
{ intros i _, use σ⁻¹ i, finish } },
{ intros σ σ' _ _ h, simp at h, assumption },
{ intros σ _, use σ⁻¹, finish }
end
/-- The determinant of a permutation matrix equals its sign. -/
@[simp] lemma det_permutation (σ : perm n) :
matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := begin
suffices : matrix.det (σ.to_pequiv.to_matrix) = ↑σ.sign * det (1 : matrix n n R), { simp [this] },
unfold det,
rw mul_sum,
apply sum_bij (λ τ _, σ * τ),
{ intros τ _, apply mem_univ },
{ intros τ _,
conv_lhs { rw [←one_mul (sign τ), ←int.units_pow_two (sign σ)] },
conv_rhs { rw [←mul_assoc, coe_coe, sign_mul, units.coe_mul, int.cast_mul, ←mul_assoc] },
congr,
{ simp [pow_two] },
{ ext i, apply pequiv.equiv_to_pequiv_to_matrix } },
{ intros τ τ' _ _, exact (mul_right_inj σ).mp },
{ intros τ _, use σ⁻¹ * τ, use (mem_univ _), exact (mul_inv_cancel_left _ _).symm }
end
/-- Permuting the columns changes the sign of the determinant. -/
lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det :=
by rw [←det_permutation, ←det_mul, pequiv.to_pequiv_mul_matrix]
@[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A :=
calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul]
... = det (diagonal (λ _, c)) * det A : det_mul _ _
... = c ^ fintype.card n * det A : by simp [card_univ]
section hom_map
variables {S : Type w} [comm_ring S]
lemma ring_hom.map_det {M : matrix n n R} {f : R →+* S} :
f M.det = matrix.det (f.map_matrix M) :=
by simp [matrix.det, f.map_sum, f.map_prod]
lemma alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
{M : matrix n n S} {f : S →ₐ[R] T} :
f M.det = matrix.det ((f : S →+* T).map_matrix M) :=
by rw [← alg_hom.coe_to_ring_hom, ring_hom.map_det]
end hom_map
section det_zero
/-!
### `det_zero` section
Prove that a matrix with a repeated column has determinant equal to zero.
-/
lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 :=
begin
rw [←det_transpose, det],
convert @sum_const_zero _ _ (univ : finset (perm n)) _,
ext σ,
convert mul_zero ↑(sign σ),
apply prod_eq_zero (mem_univ i),
rw [transpose_apply],
apply h
end
/--
`mod_swap i j` contains permutations up to swapping `i` and `j`.
We use this to partition permutations in the expression for the determinant,
such that each partitions sums up to `0`.
-/
def mod_swap {n : Type u} [decidable_eq n] (i j : n) : setoid (perm n) :=
⟨ λ σ τ, σ = τ ∨ σ = swap i j * τ,
λ σ, or.inl (refl σ),
λ σ τ h, or.cases_on h (λ h, or.inl h.symm) (λ h, or.inr (by rw [h, swap_mul_self_mul])),
λ σ τ υ hστ hτυ, by cases hστ; cases hτυ; try {rw [hστ, hτυ, swap_mul_self_mul]}; finish⟩
instance (i j : n) : decidable_rel (mod_swap i j).r := λ σ τ, or.decidable
variables {M : matrix n n R} {i j : n}
/-- If a matrix has a repeated column, the determinant will be zero. -/
theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 :=
begin
have swap_invariant : ∀ k, M (swap i j k) = M k,
{ intros k,
rw [swap_apply_def],
by_cases k = i, { rw [if_pos h, h, ←hij] },
rw [if_neg h],
by_cases k = j, { rw [if_pos h, h, hij] },
rw [if_neg h] },
have : ∀ σ, _root_.disjoint {σ} {swap i j * σ},
{ intros σ,
rw [disjoint_singleton, mem_singleton],
exact (not_congr swap_mul_eq_iff).mpr i_ne_j },
apply finset.sum_cancels_of_partition_cancels (mod_swap i j),
intros σ _,
erw [filter_or, filter_eq', filter_eq', if_pos (mem_univ σ), if_pos (mem_univ (swap i j * σ)),
sum_union (this σ), sum_singleton, sum_singleton],
convert add_right_neg (↑↑(sign σ) * ∏ i, M (σ i) i),
rw [neg_mul_eq_neg_mul],
congr,
{ rw [sign_mul, sign_swap i_ne_j], norm_num },
ext j, rw [perm.mul_apply, swap_invariant]
end
end det_zero
lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) :=
begin
simp only [det],
have : ∀ σ : perm n, ∏ i, M.update_column j (u + v) (σ i) i =
∏ i, M.update_column j u (σ i) i + ∏ i, M.update_column j v (σ i) i,
{ intros σ,
simp only [update_column_apply, prod_ite, filter_eq',
finset.prod_singleton, finset.mem_univ, if_true, pi.add_apply, add_mul] },
rw [← sum_add_distrib],
apply sum_congr rfl,
intros x _,
rw [this, mul_add]
end
lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) :=
begin
rw [← det_transpose, ← update_column_transpose, det_update_column_add],
simp [update_column_transpose, det_transpose]
end
lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column M j $ s • u) = s * det (update_column M j u) :=
begin
simp only [det],
have : ∀ σ : perm n, ∏ i, M.update_column j (s • u) (σ i) i = s * ∏ i, M.update_column j u (σ i) i,
{ intros σ,
simp only [update_column_apply, prod_ite, filter_eq', finset.prod_singleton, finset.mem_univ,
if_true, algebra.id.smul_eq_mul, pi.smul_apply],
ring },
rw mul_sum,
apply sum_congr rfl,
intros x _,
rw this,
ring
end
lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row M j $ s • u) = s * det (update_row M j u) :=
begin
rw [← det_transpose, ← update_column_transpose, det_update_column_smul],
simp [update_column_transpose, det_transpose]
end
@[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) :
(block_diagonal M).det = ∏ k, (M k).det :=
begin
-- Rewrite the determinants as a sum over permutations.
unfold det,
-- The right hand side is a product of sums, rewrite it as a sum of products.
rw finset.prod_sum,
simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ],
-- We claim that the only permutations contributing to the sum are those that
-- preserve their second component.
let preserving_snd : finset (equiv.perm (n × o)) :=
finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd),
have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)},
σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd :=
λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩,
rw ← finset.sum_subset (finset.subset_univ preserving_snd) _,
-- And that these are in bijection with `o → equiv.perm m`.
rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _,
prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm,
{ intros σ _,
rw mem_preserving_snd,
rintros ⟨k, x⟩,
simp },
{ intros σ _,
rw finset.prod_mul_distrib,
congr,
{ convert congr_arg (λ (x : units ℤ), (↑x : R)) (sign_prod_congr_left (λ k, σ k _)).symm,
simp, congr, ext, congr },
rw [← finset.univ_product_univ, finset.prod_product, finset.prod_comm],
simp },
{ intros σ σ' _ _ eq,
ext x hx k,
simp only at eq,
have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) =
prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) :=
λ k x, by rw eq,
simp only [prod_congr_left_apply, prod.mk.inj_iff] at this,
exact (this k x).1 },
{ intros σ hσ,
rw mem_preserving_snd at hσ,
have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd,
{ intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } },
have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k),
{ intros k x,
ext; simp [hσ] },
have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k),
{ intros k x,
conv_lhs { rw ← perm.apply_inv_self σ (x, k) },
ext; simp [hσ'] },
refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩,
{ intro x,
simp [mk_apply_eq, mk_inv_apply_eq] },
{ intro x,
simp [mk_apply_eq, mk_inv_apply_eq] },
{ apply finset.mem_univ },
{ ext ⟨k, x⟩; simp [hσ] } },
{ intros σ _ hσ,
rw mem_preserving_snd at hσ,
obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ,
rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero],
rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne],
exact hkx }
end
end matrix
|
e772c371e69aa533cedc909d525eb430d4192e71 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/nat/parity.lean | 7b0b2ac36ed8953784048a83bca8f4f1bedd7075 | [
"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,693 | 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 natural numbers.
-/
import data.nat.modeq
namespace nat
@[simp] theorem mod_two_ne_one {n : nat} : ¬ n % 2 = 1 ↔ n % 2 = 0 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
@[simp] theorem mod_two_ne_zero {n : nat} : ¬ n % 2 = 0 ↔ n % 2 = 1 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
/-- A natural number `n` is `even` if `2 | n`. -/
def even (n : nat) : Prop := 2 ∣ n
theorem even_iff {n : nat} : 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]
instance : decidable_pred even :=
λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm
mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`"
@[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩
@[simp] theorem not_even_one : ¬ even 1 :=
by rw even_iff; apply one_ne_zero
@[simp] theorem even_bit0 (n : nat) : even (bit0 n) :=
⟨n, by rw [bit0, two_mul]⟩
@[parity_simps] theorem even_add {m n : nat} : 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₂],
{ 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
theorem even.add {m n : ℕ} (hm : m.even) (hn : n.even) : (m + n).even :=
even_add.2 $ by simp only [*]
@[simp] theorem not_even_bit1 (n : nat) : ¬ even (bit1 n) :=
by simp [bit1] with parity_simps
@[parity_simps] theorem even_sub {m n : nat} (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) :=
begin
conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] },
by_cases h : even n; simp [h]
end
theorem even.sub {m n : ℕ} (hm : m.even) (hn : n.even) : (m - n).even :=
(le_total n m).elim
(λ h, by simp only [even_sub h, *])
(λ h, by simp only [sub_eq_zero_of_le h, even_zero])
@[parity_simps] theorem even_succ {n : nat} : even (succ n) ↔ ¬ even n :=
by rw [succ_eq_add_one, even_add]; simp [not_even_one]
@[parity_simps] theorem even_mul {m n : nat} : 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₂],
{ 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 n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 :=
by { induction n with n ih; simp [*, pow_succ, even_mul], tauto }
lemma even_div {a b : ℕ} : even (a / b) ↔ a % (2 * b) / b = 0 :=
by rw [even, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm]
theorem neg_one_pow_eq_one_iff_even {α : Type*} [ring α] {n : ℕ} (h1 : (-1 : α) ≠ 1):
(-1 : α) ^ n = 1 ↔ even n :=
⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2
(λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, _root_.pow_one] at h; exact (h1 h).elim),
λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩
-- Here are examples of how `parity_simps` can be used with `nat`.
example (m n : nat) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) :=
by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps
example : ¬ even 25394535 :=
by simp
end nat
|
91e653c9f707ad7a68c2eb8a46bac557d83c8706 | 3ef5255cebe505e5ab251615d9fbf31a132f461d | /lean/old/test2.lean | a4991eb04c06f94727fd42b0a3225b9dccf4f330 | [] | no_license | avigad/scratch | 42441a2ea94918049391e44d7adab304d3adea51 | 3fb9cef15bc5581c9602561427a7f295917990a2 | refs/heads/master | 1,608,917,412,424 | 1,473,078,921,000 | 1,473,078,921,000 | 17,224,172 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,640 | lean | import path_new
open path
inductive category [class] (ob : Type) [fob : fibrant ob] : Type :=
mk : Π (hom : ob → ob → Type) [fhom : Πa b : ob, fibrant (hom a b)]
(comp : Π⦃a b c : ob⦄, hom b c → hom a b → hom a c)
(id : Π {a : ob}, hom a a),
(Π ⦃a b c d : ob⦄ {h : hom c d} {g : hom b c} {f : hom a b},
comp h (comp g f) ≈ comp (comp h g) f) →
(Π ⦃a b : ob⦄ {f : hom a b}, comp id f ≈ f) →
(Π ⦃a b : ob⦄ {f : hom a b}, comp f id ≈ f) →
category ob
namespace category
variables {ob : Type} [fob : fibrant ob] [C : category ob]
variables {a b c d : ob}
include C
definition hom [reducible] : ob → ob → Type := rec (λ hom fhom compose id assoc idr idl, hom) C
-- note: needs to be reducible to typecheck composition in opposite category
definition fhom [instance] [reducible] : Πa b : ob, fibrant (hom a b) :=
rec (λ hom fhom compose id assoc idr idl, fhom) C
end category
inductive Category : Type := mk : Π (ob : Type) [fob : fibrant ob], category ob → Category
namespace category
definition objects [coercion] [reducible] (C : Category) : Type :=
Category.rec (fun c fc s, c) C
definition objects_fibrant [instance] [reducible] (C : Category) : fibrant (objects C) :=
Category.rec (fun c fc s, fc) C
definition category_instance [instance] [reducible] (C : Category) :
category (objects C) :=
Category.rec (fun c fc s, s) C
end category
open category
-- this loops
theorem test.{u} (A : Type.{u}) [h : fibrant Category] : Type.{u} := A
section
variable (A : Type)
definition test2 := test A
end
|
5c7679a5b06ddad8c6078ba8b1e888499b9e735b | aa5a655c05e5359a70646b7154e7cac59f0b4132 | /stage0/src/Lean/Elab/Quotation.lean | 78879886714fd271625f0ca87eeaf539bd5170e0 | [
"Apache-2.0"
] | permissive | lambdaxymox/lean4 | ae943c960a42247e06eff25c35338268d07454cb | 278d47c77270664ef29715faab467feac8a0f446 | refs/heads/master | 1,677,891,867,340 | 1,612,500,005,000 | 1,612,500,005,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,566 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
Elaboration of syntax quotations as terms and patterns (in `match_syntax`). See also `./Hygiene.lean` for the basic
hygiene workings and data types.
-/
import Lean.Syntax
import Lean.ResolveName
import Lean.Elab.Term
import Lean.Elab.Quotation.Util
import Lean.Parser.Term
namespace Lean.Elab.Term.Quotation
open Lean.Parser.Term
open Lean.Syntax
open Meta
register_builtin_option hygiene : Bool := {
defValue := true
descr := "Annotate identifiers in quotations such that they are resolved relative to the scope at their declaration, not that at their eventual use/expansion, to avoid accidental capturing. Note that quotations/notations already defined are unaffected."
}
/-- `C[$(e)]` ~> `let a := e; C[$a]`. Used in the implementation of antiquot splices. -/
private partial def floatOutAntiquotTerms : Syntax → StateT (Syntax → TermElabM Syntax) TermElabM Syntax
| stx@(Syntax.node k args) => do
if isAntiquot stx && !isEscapedAntiquot stx then
let e := getAntiquotTerm stx
if !e.isIdent || !e.getId.isAtomic then
return ← withFreshMacroScope do
let a ← `(a)
modify (fun cont stx => (`(let $a:ident := $e; $stx) : TermElabM _))
stx.setArg 2 a
Syntax.node k (← args.mapM floatOutAntiquotTerms)
| stx => pure stx
private def getSepFromSplice (splice : Syntax) : Syntax := do
let Syntax.atom _ sep ← getAntiquotSpliceSuffix splice | unreachable!
Syntax.mkStrLit (sep.dropRight 1)
partial def mkTuple : Array Syntax → TermElabM Syntax
| #[] => `(Unit.unit)
| #[e] => e
| es => do
let stx ← mkTuple (es.eraseIdx 0)
`(Prod.mk $(es[0]) $stx)
def resolveSectionVariable (sectionVars : NameMap Name) (id : Name) : List (Name × List String) :=
-- decode macro scopes from name before recursion
let extractionResult := extractMacroScopes id
let rec loop : Name → List String → List (Name × List String)
| id@(Name.str p s _), projs =>
-- NOTE: we assume that macro scopes always belong to the projected constant, not the projections
let id := { extractionResult with name := id }.review
match sectionVars.find? id with
| some newId => [(newId, projs)]
| none => loop p (s::projs)
| _, _ => []
loop extractionResult.name []
-- Elaborate the content of a syntax quotation term
private partial def quoteSyntax : Syntax → TermElabM Syntax
| Syntax.ident info rawVal val preresolved => do
if !hygiene.get (← getOptions) then
return ← `(Syntax.ident info $(quote rawVal) $(quote val) $(quote preresolved))
-- Add global scopes at compilation time (now), add macro scope at runtime (in the quotation).
-- See the paper for details.
let r ← resolveGlobalName val
-- extension of the paper algorithm: also store unique section variable names as top-level scopes
-- so they can be captured and used inside the section, but not outside
let r' := resolveSectionVariable (← read).sectionVars val
let preresolved := r ++ r' ++ preresolved
let val := quote val
-- `scp` is bound in stxQuot.expand
`(Syntax.ident info $(quote rawVal) (addMacroScope mainModule $val scp) $(quote preresolved))
-- if antiquotation, insert contents as-is, else recurse
| stx@(Syntax.node k _) => do
if isAntiquot stx && !isEscapedAntiquot stx then
getAntiquotTerm stx
else if isTokenAntiquot stx && !isEscapedAntiquot stx then
match stx[0] with
| Syntax.atom _ val => `(Syntax.atom (Option.getD (getHeadInfo $(getAntiquotTerm stx)) info) $(quote val))
| _ => throwErrorAt stx "expected token"
else if isAntiquotSuffixSplice stx && !isEscapedAntiquot stx then
-- splices must occur in a `many` node
throwErrorAt stx "unexpected antiquotation splice"
else if isAntiquotSplice stx && !isEscapedAntiquot stx then
throwErrorAt stx "unexpected antiquotation splice"
else
let empty ← `(Array.empty);
-- if escaped antiquotation, decrement by one escape level
let stx := unescapeAntiquot stx
let args ← stx.getArgs.foldlM (fun args arg => do
if k == nullKind && isAntiquotSuffixSplice arg then
let antiquot := getAntiquotSuffixSpliceInner arg
match antiquotSuffixSplice? arg with
| `optional => `(Array.appendCore $args (match $(getAntiquotTerm antiquot):term with
| some x => Array.empty.push x
| none => Array.empty))
| `many => `(Array.appendCore $args $(getAntiquotTerm antiquot))
| `sepBy => `(Array.appendCore $args (@SepArray.elemsAndSeps $(getSepFromSplice arg) $(getAntiquotTerm antiquot)))
| k => throwErrorAt! arg "invalid antiquotation suffix splice kind '{k}'"
else if k == nullKind && isAntiquotSplice arg then
let k := antiquotSpliceKind? arg
let (arg, bindLets) ← floatOutAntiquotTerms arg |>.run pure
let inner ← (getAntiquotSpliceContents arg).mapM quoteSyntax
let ids ← getAntiquotationIds arg
if ids.isEmpty then
throwErrorAt stx "antiquotation splice must contain at least one antiquotation"
let arr ← match k with
| `optional => `(match $[$ids:ident],* with
| $[some $ids:ident],* => $(quote inner)
| none => Array.empty)
| _ =>
let arr ← ids[:ids.size-1].foldrM (fun id arr => `(Array.zip $id $arr)) ids.back
`(Array.map (fun $(← mkTuple ids) => $(inner[0])) $arr)
let arr ←
if k == `sepBy then
`(mkSepArray $arr (mkAtom $(getSepFromSplice arg)))
else arr
let arr ← bindLets arr
`(Array.appendCore $args $arr)
else do
let arg ← quoteSyntax arg;
`(Array.push $args $arg)) empty
`(Syntax.node $(quote k) $args)
| Syntax.atom _ val =>
`(Syntax.atom info $(quote val))
| Syntax.missing => unreachable!
def stxQuot.expand (stx : Syntax) : TermElabM Syntax := do
/- Syntax quotations are monadic values depending on the current macro scope. For efficiency, we bind
the macro scope once for each quotation, then build the syntax tree in a completely pure computation
depending on this binding. Note that regular function calls do not introduce a new macro scope (i.e.
we preserve referential transparency), so we can refer to this same `scp` inside `quoteSyntax` by
including it literally in a syntax quotation. -/
-- TODO: simplify to `(do scp ← getCurrMacroScope; pure $(quoteSyntax quoted))
let stx ← quoteSyntax stx.getQuotContent;
`(Bind.bind MonadRef.mkInfoFromRefPos (fun info =>
Bind.bind getCurrMacroScope (fun scp =>
Bind.bind getMainModule (fun mainModule => Pure.pure $stx))))
/- NOTE: It may seem like the newly introduced binding `scp` may accidentally
capture identifiers in an antiquotation introduced by `quoteSyntax`. However,
note that the syntax quotation above enjoys the same hygiene guarantees as
anywhere else in Lean; that is, we implement hygienic quotations by making
use of the hygienic quotation support of the bootstrapped Lean compiler!
Aside: While this might sound "dangerous", it is in fact less reliant on a
"chain of trust" than other bootstrapping parts of Lean: because this
implementation itself never uses `scp` (or any other identifier) both inside
and outside quotations, it can actually correctly be compiled by an
unhygienic (but otherwise correct) implementation of syntax quotations. As
long as it is then compiled again with the resulting executable (i.e. up to
stage 2), the result is a correct hygienic implementation. In this sense the
implementation is "self-stabilizing". It was in fact originally compiled
by an unhygienic prototype implementation. -/
macro "elabStxQuot!" kind:ident : command =>
`(@[builtinTermElab $kind:ident] def elabQuot : TermElab := adaptExpander stxQuot.expand)
--
elabStxQuot! Parser.Level.quot
elabStxQuot! Parser.Term.quot
elabStxQuot! Parser.Term.funBinder.quot
elabStxQuot! Parser.Term.bracketedBinder.quot
elabStxQuot! Parser.Term.matchDiscr.quot
elabStxQuot! Parser.Tactic.quot
elabStxQuot! Parser.Tactic.quotSeq
elabStxQuot! Parser.Term.stx.quot
elabStxQuot! Parser.Term.prec.quot
elabStxQuot! Parser.Term.attr.quot
elabStxQuot! Parser.Term.prio.quot
elabStxQuot! Parser.Term.doElem.quot
elabStxQuot! Parser.Term.dynamicQuot
/- match -/
-- an "alternative" of patterns plus right-hand side
private abbrev Alt := List Syntax × Syntax
/--
In a single match step, we match the first discriminant against the "head" of the first pattern of the first
alternative. This datatype describes what kind of check this involves, which helps other patterns decide if
they are covered by the same check and don't have to be checked again (see also `MatchResult`). -/
inductive HeadCheck where
-- match step that always succeeds: _, x, `($x), ...
| unconditional
-- match step based on kind and, optionally, arity of discriminant
-- If `arity` is given, that number of new discriminants is introduced. `covered` patterns should then introduce the
-- same number of new patterns.
-- We actually check the arity at run time only in the case of `null` nodes since it should otherwise by implied by
-- the node kind.
-- without arity: `($x:k)
-- with arity: any quotation without an antiquotation head pattern
| shape (k : SyntaxNodeKind) (arity : Option Nat)
-- Match step that succeeds on `null` nodes of arity at least `numPrefix + numSuffix`, introducing discriminants
-- for the first `numPrefix` children, one `null` node for those in between, and for the `numSuffix` last children.
-- example: `([$x, $xs,*, $y]) is `slice 2 2`
| slice (numPrefix numSuffix : Nat)
-- other, complicated match step that will probably only cover identical patterns
-- example: antiquotation splices `($[...]*)
| other (pat : Syntax)
open HeadCheck
/-- Describe whether a pattern is covered by a head check (induced by the pattern itself or a different pattern). -/
inductive MatchResult where
-- Pattern agrees with head check, remove and transform remaining alternative.
-- If `exhaustive` is `false`, *also* include unchanged alternative in the "no" branch.
| covered (f : Alt → TermElabM Alt) (exhaustive : Bool)
-- Pattern disagrees with head check, include in "no" branch only
| uncovered
-- Pattern is not quite sure yet; include unchanged in both branches
| undecided
open MatchResult
/-- All necessary information on a pattern head. -/
structure HeadInfo where
-- check induced by the pattern
check : HeadCheck
-- compute compatibility of pattern with given head check
onMatch (taken : HeadCheck) : MatchResult
-- actually run the specified head check, with the discriminant bound to `discr`
doMatch (yes : (newDiscrs : List Syntax) → TermElabM Syntax) (no : TermElabM Syntax) : TermElabM Syntax
/-- Adapt alternatives that do not introduce new discriminants in `doMatch`, but are covered by those that do so. -/
private def noOpMatchAdaptPats : HeadCheck → Alt → Alt
| shape k (some sz), (pats, rhs) => (List.replicate sz (Unhygienic.run `(_)) ++ pats, rhs)
| slice p s, (pats, rhs) => (List.replicate (p + 1 + s) (Unhygienic.run `(_)) ++ pats, rhs)
| _, alt => alt
private def adaptRhs (fn : Syntax → TermElabM Syntax) : Alt → TermElabM Alt
| (pats, rhs) => do (pats, ← fn rhs)
private partial def getHeadInfo (alt : Alt) : TermElabM HeadInfo :=
let pat := alt.fst.head!
let unconditionally (rhsFn) := pure {
check := unconditional,
doMatch := fun yes no => yes [],
onMatch := fun taken => covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (match taken with | unconditional => true | _ => false)
}
-- quotation pattern
if isQuot pat then
let quoted := getQuotContent pat
if quoted.isAtom then
-- We assume that atoms are uniquely determined by the node kind and never have to be checked
unconditionally pure
else if quoted.isTokenAntiquot then
unconditionally (`(let $(quoted.getAntiquotTerm) := discr; $(·)))
else if isAntiquot quoted && !isEscapedAntiquot quoted then
-- quotation contains a single antiquotation
let k := antiquotKind? quoted |>.get!
-- Antiquotation kinds like `$id:ident` influence the parser, but also need to be considered by
-- `match` (but not by quotation terms). For example, `($id:ident) and `($e) are not
-- distinguishable without checking the kind of the node to be captured. Note that some
-- antiquotations like the latter one for terms do not correspond to any actual node kind
-- (signified by `k == Name.anonymous`), so we would only check for `ident` here.
--
-- if stx.isOfKind `ident then
-- let id := stx; let e := stx; ...
-- else
-- let e := stx; ...
let anti := getAntiquotTerm quoted
if anti.isIdent then
let rhsFn := (`(let $anti := discr; $(·)))
if k == Name.anonymous then unconditionally rhsFn else pure {
check := shape k none,
onMatch := fun
| taken@(shape k' sz) =>
if k' == k then
covered (adaptRhs rhsFn ∘ noOpMatchAdaptPats taken) (exhaustive := sz.isNone)
else uncovered
| _ => uncovered,
doMatch := fun yes no => do `(cond (Syntax.isOfKind discr $(quote k)) $(← yes []) $(← no)),
}
else throwErrorAt! anti "match_syntax: antiquotation must be variable {anti}"
else if isAntiquotSuffixSplice quoted then throwErrorAt quoted "unexpected antiquotation splice"
else if isAntiquotSplice quoted then throwErrorAt quoted "unexpected antiquotation splice"
else if quoted.getArgs.size == 1 && isAntiquotSuffixSplice quoted[0] then
let anti := getAntiquotTerm (getAntiquotSuffixSpliceInner quoted[0])
unconditionally fun rhs => match antiquotSuffixSplice? quoted[0] with
| `optional => `(let $anti := Syntax.getOptional? discr; $rhs)
| `many => `(let $anti := Syntax.getArgs discr; $rhs)
| `sepBy => `(let $anti := @SepArray.mk $(getSepFromSplice quoted[0]) (Syntax.getArgs discr); $rhs)
| k => throwErrorAt! quoted "invalid antiquotation suffix splice kind '{k}'"
else if quoted.getArgs.size == 1 && isAntiquotSplice quoted[0] then pure {
check := other pat,
onMatch := fun
| other pat' => if pat' == pat then covered pure (exhaustive := true) else undecided
| _ => undecided,
doMatch := fun yes no => do
let splice := quoted[0]
let k := antiquotSpliceKind? splice
let contents := getAntiquotSpliceContents splice
let ids ← getAntiquotationIds splice
let yes ← yes []
let no ← no
match k with
| `optional =>
let nones := mkArray ids.size (← `(none))
`(let* yes _ $ids* := $yes;
if discr.isNone then yes () $[ $nones]*
else match discr with
| `($(mkNullNode contents)) => yes () $[ (some $ids)]*
| _ => $no)
| _ =>
let mut discrs ← `(Syntax.getArgs discr)
if k == `sepBy then
discrs ← `(Array.getSepElems $discrs)
let tuple ← mkTuple ids
let mut yes := yes
let resId ← match ids with
| #[id] => id
| _ =>
for id in ids do
yes ← `(let $id := tuples.map (fun $tuple => $id); $yes)
`(tuples)
`(match ($(discrs).sequenceMap fun
| `($(contents[0])) => some $tuple
| _ => none) with
| some $resId => $yes
| none => $no)
}
else if let some idx := quoted.getArgs.findIdx? (fun arg => isAntiquotSuffixSplice arg || isAntiquotSplice arg) then do
/-
pattern of the form `match discr, ... with | `(pat_0 ... pat_(idx-1) $[...]* pat_(idx+1) ...), ...`
transform to
```
if discr.getNumArgs >= $quoted.getNumArgs - 1 then
match discr[0], ..., discr[idx-1], mkNullNode (discr.getArgs.extract idx (discr.getNumArgs - $numSuffix))), ..., discr[quoted.getNumArgs - 1] with
| `(pat_0), ... `(pat_(idx-1)), `($[...])*, `(pat_(idx+1)), ...
```
-/
let numSuffix := quoted.getNumArgs - 1 - idx
pure {
check := slice idx numSuffix
onMatch := fun
| slice p s =>
if p == idx && s == numSuffix then
let argPats := quoted.getArgs.mapIdx fun i arg =>
let arg := if (i : Nat) == idx then mkNullNode #[arg] else arg
Unhygienic.run `(`($(arg)))
covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true)
else uncovered
| _ => uncovered
doMatch := fun yes no => do
let prefixDiscrs ← (List.range idx).mapM (`(Syntax.getArg discr $(quote ·)))
let sliceDiscr ← `(mkNullNode (discr.getArgs.extract $(quote idx) (discr.getNumArgs - $(quote numSuffix))))
let suffixDiscrs ← (List.range numSuffix).mapM fun i =>
`(Syntax.getArg discr (discr.getNumArgs - $(quote (numSuffix - i))))
`(ite (GreaterEq discr.getNumArgs $(quote (quoted.getNumArgs - 1)))
$(← yes (prefixDiscrs ++ sliceDiscr :: suffixDiscrs))
$(← no))
}
else
-- not an antiquotation, or an escaped antiquotation: match head shape
let quoted := unescapeAntiquot quoted
let kind := quoted.getKind
let argPats := quoted.getArgs.map fun arg => Unhygienic.run `(`($(arg)))
pure {
check := shape kind argPats.size,
onMatch := fun taken =>
if (match taken with | shape k' sz => k' == kind && sz == argPats.size | _ => false : Bool) then
covered (fun (pats, rhs) => (argPats.toList ++ pats, rhs)) (exhaustive := true)
else
uncovered,
doMatch := fun yes no => do
let cond ← match kind with
| `null => `(and (Syntax.isOfKind discr $(quote kind)) (BEq.beq (Array.size (Syntax.getArgs discr)) $(quote argPats.size)))
| _ => `(Syntax.isOfKind discr $(quote kind))
let newDiscrs ← (List.range argPats.size).mapM fun i => `(Syntax.getArg discr $(quote i))
`(ite (Eq $cond true) $(← yes newDiscrs) $(← no))
}
else match pat with
| `(_) => unconditionally pure
| `($id:ident) => unconditionally (`(let $id := discr; $(·)))
| `($id:ident@$pat) => do
let info ← getHeadInfo (pat::alt.1.tail!, alt.2)
{ info with onMatch := fun taken => match info.onMatch taken with
| covered f exh => covered (fun alt => f alt >>= adaptRhs (`(let $id := discr; $(·)))) exh
| r => r }
| _ => throwErrorAt! pat "match_syntax: unexpected pattern kind {pat}"
-- Bind right-hand side to new `let*` decl in order to prevent code duplication
private def deduplicate (floatedLetDecls : Array Syntax) : Alt → TermElabM (Array Syntax × Alt)
-- NOTE: new macro scope so that introduced bindings do not collide
| (pats, rhs) => do
if let `($f:ident $[ $args:ident]*) := rhs then
-- looks simple enough/created by this function, skip
return (floatedLetDecls, (pats, rhs))
withFreshMacroScope do
match ← getPatternsVars pats.toArray with
| #[] =>
-- no antiquotations => introduce Unit parameter to preserve evaluation order
let rhs' ← `(rhs Unit.unit)
(floatedLetDecls.push (← `(letDecl|rhs _ := $rhs)), (pats, rhs'))
| vars =>
let rhs' ← `(rhs $vars*)
(floatedLetDecls.push (← `(letDecl|rhs $vars:ident* := $rhs)), (pats, rhs'))
private partial def compileStxMatch (discrs : List Syntax) (alts : List Alt) : TermElabM Syntax := do
trace[Elab.match_syntax]! "match {discrs} with {alts}"
match discrs, alts with
| [], ([], rhs)::_ => pure rhs -- nothing left to match
| _, [] => throwError "non-exhaustive 'match_syntax'"
| discr::discrs, alt::alts => do
let info ← getHeadInfo alt
let pat := alt.1.head!
let alts ← (alt::alts).mapM fun alt => do ((← getHeadInfo alt).onMatch info.check, alt)
let mut yesAlts := #[]
let mut undecidedAlts := #[]
let mut nonExhaustiveAlts := #[]
let mut floatedLetDecls := #[]
for alt in alts do
let mut alt := alt
match alt with
| (covered f exh, alt) =>
-- we can only factor out a common check if there are no undecided patterns in between;
-- otherwise we would change the order of alternatives
if undecidedAlts.isEmpty then
yesAlts ← yesAlts.push <$> f (alt.1.tail!, alt.2)
if !exh then
nonExhaustiveAlts := nonExhaustiveAlts.push alt
else
(floatedLetDecls, alt) ← deduplicate floatedLetDecls alt
undecidedAlts := undecidedAlts.push alt
nonExhaustiveAlts := nonExhaustiveAlts.push alt
| (undecided, alt) =>
(floatedLetDecls, alt) ← deduplicate floatedLetDecls alt
undecidedAlts := undecidedAlts.push alt
nonExhaustiveAlts := nonExhaustiveAlts.push alt
| (uncovered, alt) =>
nonExhaustiveAlts := nonExhaustiveAlts.push alt
let mut stx ← info.doMatch
(yes := fun newDiscrs => do
let mut yesAlts := yesAlts
if !undecidedAlts.isEmpty then
-- group undecided alternatives in a new default case `| discr2, ... => match discr, discr2, ... with ...`
let vars ← discrs.mapM fun _ => withFreshMacroScope `(discr)
let pats := List.replicate newDiscrs.length (Unhygienic.run `(_)) ++ vars
let alts ← undecidedAlts.mapM fun alt => `(matchAltExpr| | $(alt.1.toArray),* => $(alt.2))
let rhs ← `(match discr, $[$(vars.toArray):term],* with $alts:matchAlt*)
yesAlts := yesAlts.push (pats, rhs)
withFreshMacroScope $ compileStxMatch (newDiscrs ++ discrs) yesAlts.toList)
(no := withFreshMacroScope $ compileStxMatch (discr::discrs) nonExhaustiveAlts.toList)
for d in floatedLetDecls do
stx ← `(let* $d:letDecl; $stx)
`(let discr := $discr; $stx)
| _, _ => unreachable!
def match_syntax.expand (stx : Syntax) : TermElabM Syntax := do
match stx with
| `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do
if !patss.any (·.any (fun
| `($id@$pat) => pat.isQuot
| pat => pat.isQuot)) then
-- no quotations => fall back to regular `match`
throwUnsupportedSyntax
let stx ← compileStxMatch discrs.toList (patss.map (·.toList) |>.zip rhss).toList
trace[Elab.match_syntax.result]! "{stx}"
stx
| _ => throwUnsupportedSyntax
@[builtinTermElab «match»] def elabMatchSyntax : TermElab :=
adaptExpander match_syntax.expand
builtin_initialize
registerTraceClass `Elab.match_syntax
registerTraceClass `Elab.match_syntax.result
end Lean.Elab.Term.Quotation
|
c06081856c721fec7295c20c8745e3340925bcfd | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/algebra/big_operators/order.lean | 23ae1ab25e660ab4fdb5858c7124719ddd63c426 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 12,072 | 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 [discrete_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
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 [decidable_eq γ] {f : α → γ} (s : finset α)
(n : ℕ) (hn : ∀ a ∈ s.image f, (s.filter (λ x, f x = a)).card ≤ n) :
s.card ≤ n * (s.image f).card :=
calc s.card = (∑ a in s.image f, (s.filter (λ x, f x = a)).card) :
card_eq_sum_card_image _ _
... ≤ (∑ _ in s.image f, n) : sum_le_sum hn
... = _ : by simp [mul_comm]
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_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 decidable_linear_ordered_cancel_comm_monoid
variables [decidable_linear_ordered_cancel_add_comm_monoid β]
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
classical,
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 : by { apply 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 decidable_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
/-- 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
open_locale classical
/-- 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
open opposite
/-- Moving to the opposite additive commutative monoid commutes with summing. -/
@[simp] lemma op_sum [add_comm_monoid β] {s : finset α} (f : α → β) :
op (∑ x in s, f x) = ∑ x in s, op (f x) :=
(@op_add_hom β _).map_sum _ _
@[simp] lemma unop_sum [add_comm_monoid β] {s : finset α} (f : α → βᵒᵖ) :
unop (∑ x in s, f x) = ∑ x in s, unop (f x) :=
(@unop_add_hom β _).map_sum _ _
end with_top
|
6bada7b2ddb855b2cd0985148a76f54e91e3a146 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/set1.lean | a0d5d681d17720669fcaa2a807115319748e7355 | [
"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 | 237 | lean | variables A : Type
instance : has_subset (set A) := ⟨λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t⟩
example (s₁ s₂ s₃ : set A) : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ :=
assume h₁ h₂ a ains₁,
h₂ (h₁ ains₁)
|
77e7ea26818a36ed7b66e2522a72f515d2c0eb10 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/data/rbtree/basic.lean | 2e95df9fa44fb2f21f8bb6fd54b304c080ba7bd2 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,374 | 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
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
universes u
namespace Mathlib
namespace rbnode
inductive is_node_of {α : Type u} : rbnode α → rbnode α → α → rbnode α → Prop
where
| of_red : ∀ (l : rbnode α) (v : α) (r : rbnode α), is_node_of (red_node l v r) l v r
| of_black : ∀ (l : rbnode α) (v : α) (r : rbnode α), is_node_of (black_node l v r) l v r
def lift {α : Type u} (lt : α → α → Prop) : Option α → Option α → Prop :=
sorry
inductive is_searchable {α : Type u} (lt : α → α → Prop) : rbnode α → Option α → Option α → Prop
where
| leaf_s : ∀ {lo hi : Option α}, lift lt lo hi → is_searchable lt leaf lo hi
| red_s : ∀ {l r : rbnode α} {v : α} {lo hi : Option α},
is_searchable lt l lo (some v) → is_searchable lt r (some v) hi → is_searchable lt (red_node l v r) lo hi
| black_s : ∀ {l r : rbnode α} {v : α} {lo hi : Option α},
is_searchable lt l lo (some v) → is_searchable lt r (some v) hi → is_searchable lt (black_node l v r) lo hi
theorem lo_lt_hi {α : Type u} {t : rbnode α} {lt : α → α → Prop} [is_trans α lt] {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → lift lt lo hi := sorry
theorem is_searchable_of_is_searchable_of_incomp {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {lo : Option α} {hi : α} {hi' : α} (hc : ¬lt hi' hi ∧ ¬lt hi hi') (hs : is_searchable lt t lo (some hi)) : is_searchable lt t lo (some hi') := sorry
theorem is_searchable_of_incomp_of_is_searchable {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {lo : α} {lo' : α} {hi : Option α} (hc : ¬lt lo' lo ∧ ¬lt lo lo') (hs : is_searchable lt t (some lo) hi) : is_searchable lt t (some lo') hi := sorry
theorem is_searchable_some_low_of_is_searchable_of_lt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} [is_trans α lt] {lo : α} {hi : Option α} {lo' : α} (hlt : lt lo' lo) (hs : is_searchable lt t (some lo) hi) : is_searchable lt t (some lo') hi := sorry
theorem is_searchable_none_low_of_is_searchable_some_low {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} {y : α} {hi : Option α} (hlt : is_searchable lt t (some y) hi) : is_searchable lt t none hi := sorry
theorem is_searchable_some_high_of_is_searchable_of_lt {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} [is_trans α lt] {lo : Option α} {hi : α} {hi' : α} (hlt : lt hi hi') (hs : is_searchable lt t lo (some hi)) : is_searchable lt t lo (some hi') := sorry
theorem is_searchable_none_high_of_is_searchable_some_high {α : Type u} {lt : α → α → Prop} [DecidableRel lt] {t : rbnode α} {lo : Option α} {y : α} (hlt : is_searchable lt t lo (some y)) : is_searchable lt t lo none := sorry
theorem range {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {t : rbnode α} {x : α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → mem lt x t → lift lt lo (some x) ∧ lift lt (some x) hi := sorry
theorem lt_of_mem_left {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {x : α}, mem lt x l → lt x y := sorry
theorem lt_of_mem_right {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {z : α}, mem lt z r → lt y z := sorry
theorem lt_of_mem_left_right {α : Type u} {lt : α → α → Prop} [DecidableRel lt] [is_strict_weak_order α lt] {y : α} {t : rbnode α} {l : rbnode α} {r : rbnode α} {lo : Option α} {hi : Option α} : is_searchable lt t lo hi → is_node_of t l y r → ∀ {x z : α}, mem lt x l → mem lt z r → lt x z := sorry
inductive is_red_black {α : Type u} : rbnode α → color → ℕ → Prop
where
| leaf_rb : is_red_black leaf color.black 0
| red_rb : ∀ {v : α} {l r : rbnode α} {n : ℕ},
is_red_black l color.black n → is_red_black r color.black n → is_red_black (red_node l v r) color.red n
| black_rb : ∀ {v : α} {l r : rbnode α} {n : ℕ} {c₁ c₂ : color},
is_red_black l c₁ n → is_red_black r c₂ n → is_red_black (black_node l v r) color.black (Nat.succ n)
theorem depth_min {α : Type u} {c : color} {n : ℕ} {t : rbnode α} : is_red_black t c n → depth min t ≥ n := sorry
theorem depth_max' {α : Type u} {c : color} {n : ℕ} {t : rbnode α} : is_red_black t c n → depth max t ≤ upper c n := sorry
theorem depth_max {α : Type u} {c : color} {n : ℕ} {t : rbnode α} (h : is_red_black t c n) : depth max t ≤ bit0 1 * n + 1 :=
le_trans (depth_max' h) (upper_le c n)
theorem balanced {α : Type u} {c : color} {n : ℕ} {t : rbnode α} (h : is_red_black t c n) : bit0 1 * depth min t + 1 ≥ depth max t :=
le_trans (depth_max h) (nat.succ_le_succ (nat.mul_le_mul_left (bit0 1) (depth_min h)))
|
1e8ad314a8bc16d366796aa342865d4116005225 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/topology/homeomorph.lean | eaf7605b21f74c829545e3832beb807406be7d85 | [
"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,187 | 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, Patrick Massot, Sébastien Gouëzel, Zhouhang Zhou, Reid Barton
-/
import logic.equiv.fin
import topology.dense_embedding
import topology.support
/-!
# Homeomorphisms
This file defines homeomorphisms between two topological spaces. They are bijections with both
directions continuous. We denote homeomorphisms with the notation `≃ₜ`.
# Main definitions
* `homeomorph α β`: The type of homeomorphisms from `α` to `β`.
This type can be denoted using the following notation: `α ≃ₜ β`.
# Main results
* Pretty much every topological property is preserved under homeomorphisms.
* `homeomorph.homeomorph_of_continuous_open`: A continuous bijection that is
an open map is a homeomorphism.
-/
open set filter
open_locale topological_space
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Homeomorphism between `α` and `β`, also called topological isomorphism -/
@[nolint has_inhabited_instance] -- not all spaces are homeomorphic to each other
structure homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β]
extends α ≃ β :=
(continuous_to_fun : continuous to_fun . tactic.interactive.continuity')
(continuous_inv_fun : continuous inv_fun . tactic.interactive.continuity')
infix ` ≃ₜ `:25 := homeomorph
namespace homeomorph
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
instance : has_coe_to_fun (α ≃ₜ β) (λ _, α → β) := ⟨λe, e.to_equiv⟩
@[simp] lemma homeomorph_mk_coe (a : equiv α β) (b c) :
((homeomorph.mk a b c) : α → β) = a :=
rfl
@[simp] lemma coe_to_equiv (h : α ≃ₜ β) : ⇑h.to_equiv = h := rfl
/-- Inverse of a homeomorphism. -/
protected def symm (h : α ≃ₜ β) : β ≃ₜ α :=
{ continuous_to_fun := h.continuous_inv_fun,
continuous_inv_fun := h.continuous_to_fun,
to_equiv := h.to_equiv.symm }
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply (h : α ≃ₜ β) : α → β := h
/-- See Note [custom simps projection] -/
def simps.symm_apply (h : α ≃ₜ β) : β → α := h.symm
initialize_simps_projections homeomorph
(to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, -to_equiv)
lemma to_equiv_injective : function.injective (to_equiv : α ≃ₜ β → α ≃ β)
| ⟨e, h₁, h₂⟩ ⟨e', h₁', h₂'⟩ rfl := rfl
@[ext] lemma ext {h h' : α ≃ₜ β} (H : ∀ x, h x = h' x) : h = h' :=
to_equiv_injective $ equiv.ext H
/-- Identity map as a homeomorphism. -/
@[simps apply {fully_applied := ff}]
protected def refl (α : Type*) [topological_space α] : α ≃ₜ α :=
{ continuous_to_fun := continuous_id,
continuous_inv_fun := continuous_id,
to_equiv := equiv.refl α }
/-- Composition of two homeomorphisms. -/
protected def trans (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) : α ≃ₜ γ :=
{ continuous_to_fun := h₂.continuous_to_fun.comp h₁.continuous_to_fun,
continuous_inv_fun := h₁.continuous_inv_fun.comp h₂.continuous_inv_fun,
to_equiv := equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ₜ β) (h₂ : β ≃ₜ γ) (a : α) : h₁.trans h₂ a = h₂ (h₁ a) := rfl
@[simp] lemma homeomorph_mk_coe_symm (a : equiv α β) (b c) :
((homeomorph.mk a b c).symm : β → α) = a.symm :=
rfl
@[simp] lemma refl_symm : (homeomorph.refl α).symm = homeomorph.refl α := rfl
@[continuity]
protected lemma continuous (h : α ≃ₜ β) : continuous h := h.continuous_to_fun
@[continuity] -- otherwise `by continuity` can't prove continuity of `h.to_equiv.symm`
protected lemma continuous_symm (h : α ≃ₜ β) : continuous (h.symm) := h.continuous_inv_fun
@[simp] lemma apply_symm_apply (h : α ≃ₜ β) (x : β) : h (h.symm x) = x :=
h.to_equiv.apply_symm_apply x
@[simp] lemma symm_apply_apply (h : α ≃ₜ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
protected lemma bijective (h : α ≃ₜ β) : function.bijective h := h.to_equiv.bijective
protected lemma injective (h : α ≃ₜ β) : function.injective h := h.to_equiv.injective
protected lemma surjective (h : α ≃ₜ β) : function.surjective h := h.to_equiv.surjective
/-- Change the homeomorphism `f` to make the inverse function definitionally equal to `g`. -/
def change_inv (f : α ≃ₜ β) (g : β → α) (hg : function.right_inverse g f) : α ≃ₜ β :=
have g = f.symm, from funext (λ x, calc g x = f.symm (f (g x)) : (f.left_inv (g x)).symm
... = f.symm x : by rw hg x),
{ to_fun := f,
inv_fun := g,
left_inv := by convert f.left_inv,
right_inv := by convert f.right_inv,
continuous_to_fun := f.continuous,
continuous_inv_fun := by convert f.symm.continuous }
@[simp] lemma symm_comp_self (h : α ≃ₜ β) : ⇑h.symm ∘ ⇑h = id :=
funext h.symm_apply_apply
@[simp] lemma self_comp_symm (h : α ≃ₜ β) : ⇑h ∘ ⇑h.symm = id :=
funext h.apply_symm_apply
@[simp] lemma range_coe (h : α ≃ₜ β) : range h = univ :=
h.surjective.range_eq
lemma image_symm (h : α ≃ₜ β) : image h.symm = preimage h :=
funext h.symm.to_equiv.image_eq_preimage
lemma preimage_symm (h : α ≃ₜ β) : preimage h.symm = image h :=
(funext h.to_equiv.image_eq_preimage).symm
@[simp] lemma image_preimage (h : α ≃ₜ β) (s : set β) : h '' (h ⁻¹' s) = s :=
h.to_equiv.image_preimage s
@[simp] lemma preimage_image (h : α ≃ₜ β) (s : set α) : h ⁻¹' (h '' s) = s :=
h.to_equiv.preimage_image s
protected lemma inducing (h : α ≃ₜ β) : inducing h :=
inducing_of_inducing_compose h.continuous h.symm.continuous $
by simp only [symm_comp_self, inducing_id]
lemma induced_eq (h : α ≃ₜ β) : topological_space.induced h ‹_› = ‹_› := h.inducing.1.symm
protected lemma quotient_map (h : α ≃ₜ β) : quotient_map h :=
quotient_map.of_quotient_map_compose h.symm.continuous h.continuous $
by simp only [self_comp_symm, quotient_map.id]
lemma coinduced_eq (h : α ≃ₜ β) : topological_space.coinduced h ‹_› = ‹_› :=
h.quotient_map.2.symm
protected lemma embedding (h : α ≃ₜ β) : embedding h :=
⟨h.inducing, h.injective⟩
/-- Homeomorphism given an embedding. -/
noncomputable def of_embedding (f : α → β) (hf : embedding f) : α ≃ₜ (set.range f) :=
{ continuous_to_fun := continuous_subtype_mk _ hf.continuous,
continuous_inv_fun := by simp [hf.continuous_iff, continuous_subtype_coe],
.. equiv.of_injective f hf.inj }
protected lemma second_countable_topology [topological_space.second_countable_topology β]
(h : α ≃ₜ β) :
topological_space.second_countable_topology α :=
h.inducing.second_countable_topology
lemma compact_image {s : set α} (h : α ≃ₜ β) : is_compact (h '' s) ↔ is_compact s :=
h.embedding.is_compact_iff_is_compact_image.symm
lemma compact_preimage {s : set β} (h : α ≃ₜ β) : is_compact (h ⁻¹' s) ↔ is_compact s :=
by rw ← image_symm; exact h.symm.compact_image
@[simp] lemma comap_cocompact (h : α ≃ₜ β) : comap h (cocompact β) = cocompact α :=
(comap_cocompact_le h.continuous).antisymm $
(has_basis_cocompact.le_basis_iff (has_basis_cocompact.comap h)).2 $ λ K hK,
⟨h ⁻¹' K, h.compact_preimage.2 hK, subset.rfl⟩
@[simp] lemma map_cocompact (h : α ≃ₜ β) : map h (cocompact α) = cocompact β :=
by rw [← h.comap_cocompact, map_comap_of_surjective h.surjective]
protected lemma compact_space [compact_space α] (h : α ≃ₜ β) : compact_space β :=
{ compact_univ := by { rw [← image_univ_of_surjective h.surjective, h.compact_image],
apply compact_space.compact_univ } }
protected lemma t0_space [t0_space α] (h : α ≃ₜ β) : t0_space β :=
h.symm.embedding.t0_space
protected lemma t1_space [t1_space α] (h : α ≃ₜ β) : t1_space β :=
h.symm.embedding.t1_space
protected lemma t2_space [t2_space α] (h : α ≃ₜ β) : t2_space β :=
h.symm.embedding.t2_space
protected lemma regular_space [regular_space α] (h : α ≃ₜ β) : regular_space β :=
h.symm.embedding.regular_space
protected lemma dense_embedding (h : α ≃ₜ β) : dense_embedding h :=
{ dense := h.surjective.dense_range,
.. h.embedding }
@[simp] lemma is_open_preimage (h : α ≃ₜ β) {s : set β} : is_open (h ⁻¹' s) ↔ is_open s :=
h.quotient_map.is_open_preimage
@[simp] lemma is_open_image (h : α ≃ₜ β) {s : set α} : is_open (h '' s) ↔ is_open s :=
by rw [← preimage_symm, is_open_preimage]
protected lemma is_open_map (h : α ≃ₜ β) : is_open_map h := λ s, h.is_open_image.2
@[simp] lemma is_closed_preimage (h : α ≃ₜ β) {s : set β} : is_closed (h ⁻¹' s) ↔ is_closed s :=
by simp only [← is_open_compl_iff, ← preimage_compl, is_open_preimage]
@[simp] lemma is_closed_image (h : α ≃ₜ β) {s : set α} : is_closed (h '' s) ↔ is_closed s :=
by rw [← preimage_symm, is_closed_preimage]
protected lemma is_closed_map (h : α ≃ₜ β) : is_closed_map h := λ s, h.is_closed_image.2
protected lemma open_embedding (h : α ≃ₜ β) : open_embedding h :=
open_embedding_of_embedding_open h.embedding h.is_open_map
protected lemma closed_embedding (h : α ≃ₜ β) : closed_embedding h :=
closed_embedding_of_embedding_closed h.embedding h.is_closed_map
protected lemma normal_space [normal_space α] (h : α ≃ₜ β) : normal_space β :=
h.symm.closed_embedding.normal_space
lemma preimage_closure (h : α ≃ₜ β) (s : set β) : h ⁻¹' (closure s) = closure (h ⁻¹' s) :=
h.is_open_map.preimage_closure_eq_closure_preimage h.continuous _
lemma image_closure (h : α ≃ₜ β) (s : set α) : h '' (closure s) = closure (h '' s) :=
by rw [← preimage_symm, preimage_closure]
lemma preimage_interior (h : α ≃ₜ β) (s : set β) : h⁻¹' (interior s) = interior (h ⁻¹' s) :=
h.is_open_map.preimage_interior_eq_interior_preimage h.continuous _
lemma image_interior (h : α ≃ₜ β) (s : set α) : h '' (interior s) = interior (h '' s) :=
by rw [← preimage_symm, preimage_interior]
lemma preimage_frontier (h : α ≃ₜ β) (s : set β) : h ⁻¹' (frontier s) = frontier (h ⁻¹' s) :=
h.is_open_map.preimage_frontier_eq_frontier_preimage h.continuous _
@[to_additive]
lemma _root_.has_compact_mul_support.comp_homeomorph {M} [has_one M] {f : β → M}
(hf : has_compact_mul_support f) (φ : α ≃ₜ β) : has_compact_mul_support (f ∘ φ) :=
hf.comp_closed_embedding φ.closed_embedding
@[simp] lemma map_nhds_eq (h : α ≃ₜ β) (x : α) : map h (𝓝 x) = 𝓝 (h x) :=
h.embedding.map_nhds_of_mem _ (by simp)
lemma symm_map_nhds_eq (h : α ≃ₜ β) (x : α) : map h.symm (𝓝 (h x)) = 𝓝 x :=
by rw [h.symm.map_nhds_eq, h.symm_apply_apply]
lemma nhds_eq_comap (h : α ≃ₜ β) (x : α) : 𝓝 x = comap h (𝓝 (h x)) :=
h.embedding.to_inducing.nhds_eq_comap x
@[simp] lemma comap_nhds_eq (h : α ≃ₜ β) (y : β) : comap h (𝓝 y) = 𝓝 (h.symm y) :=
by rw [h.nhds_eq_comap, h.apply_symm_apply]
/-- If an bijective map `e : α ≃ β` is continuous and open, then it is a homeomorphism. -/
def homeomorph_of_continuous_open (e : α ≃ β) (h₁ : continuous e) (h₂ : is_open_map e) :
α ≃ₜ β :=
{ continuous_to_fun := h₁,
continuous_inv_fun := begin
rw continuous_def,
intros s hs,
convert ← h₂ s hs using 1,
apply e.image_eq_preimage
end,
to_equiv := e }
@[simp] lemma comp_continuous_on_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) :
continuous_on (h ∘ f) s ↔ continuous_on f s :=
h.inducing.continuous_on_iff.symm
@[simp] lemma comp_continuous_iff (h : α ≃ₜ β) {f : γ → α} :
continuous (h ∘ f) ↔ continuous f :=
h.inducing.continuous_iff.symm
@[simp] lemma comp_continuous_iff' (h : α ≃ₜ β) {f : β → γ} :
continuous (f ∘ h) ↔ continuous f :=
h.quotient_map.continuous_iff.symm
lemma comp_continuous_at_iff (h : α ≃ₜ β) (f : γ → α) (x : γ) :
continuous_at (h ∘ f) x ↔ continuous_at f x :=
h.inducing.continuous_at_iff.symm
lemma comp_continuous_at_iff' (h : α ≃ₜ β) (f : β → γ) (x : α) :
continuous_at (f ∘ h) x ↔ continuous_at f (h x) :=
h.inducing.continuous_at_iff' (by simp)
lemma comp_continuous_within_at_iff (h : α ≃ₜ β) (f : γ → α) (s : set γ) (x : γ) :
continuous_within_at f s x ↔ continuous_within_at (h ∘ f) s x :=
h.inducing.continuous_within_at_iff
@[simp] lemma comp_is_open_map_iff (h : α ≃ₜ β) {f : γ → α} :
is_open_map (h ∘ f) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, h.is_open_map.comp hf⟩,
intros hf,
rw [← function.comp.left_id f, ← h.symm_comp_self, function.comp.assoc],
exact h.symm.is_open_map.comp hf,
end
@[simp] lemma comp_is_open_map_iff' (h : α ≃ₜ β) {f : β → γ} :
is_open_map (f ∘ h) ↔ is_open_map f :=
begin
refine ⟨_, λ hf, hf.comp h.is_open_map⟩,
intros hf,
rw [← function.comp.right_id f, ← h.self_comp_symm, ← function.comp.assoc],
exact hf.comp h.symm.is_open_map,
end
/-- If two sets are equal, then they are homeomorphic. -/
def set_congr {s t : set α} (h : s = t) : s ≃ₜ t :=
{ continuous_to_fun := continuous_subtype_mk _ continuous_subtype_val,
continuous_inv_fun := continuous_subtype_mk _ continuous_subtype_val,
to_equiv := equiv.set_congr h }
/-- Sum of two homeomorphisms. -/
def sum_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α ⊕ γ ≃ₜ β ⊕ δ :=
{ continuous_to_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.continuous)
(continuous_inr.comp h₂.continuous),
ext x, cases x; refl,
end,
continuous_inv_fun :=
begin
convert continuous_sum_rec (continuous_inl.comp h₁.symm.continuous)
(continuous_inr.comp h₂.symm.continuous),
ext x, cases x; refl
end,
to_equiv := h₁.to_equiv.sum_congr h₂.to_equiv }
/-- Product of two homeomorphisms. -/
def prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) : α × γ ≃ₜ β × δ :=
{ continuous_to_fun := (h₁.continuous.comp continuous_fst).prod_mk
(h₂.continuous.comp continuous_snd),
continuous_inv_fun := (h₁.symm.continuous.comp continuous_fst).prod_mk
(h₂.symm.continuous.comp continuous_snd),
to_equiv := h₁.to_equiv.prod_congr h₂.to_equiv }
@[simp] lemma prod_congr_symm (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
(h₁.prod_congr h₂).symm = h₁.symm.prod_congr h₂.symm := rfl
@[simp] lemma coe_prod_congr (h₁ : α ≃ₜ β) (h₂ : γ ≃ₜ δ) :
⇑(h₁.prod_congr h₂) = prod.map h₁ h₂ := rfl
section
variables (α β γ)
/-- `α × β` is homeomorphic to `β × α`. -/
def prod_comm : α × β ≃ₜ β × α :=
{ continuous_to_fun := continuous_snd.prod_mk continuous_fst,
continuous_inv_fun := continuous_snd.prod_mk continuous_fst,
to_equiv := equiv.prod_comm α β }
@[simp] lemma prod_comm_symm : (prod_comm α β).symm = prod_comm β α := rfl
@[simp] lemma coe_prod_comm : ⇑(prod_comm α β) = prod.swap := rfl
/-- `(α × β) × γ` is homeomorphic to `α × (β × γ)`. -/
def prod_assoc : (α × β) × γ ≃ₜ α × (β × γ) :=
{ continuous_to_fun := (continuous_fst.comp continuous_fst).prod_mk
((continuous_snd.comp continuous_fst).prod_mk continuous_snd),
continuous_inv_fun := (continuous_fst.prod_mk (continuous_fst.comp continuous_snd)).prod_mk
(continuous_snd.comp continuous_snd),
to_equiv := equiv.prod_assoc α β γ }
/-- `α × {*}` is homeomorphic to `α`. -/
@[simps apply {fully_applied := ff}]
def prod_punit : α × punit ≃ₜ α :=
{ to_equiv := equiv.prod_punit α,
continuous_to_fun := continuous_fst,
continuous_inv_fun := continuous_id.prod_mk continuous_const }
/-- `{*} × α` is homeomorphic to `α`. -/
def punit_prod : punit × α ≃ₜ α :=
(prod_comm _ _).trans (prod_punit _)
@[simp] lemma coe_punit_prod : ⇑(punit_prod α) = prod.snd := rfl
end
/-- `ulift α` is homeomorphic to `α`. -/
def {u v} ulift {α : Type u} [topological_space α] : ulift.{v u} α ≃ₜ α :=
{ continuous_to_fun := continuous_ulift_down,
continuous_inv_fun := continuous_ulift_up,
to_equiv := equiv.ulift }
section distrib
/-- `(α ⊕ β) × γ` is homeomorphic to `α × γ ⊕ β × γ`. -/
def sum_prod_distrib : (α ⊕ β) × γ ≃ₜ α × γ ⊕ β × γ :=
begin
refine (homeomorph.homeomorph_of_continuous_open (equiv.sum_prod_distrib α β γ).symm _ _).symm,
{ convert continuous_sum_rec
((continuous_inl.comp continuous_fst).prod_mk continuous_snd)
((continuous_inr.comp continuous_fst).prod_mk continuous_snd),
ext1 x, cases x; refl, },
{ exact (is_open_map_sum
(open_embedding_inl.prod open_embedding_id).is_open_map
(open_embedding_inr.prod open_embedding_id).is_open_map) }
end
/-- `α × (β ⊕ γ)` is homeomorphic to `α × β ⊕ α × γ`. -/
def prod_sum_distrib : α × (β ⊕ γ) ≃ₜ α × β ⊕ α × γ :=
(prod_comm _ _).trans $
sum_prod_distrib.trans $
sum_congr (prod_comm _ _) (prod_comm _ _)
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
/-- `(Σ i, σ i) × β` is homeomorphic to `Σ i, (σ i × β)`. -/
def sigma_prod_distrib : ((Σ i, σ i) × β) ≃ₜ (Σ i, (σ i × β)) :=
homeomorph.symm $
homeomorph_of_continuous_open (equiv.sigma_prod_distrib σ β).symm
(continuous_sigma $ λ i,
(continuous_sigma_mk.comp continuous_fst).prod_mk continuous_snd)
(is_open_map_sigma $ λ i,
(open_embedding_sigma_mk.prod open_embedding_id).is_open_map)
end distrib
/-- If `ι` has a unique element, then `ι → α` is homeomorphic to `α`. -/
@[simps { fully_applied := ff }]
def fun_unique (ι α : Type*) [unique ι] [topological_space α] : (ι → α) ≃ₜ α :=
{ to_equiv := equiv.fun_unique ι α,
continuous_to_fun := continuous_apply _,
continuous_inv_fun := continuous_pi (λ _, continuous_id) }
/-- Homeomorphism between dependent functions `Π i : fin 2, α i` and `α 0 × α 1`. -/
@[simps { fully_applied := ff }]
def {u} pi_fin_two (α : fin 2 → Type u) [Π i, topological_space (α i)] : (Π i, α i) ≃ₜ α 0 × α 1 :=
{ to_equiv := pi_fin_two_equiv α,
continuous_to_fun := (continuous_apply 0).prod_mk (continuous_apply 1),
continuous_inv_fun := continuous_pi $ fin.forall_fin_two.2 ⟨continuous_fst, continuous_snd⟩ }
/-- Homeomorphism between `α² = fin 2 → α` and `α × α`. -/
@[simps { fully_applied := ff }] def fin_two_arrow : (fin 2 → α) ≃ₜ α × α :=
{ to_equiv := fin_two_arrow_equiv α, .. pi_fin_two (λ _, α) }
/--
A subset of a topological space is homeomorphic to its image under a homeomorphism.
-/
def image (e : α ≃ₜ β) (s : set α) : s ≃ₜ e '' s :=
{ continuous_to_fun := by continuity!,
continuous_inv_fun := by continuity!,
..e.to_equiv.image s, }
end homeomorph
/-- An inducing equiv between topological spaces is a homeomorphism. -/
@[simps] def equiv.to_homeomorph_of_inducing [topological_space α] [topological_space β] (f : α ≃ β)
(hf : inducing f) :
α ≃ₜ β :=
{ continuous_to_fun := hf.continuous,
continuous_inv_fun := hf.continuous_iff.2 $ by simpa using continuous_id,
.. f }
namespace continuous
variables [topological_space α] [topological_space β]
lemma continuous_symm_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : continuous f.symm :=
begin
rw continuous_iff_is_closed,
intros C hC,
have hC' : is_closed (f '' C) := (hC.is_compact.image hf).is_closed,
rwa equiv.image_eq_preimage at hC',
end
/-- Continuous equivalences from a compact space to a T2 space are homeomorphisms.
This is not true when T2 is weakened to T1
(see `continuous.homeo_of_equiv_compact_to_t2.t1_counterexample`). -/
@[simps]
def homeo_of_equiv_compact_to_t2 [compact_space α] [t2_space β]
{f : α ≃ β} (hf : continuous f) : α ≃ₜ β :=
{ continuous_to_fun := hf,
continuous_inv_fun := hf.continuous_symm_of_equiv_compact_to_t2,
..f }
end continuous
|
8ed80d0a903c03714fb3281b6c894b672d9f92fc | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/seclvl.lean | d0e6df26f690e90c3d3206aae6723e178d43671f | [
"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 | 312 | lean | section
variables (A B C : Type)
definition foo := A → B
#check foo A B
#check foo B C
#check foo A A
end
constants A B C : Type
#check foo A B
#check foo B C
#check foo A A
section
variables (A B C : Type)
definition foo2 := A → B
#check foo2 A B
#check foo2 B C
#check foo2 A A
end
|
66a48e808fffbe3e99ea742780db6d66b32a727b | 367134ba5a65885e863bdc4507601606690974c1 | /src/ring_theory/principal_ideal_domain.lean | e3442407cb171041c0bb45625b3d522fd993bdce | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 9,013 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Chris Hughes, Morenikeji Neri
-/
import ring_theory.noetherian
import ring_theory.unique_factorization_domain
/-!
# Principal ideal rings and principal ideal domains
A principal ideal ring (PIR) is a commutative ring in which all ideals are principal. A
principal ideal domain (PID) is an integral domain which is a principal ideal ring.
# Main definitions
Note that for principal ideal domains, one should use
`[integral domain R] [is_principal_ideal_ring R]`. There is no explicit definition of a PID.
Theorems about PID's are in the `principal_ideal_ring` namespace.
- `is_principal_ideal_ring`: a predicate on commutative rings, saying that every
ideal is principal.
- `generator`: a generator of a principal ideal (or more generally submodule)
- `to_unique_factorization_monoid`: a PID is a unique factorization domain
# Main results
- `to_maximal_ideal`: a non-zero prime ideal in a PID is maximal.
- `euclidean_domain.to_principal_ideal_domain` : a Euclidean domain is a PID.
-/
universes u v
variables {R : Type u} {M : Type v}
open set function
open submodule
open_locale classical
/-- An `R`-submodule of `M` is principal if it is generated by one element. -/
class submodule.is_principal [ring R] [add_comm_group M] [module R M] (S : submodule R M) : Prop :=
(principal [] : ∃ a, S = span R {a})
/-- A commutative ring is a principal ideal ring if all ideals are principal. -/
class is_principal_ideal_ring (R : Type u) [comm_ring R] : Prop :=
(principal : ∀ (S : ideal R), S.is_principal)
attribute [instance] is_principal_ideal_ring.principal
namespace submodule.is_principal
variables [comm_ring R] [add_comm_group M] [module R M]
/-- `generator I`, if `I` is a principal submodule, is an `x ∈ M` such that `span R {x} = I` -/
noncomputable def generator (S : submodule R M) [S.is_principal] : M :=
classical.some (principal S)
lemma span_singleton_generator (S : submodule R M) [S.is_principal] : span R {generator S} = S :=
eq.symm (classical.some_spec (principal S))
@[simp] lemma generator_mem (S : submodule R M) [S.is_principal] : generator S ∈ S :=
by { conv_rhs { rw ← span_singleton_generator S }, exact subset_span (mem_singleton _) }
lemma mem_iff_eq_smul_generator (S : submodule R M) [S.is_principal] {x : M} :
x ∈ S ↔ ∃ s : R, x = s • generator S :=
by simp_rw [@eq_comm _ x, ← mem_span_singleton, span_singleton_generator]
lemma mem_iff_generator_dvd (S : ideal R) [S.is_principal] {x : R} : x ∈ S ↔ generator S ∣ x :=
(mem_iff_eq_smul_generator S).trans (exists_congr (λ a, by simp only [mul_comm, smul_eq_mul]))
lemma eq_bot_iff_generator_eq_zero (S : submodule R M) [S.is_principal] :
S = ⊥ ↔ generator S = 0 :=
by rw [← @span_singleton_eq_bot R M, span_singleton_generator]
end submodule.is_principal
namespace is_prime
open submodule.is_principal ideal
-- TODO -- for a non-ID one could perhaps prove that if p < q are prime then q maximal;
-- 0 isn't prime in a non-ID PIR but the Krull dimension is still <= 1.
-- The below result follows from this, but we could also use the below result to
-- prove this (quotient out by p).
lemma to_maximal_ideal [integral_domain R] [is_principal_ideal_ring R] {S : ideal R}
[hpi : is_prime S] (hS : S ≠ ⊥) : is_maximal S :=
is_maximal_iff.2 ⟨(ne_top_iff_one S).1 hpi.1, begin
assume T x hST hxS hxT,
cases (mem_iff_generator_dvd _).1 (hST $ generator_mem S) with z hz,
cases hpi.mem_or_mem (show generator T * z ∈ S, from hz ▸ generator_mem S),
{ have hTS : T ≤ S, rwa [← span_singleton_generator T, submodule.span_le, singleton_subset_iff],
exact (hxS $ hTS hxT).elim },
cases (mem_iff_generator_dvd _).1 h with y hy,
have : generator S ≠ 0 := mt (eq_bot_iff_generator_eq_zero _).2 hS,
rw [← mul_one (generator S), hy, mul_left_comm, mul_right_inj' this] at hz,
exact hz.symm ▸ T.mul_mem_right _ (generator_mem T)
end⟩
end is_prime
section
open euclidean_domain
variable [euclidean_domain R]
lemma mod_mem_iff {S : ideal R} {x y : R} (hy : y ∈ S) : x % y ∈ S ↔ x ∈ S :=
⟨λ hxy, div_add_mod x y ▸ S.add_mem (S.mul_mem_right _ hy) hxy,
λ hx, (mod_eq_sub_mul_div x y).symm ▸ S.sub_mem hx (S.mul_mem_right _ hy)⟩
@[priority 100] -- see Note [lower instance priority]
instance euclidean_domain.to_principal_ideal_domain : is_principal_ideal_ring R :=
{ principal := λ S, by exactI
⟨if h : {x : R | x ∈ S ∧ x ≠ 0}.nonempty
then
have wf : well_founded (euclidean_domain.r : R → R → Prop) := euclidean_domain.r_well_founded,
have hmin : well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ∈ S ∧
well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h ≠ 0,
from well_founded.min_mem wf {x : R | x ∈ S ∧ x ≠ 0} h,
⟨well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h,
submodule.ext $ λ x,
⟨λ hx, div_add_mod x (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ▸
(ideal.mem_span_singleton.2 $ dvd_add (dvd_mul_right _ _) $
have (x % (well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h) ∉ {x : R | x ∈ S ∧ x ≠ 0}),
from λ h₁, well_founded.not_lt_min wf _ h h₁ (mod_lt x hmin.2),
have x % well_founded.min wf {x : R | x ∈ S ∧ x ≠ 0} h = 0,
by finish [(mod_mem_iff hmin.1).2 hx],
by simp *),
λ hx, let ⟨y, hy⟩ := ideal.mem_span_singleton.1 hx in hy.symm ▸ S.mul_mem_right _ hmin.1⟩⟩
else ⟨0, submodule.ext $ λ a,
by rw [← @submodule.bot_coe R R _ _ _, span_eq, submodule.mem_bot];
exact ⟨λ haS, by_contradiction $ λ ha0, h ⟨a, ⟨haS, ha0⟩⟩, λ h₁, h₁.symm ▸ S.zero_mem⟩⟩⟩ }
end
namespace principal_ideal_ring
open is_principal_ideal_ring
variables [integral_domain R] [is_principal_ideal_ring R]
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring : is_noetherian_ring R :=
is_noetherian_ring_iff.2 ⟨assume s : ideal R,
begin
rcases (is_principal_ideal_ring.principal s).principal with ⟨a, rfl⟩,
rw [← finset.coe_singleton],
exact ⟨{a}, submodule.coe_injective rfl⟩
end⟩
lemma is_maximal_of_irreducible {p : R} (hp : irreducible p) :
ideal.is_maximal (span R ({p} : set R)) :=
⟨⟨mt ideal.span_singleton_eq_top.1 hp.1, λ I hI, begin
rcases principal I with ⟨a, rfl⟩,
erw ideal.span_singleton_eq_top,
unfreezingI { rcases ideal.span_singleton_le_span_singleton.1 (le_of_lt hI) with ⟨b, rfl⟩ },
refine (of_irreducible_mul hp).resolve_right (mt (λ hb, _) (not_le_of_lt hI)),
erw [ideal.span_singleton_le_span_singleton, is_unit.mul_right_dvd hb]
end⟩⟩
lemma irreducible_iff_prime {p : R} : irreducible p ↔ prime p :=
⟨λ hp, (ideal.span_singleton_prime hp.ne_zero).1 $
(is_maximal_of_irreducible hp).is_prime,
irreducible_of_prime⟩
lemma associates_irreducible_iff_prime : ∀{p : associates R}, irreducible p ↔ prime p :=
associates.irreducible_iff_prime_iff.1 (λ _, irreducible_iff_prime)
section
open_locale classical
/-- `factors a` is a multiset of irreducible elements whose product is `a`, up to units -/
noncomputable def factors (a : R) : multiset R :=
if h : a = 0 then ∅ else classical.some (wf_dvd_monoid.exists_factors a h)
lemma factors_spec (a : R) (h : a ≠ 0) :
(∀b∈factors a, irreducible b) ∧ associated (factors a).prod a :=
begin
unfold factors, rw [dif_neg h],
exact classical.some_spec (wf_dvd_monoid.exists_factors a h)
end
lemma ne_zero_of_mem_factors {R : Type v} [integral_domain R] [is_principal_ideal_ring R] {a b : R}
(ha : a ≠ 0) (hb : b ∈ factors a) : b ≠ 0 := irreducible.ne_zero ((factors_spec a ha).1 b hb)
lemma mem_submonoid_of_factors_subset_of_units_subset (s : submonoid R)
{a : R} (ha : a ≠ 0) (hfac : ∀ b ∈ factors a, b ∈ s) (hunit : ∀ c : units R, (c : R) ∈ s) :
a ∈ s :=
begin
rcases ((factors_spec a ha).2) with ⟨c, hc⟩,
rw [← hc],
exact submonoid.mul_mem _ (submonoid.multiset_prod_mem _ _ hfac) (hunit _),
end
/-- If a `ring_hom` maps all units and all factors of an element `a` into a submonoid `s`, then it
also maps `a` into that submonoid. -/
lemma ring_hom_mem_submonoid_of_factors_subset_of_units_subset {R S : Type*}
[integral_domain R] [is_principal_ideal_ring R] [semiring S]
(f : R →+* S) (s : submonoid S) (a : R) (ha : a ≠ 0)
(h : ∀ b ∈ factors a, f b ∈ s) (hf: ∀ c : units R, f c ∈ s) :
f a ∈ s :=
mem_submonoid_of_factors_subset_of_units_subset (s.comap f.to_monoid_hom) ha h hf
/-- A principal ideal domain has unique factorization -/
@[priority 100] -- see Note [lower instance priority]
instance to_unique_factorization_monoid : unique_factorization_monoid R :=
{ irreducible_iff_prime := λ _, principal_ideal_ring.irreducible_iff_prime
.. (is_noetherian_ring.wf_dvd_monoid : wf_dvd_monoid R) }
end
end principal_ideal_ring
|
5c37ff38b5c3f0a3fcead4a0bdb63f10a4d9f83a | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/eq18.lean | c0b963742a8f3e24ffd890c9988542175a40efc2 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 342 | lean | import data.examples.vector
open nat vector
definition last {A : Type} : Π {n}, vector A (succ n) → A
| last (a :: nil) := a
| last (a :: v) := last v
theorem last_cons_nil {A : Type} {n : nat} (a : A) : last (a :: nil) = a :=
rfl
theorem last_cons {A : Type} {n : nat} (a : A) (v : vector A (succ n)) : last (a :: v) = last v :=
rfl
|
139f3bf8e0cff196a3726a8e2f392ae30f320f8e | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/delta_instance.lean | 32a1bb7538793185f1e3595d50140814d859abe1 | [
"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 | 961 | lean | /-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import data.set.basic
import algebra.category.Mon.basic
def X : Type := set ℕ
instance : has_coe_to_sort X Type := set.has_coe_to_sort
@[derive ring] def T := ℤ
class binclass (T1 T2 : Type)
instance : binclass ℤ ℤ := ⟨⟩
@[derive [ring, binclass ℤ]] def U := ℤ
@[derive λ α, binclass α ℤ] def V := ℤ
-- test instance naming
example := U.ring
example := U.binclass
example := V.binclass
@[derive ring] def id_ring (α) [ring α] : Type := α
@[derive decidable_eq] def S := ℕ
@[derive decidable_eq] inductive P | a | b | c
open category_theory
-- Test that `delta_instance` works in the presence of universe metavariables.
attribute [derive large_category] Mon
-- test deriving instances on function types
@[derive monad]
meta def my_tactic : Type → Type :=
tactic
|
a9152cddec8aa90632e615c049a7619fd07fc996 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/def1.lean | 83156af66cc793500a6aba8fe2b269553a3d8a39 | [
"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 | 160 | lean | universe variable u
variable {A : Type u}
lemma foo (f : A → A → A) (a b c : A) (H₁ : a = b) (H₂ : c = b) : f a = f c :=
H₂ ▸ eq.symm H₁ ▸ rfl
|
c49dcf2c05bf579d038f3e1d0c44ad7339757656 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/lift.lean | 11f363f242388dc26bd5982b697529330f5a0989 | [
"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 | 8,858 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.rcases
/-!
# lift tactic
This file defines the lift tactic, allowing the user to lift elements from one type to another
under a specified condition.
## Tags
lift, tactic
-/
universe variables u v w
/-- A class specifying that you can lift elements from `α` to `β` assuming `cond` is true.
Used by the tactic `lift`. -/
class can_lift (α : Type u) (β : Type v) : Type (max u v) :=
(coe : β → α)
(cond : α → Prop)
(prf : ∀(x : α), cond x → ∃(y : β), coe y = x)
open tactic
@[user_attribute]
meta def can_lift_attr : user_attribute (list name) :=
{ name := "_can_lift",
descr := "internal attribute used by the lift tactic",
cache_cfg := { mk_cache := λ _,
do { ls ← attribute.get_instances `instance,
ls.mfilter $ λ l,
do { (_,t) ← mk_const l >>= infer_type >>= mk_local_pis,
return $ t.is_app_of `can_lift } },
dependencies := [`instance] } }
instance : can_lift ℤ ℕ :=
⟨coe, λ n, 0 ≤ n, λ n hn, ⟨n.nat_abs, int.nat_abs_of_nonneg hn⟩⟩
/-- Enable automatic handling of pi types in `can_lift`. -/
instance pi.can_lift (ι : Type u) (α : Π i : ι, Type v) (β : Π i : ι, Type w)
[Π i : ι, can_lift (α i) (β i)] :
can_lift (Π i : ι, α i) (Π i : ι, β i) :=
{ coe := λ f i, can_lift.coe (f i),
cond := λ f, ∀ i, can_lift.cond (β i) (f i),
prf := λ f hf, ⟨λ i, classical.some (can_lift.prf (f i) (hf i)), funext $ λ i,
classical.some_spec (can_lift.prf (f i) (hf i))⟩ }
namespace tactic
/- Construct the proof of `cond x` in the lift tactic.
`e` is the expression being lifted and `h` is the specified proof of `can_lift.cond e`.
`old_tp` and `new_tp` are the arguments to `can_lift` and `inst` is the `can_lift`-instance.
`s` and `to_unfold` contain the information of the simp set used to simplify.
If the proof was specified, we check whether it has the correct type.
If it doesn't have the correct type, we display an error message
(but first call dsimp on the expression in the message).
If the proof was not specified, we create assert it as a local constant.
(The name of this local constant doesn't matter, since `lift` will remove it from the context) -/
meta def get_lift_prf (h : option pexpr) (old_tp new_tp inst e : expr)
(s : simp_lemmas) (to_unfold : list name) : tactic expr :=
if h_some : h.is_some then
(do prf ← i_to_expr (option.get h_some), prf_ty ← infer_type prf,
expected_prf_ty ← mk_app `can_lift.cond [old_tp, new_tp, inst, e],
unify prf_ty expected_prf_ty <|>
(do expected_prf_ty2 ← s.dsimplify to_unfold expected_prf_ty,
pformat!"lift tactic failed. The type of\n {prf}\nis\n {prf_ty}\nbut it is expected to be\n {expected_prf_ty2}" >>= fail),
return prf)
else (do prf_nm ← get_unused_name,
prf ← mk_app `can_lift.cond [old_tp, new_tp, inst, e] >>= assert prf_nm,
dsimp_target s to_unfold {}, swap, return prf)
/-- Lift the expression `p` to the type `t`, with proof obligation given by `h`.
The list `n` is used for the two newly generated names, and to specify whether `h` should
remain in the local context. See the doc string of `tactic.interactive.lift` for more information.
-/
meta def lift (p : pexpr) (t : pexpr) (h : option pexpr) (n : list name) : tactic unit :=
do
propositional_goal <|>
fail "lift tactic failed. Tactic is only applicable when the target is a proposition.",
e ← i_to_expr p,
old_tp ← infer_type e,
new_tp ← i_to_expr t,
inst_type ← mk_app ``can_lift [old_tp, new_tp],
inst ← mk_instance inst_type <|>
pformat!"Failed to find a lift from {old_tp} to {new_tp}. Provide an instance of\n {inst_type}"
>>= fail,
/- make the simp set to get rid of `can_lift` projections -/
can_lift_instances ← can_lift_attr.get_cache >>= λ l, l.mmap resolve_name,
(s, to_unfold) ← mk_simp_set tt [] $ can_lift_instances.map simp_arg_type.expr,
prf_cond ← get_lift_prf h old_tp new_tp inst e s to_unfold,
let prf_nm := if prf_cond.is_local_constant then some prf_cond.local_pp_name else none,
/- We use mk_mapp to apply `can_lift.prf` to all but one argument, and then just use expr.app
for the last argument. For some reason we get an error when applying mk_mapp it to all
arguments. -/
prf_ex0 ← mk_mapp `can_lift.prf [old_tp, new_tp, inst, e],
let prf_ex := prf_ex0 prf_cond,
/- Find the name of the new variable -/
new_nm ← if n ≠ [] then return n.head
else if e.is_local_constant then return e.local_pp_name
else get_unused_name,
/- Find the name of the proof of the equation -/
eq_nm ← if hn : 1 < n.length then return (n.nth_le 1 hn)
else if e.is_local_constant then return `rfl
else get_unused_name `h,
/- We add the proof of the existential statement to the context and then apply
`dsimp` to it, unfolding all `can_lift` instances. -/
temp_nm ← get_unused_name,
temp_e ← note temp_nm none prf_ex,
dsimp_hyp temp_e s to_unfold {},
/- We case on the existential. We use `rcases` because `eq_nm` could be `rfl`. -/
rcases none (pexpr.of_expr temp_e) [[rcases_patt.one new_nm, rcases_patt.one eq_nm]],
/- If the lifted variable is not a local constant, try to rewrite it away using the new equality-/
when (¬ e.is_local_constant) (get_local eq_nm >>=
λ e, interactive.rw ⟨[⟨⟨0, 0⟩, tt, (pexpr.of_expr e)⟩], none⟩ interactive.loc.wildcard),
/- If the proof `prf_cond` is a local constant, remove it from the context,
unless `n` specifies to keep it. -/
if h_prf_nm : prf_nm.is_some ∧ n.nth 2 ≠ prf_nm then
get_local (option.get h_prf_nm.1) >>= clear else skip
open lean.parser interactive interactive.types
local postfix `?`:9001 := optional
meta def using_texpr := (tk "using" *> texpr)?
reserve notation `to`
meta def to_texpr := (tk "to" *> texpr)
namespace interactive
/-- Lift an expression to another type.
Lift an expression to another type.
* Usage: `'lift' expr 'to' expr ('using' expr)? ('with' id (id id?)?)?`.
* If `n : ℤ` and `hn : n ≥ 0` then the tactic `lift n to ℕ using hn` creates a new
constant of type `ℕ`, also named `n` and replaces all occurrences of the old variable `(n : ℤ)`
with `↑n` (where `n` in the new variable). It will remove `n` and `hn` from the context.
+ So for example the tactic `lift n to ℕ using hn` transforms the goal
`n : ℤ, hn : n ≥ 0, h : P n ⊢ n = 3` to `n : ℕ, h : P ↑n ⊢ ↑n = 3`
(here `P` is some term of type `ℤ → Prop`).
* The argument `using hn` is optional, the tactic `lift n to ℕ` does the same, but also creates a
new subgoal that `n ≥ 0` (where `n` is the old variable).
+ So for example the tactic `lift n to ℕ` transforms the goal
`n : ℤ, h : P n ⊢ n = 3` to two goals
`n : ℕ, h : P ↑n ⊢ ↑n = 3` and `n : ℤ, h : P n ⊢ n ≥ 0`.
* You can also use `lift n to ℕ using e` where `e` is any expression of type `n ≥ 0`.
* Use `lift n to ℕ with k` to specify the name of the new variable.
* Use `lift n to ℕ with k hk` to also specify the name of the equality `↑k = n`. In this case, `n`
will remain in the context. You can use `rfl` for the name of `hk` to substitute `n` away
(i.e. the default behavior).
* You can also use `lift e to ℕ with k hk` where `e` is any expression of type `ℤ`.
In this case, the `hk` will always stay in the context, but it will be used to rewrite `e` in
all hypotheses and the target.
+ So for example the tactic `lift n + 3 to ℕ using hn with k hk` transforms the goal
`n : ℤ, hn : n + 3 ≥ 0, h : P (n + 3) ⊢ n + 3 = 2 * n` to the goal
`n : ℤ, k : ℕ, hk : ↑k = n + 3, h : P ↑k ⊢ ↑k = 2 * n`.
* The tactic `lift n to ℕ using h` will remove `h` from the context. If you want to keep it,
specify it again as the third argument to `with`, like this: `lift n to ℕ using h with n rfl h`.
* More generally, this can lift an expression from `α` to `β` assuming that there is an instance
of `can_lift α β`. In this case the proof obligation is specified by `can_lift.cond`.
* Given an instance `can_lift β γ`, it can also lift `α → β` to `α → γ`; more generally, given
`β : Π a : α, Type*`, `γ : Π a : α, Type*`, and `[Π a : α, can_lift (β a) (γ a)]`, it automatically
generates an instance `can_lift (Π a, β a) (Π a, γ a)`.
-/
meta def lift (p : parse texpr) (t : parse to_texpr) (h : parse using_texpr)
(n : parse with_ident_list) : tactic unit :=
tactic.lift p t h n
add_tactic_doc
{ name := "lift",
category := doc_category.tactic,
decl_names := [`tactic.interactive.lift],
tags := ["coercions"] }
end interactive
end tactic
|
ab7f40d12c732b5843a8eeb58e8ecb329dfa7fea | b1e80085f6d9158c0b431ffc4fa9d0d53cbac8e4 | /src/free.lean | 9b2934875eb0b160aa487fd398d15654fbeaae76 | [] | no_license | dwarn/nielsen-schreier-2 | d73c20e4d2a8ae537fe4f8063272d0b72c58276a | e51a8c6511d374dc584698c7fa236a5be47e7dbe | refs/heads/master | 1,679,911,740,113 | 1,615,656,058,000 | 1,615,656,058,000 | 344,111,212 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,503 | lean | import category_theory.single_obj
category_theory.functor
category_theory.elements
category_theory.action
group_theory.free_group
quiver
misc
open category_theory
universes u v
class is_free_group (G) [group.{u} G] :=
(gp_gens : Type u)
(gp_emb : gp_gens → G)
(gp_lift {X} [group.{u} X] (f : gp_gens → X) : ∃! F : G →* X, ∀ a, f a = F (gp_emb a))
class is_free_groupoid (G) [groupoid.{v u} G] :=
(gpd_gens : quiver.{v u} G)
(gpd_emb : Π ⦃a b⦄, gpd_gens a b → (a ⟶ b))
(gpd_lift {X} [group.{v} X] (f : valu gpd_gens X) :
∃! F : G ⥤ single_obj X, ∀ {x y : G} (a : gpd_gens x y), f a = F.map (gpd_emb a))
(ind {P : Π {a b : G}, (a ⟶ b) → Prop}
(base : ∀ a b (e : gpd_gens a b), P (gpd_emb e))
(id : ∀ a, P (𝟙 a))
(comp : ∀ a b c (f : a ⟶ b) (g : b ⟶ c), P f → P g → P (f ≫ g))
(comp : ∀ a b (f : a ⟶ b), P f → P (inv f))
{a b} (f : a ⟶ b) : P f)
open is_free_group is_free_groupoid
-- this restricted extensionality lemma should be enough for our purposes
lemma is_free_group_ext {G} [group G] [is_free_group G] (f : G →* G) :
(∀ a : gp_gens G, f (gp_emb a) = gp_emb a) → ∀ g, f g = g :=
begin
intro hyp,
suffices : f = monoid_hom.id G,
{ intro g, rw this, refl },
let F : gp_gens G → G := f ∘ gp_emb,
rcases gp_lift F with ⟨p, hp, up⟩,
have : f = p,
{ apply up, intros, refl },
have : monoid_hom.id G = p,
{ apply up, intros, apply hyp },
cc,
end
def free_group_is_free_group (A) : is_free_group (free_group A) :=
{ gp_gens := A,
gp_emb := free_group.of,
gp_lift := begin
introsI X _ f,
apply (free_group.lift.exists_unique_congr _).mp ⟨f, rfl, λ _, eq.symm⟩,
intro, simp only [function.funext_iff, free_group.lift.of],
end }
noncomputable def iso_free_group_of_is_free_group {G} [group G] [is_free_group G] :
G ≃* free_group (gp_gens G) :=
let ⟨F, hF, uF⟩ := classical.indefinite_description _ (gp_lift $ @free_group.of (gp_gens G)) in
{ to_fun := F,
inv_fun := free_group.lift gp_emb,
left_inv := by { change ∀ g, ((free_group.lift gp_emb).comp F) g = g,
apply is_free_group_ext, simp [←hF] },
right_inv := begin
suffices : F.comp (free_group.lift gp_emb) = monoid_hom.id _,
{ rwa monoid_hom.ext_iff at this },
apply free_group.ext_hom,
simp [←hF]
end,
map_mul' := F.map_mul }
lemma is_free_group_induction {G} [group G] [is_free_group G]
(P : G → Prop)
(base : ∀ a, P (gp_emb a))
(one : P 1)
(mul : ∀ g h, P g → P h → P (g * h))
(inv : ∀ g, P g → P (g⁻¹))
(g : G) : P g :=
let H : subgroup G := {
carrier := P,
one_mem' := one,
mul_mem' := mul,
inv_mem' := inv } in
let f : gp_gens G → H := λ a, ⟨gp_emb a, base a⟩ in
begin
rcases gp_lift f with ⟨F, hF, _⟩,
have : ∀ g, H.subtype.comp F g = g,
{ apply is_free_group_ext,
intro a,
change (F (gp_emb a)).val = _,
rw ←hF },
convert (F g).property,
symmetry, apply this
end
-- being a free group is an isomorphism invariant
def is_free_group_mul_equiv {G H : Type u} [group G] [group H] [is_free_group G] (h : G ≃* H)
: is_free_group H :=
{ gp_gens := gp_gens G,
gp_emb := λ a, h (gp_emb a),
gp_lift := begin
introsI X _ f,
refine (equiv.exists_unique_congr (homset_equiv_of_mul_equiv h) _).mp (gp_lift f),
intros F, apply forall_congr,
intro, apply eq.congr,
{ refl },
{ change F _ = F _, simp },
end }
|
da7f79ac228af417b6749fae80025f0cc28290ef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Util/CollectMVars.lean | fd71d68baf57c1c4280585aaf702724b9218a579 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,152 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Expr
namespace Lean
namespace CollectMVars
structure State where
visitedExpr : ExprSet := {}
result : Array MVarId := #[]
instance : Inhabited State := ⟨{}⟩
abbrev Visitor := State → State
mutual
partial def visit (e : Expr) : Visitor := fun s =>
if !e.hasMVar || s.visitedExpr.contains e then s
else main e { s with visitedExpr := s.visitedExpr.insert e }
partial def main : Expr → Visitor
| Expr.proj _ _ e => visit e
| Expr.forallE _ d b _ => visit b ∘ visit d
| Expr.lam _ d b _ => visit b ∘ visit d
| Expr.letE _ t v b _ => visit b ∘ visit v ∘ visit t
| Expr.app f a => visit a ∘ visit f
| Expr.mdata _ b => visit b
| Expr.mvar mvarId => fun s => { s with result := s.result.push mvarId }
| _ => id
end
end CollectMVars
def Expr.collectMVars (s : CollectMVars.State) (e : Expr) : CollectMVars.State :=
CollectMVars.visit e s
end Lean
|
63ae96c1d32c33f5e95f3da5b446557e6ca11034 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/topology/continuous_function/bounded.lean | 90d13d7137b47eab75fa38304645479f684436a3 | [
"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 | 35,542 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Mario Carneiro, Yury Kudryashov, Heather Macbeth
-/
import analysis.normed_space.basic
import topology.continuous_function.algebra
/-!
# Bounded continuous functions
The type of bounded continuous functions taking values in a metric space, with
the uniform distance.
-/
noncomputable theory
open_locale topological_space classical nnreal
open set filter metric
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- The type of bounded continuous functions from a topological space to a metric space -/
structure bounded_continuous_function
(α : Type u) (β : Type v) [topological_space α] [metric_space β] extends continuous_map α β :
Type (max u v) :=
(bounded' : ∃C, ∀x y:α, dist (to_fun x) (to_fun y) ≤ C)
localized "infixr ` →ᵇ `:25 := bounded_continuous_function" in bounded_continuous_function
namespace bounded_continuous_function
section basics
variables [topological_space α] [metric_space β] [metric_space γ]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : has_coe_to_fun (α →ᵇ β) := ⟨_, λ f, f.to_fun⟩
protected lemma bounded (f : α →ᵇ β) : ∃C, ∀ x y : α, dist (f x) (f y) ≤ C := f.bounded'
@[continuity]
protected lemma continuous (f : α →ᵇ β) : continuous f := f.to_continuous_map.continuous
@[ext] lemma ext (H : ∀x, f x = g x) : f = g :=
by { cases f, cases g, congr, ext, exact H x, }
lemma ext_iff : f = g ↔ ∀ x, f x = g x :=
⟨λ h, λ x, h ▸ rfl, ext⟩
lemma bounded_range : bounded (range f) :=
bounded_range_iff.2 f.bounded
/-- A continuous function with an explicit bound is a bounded continuous function. -/
def mk_of_bound (f : C(α, β)) (C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨f, ⟨C, h⟩⟩
@[simp] lemma mk_of_bound_coe {f} {C} {h} : (mk_of_bound f C h : α → β) = (f : α → β) :=
rfl
/-- A continuous function on a compact space is automatically a bounded continuous function. -/
def mk_of_compact [compact_space α] (f : C(α, β)) : α →ᵇ β :=
⟨f, bounded_range_iff.1 $ bounded_of_compact $ is_compact_range f.continuous⟩
@[simp] lemma mk_of_compact_apply [compact_space α] (f : C(α, β)) (a : α) :
mk_of_compact f a = f a :=
rfl
/-- If a function is bounded on a discrete space, it is automatically continuous,
and therefore gives rise to an element of the type of bounded continuous functions -/
def mk_of_discrete [discrete_topology α] (f : α → β)
(C : ℝ) (h : ∀ x y : α, dist (f x) (f y) ≤ C) : α →ᵇ β :=
⟨⟨f, continuous_of_discrete_topology⟩, ⟨C, h⟩⟩
@[simp] lemma mk_of_discrete_apply
[discrete_topology α] (f : α → β) (C) (h) (a : α) :
mk_of_discrete f C h a = f a :=
rfl
section
variables (α β)
/--
The map forgetting that a bounded continuous function is bounded.
-/
def forget_boundedness : (α →ᵇ β) → C(α, β) :=
λ f, f.1
@[simp] lemma forget_boundedness_coe (f : α →ᵇ β) : (forget_boundedness α β f : α → β) = f :=
rfl
end
/-- The uniform distance between two bounded continuous functions -/
instance : has_dist (α →ᵇ β) :=
⟨λf g, Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C}⟩
lemma dist_eq : dist f g = Inf {C | 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C} := rfl
lemma dist_set_exists : ∃ C, 0 ≤ C ∧ ∀ x : α, dist (f x) (g x) ≤ C :=
begin
refine if h : nonempty α then _ else ⟨0, le_refl _, λ x, h.elim ⟨x⟩⟩,
cases h with x,
rcases f.bounded with ⟨Cf, hCf : ∀ x y, dist (f x) (f y) ≤ Cf⟩,
rcases g.bounded with ⟨Cg, hCg : ∀ x y, dist (g x) (g y) ≤ Cg⟩,
let C := max 0 (dist (f x) (g x) + (Cf + Cg)),
refine ⟨C, le_max_left _ _, λ y, _⟩,
calc dist (f y) (g y) ≤ dist (f x) (g x) + (dist (f x) (f y) + dist (g x) (g y)) :
dist_triangle4_left _ _ _ _
... ≤ dist (f x) (g x) + (Cf + Cg) : by mono*
... ≤ C : le_max_right _ _
end
/-- The pointwise distance is controlled by the distance between functions, by definition. -/
lemma dist_coe_le_dist (x : α) : dist (f x) (g x) ≤ dist f g :=
le_cInf dist_set_exists $ λb hb, hb.2 x
/- This lemma will be needed in the proof of the metric space instance, but it will become
useless afterwards as it will be superseded by the general result that the distance is nonnegative
in metric spaces. -/
private lemma dist_nonneg' : 0 ≤ dist f g :=
le_cInf dist_set_exists (λ C, and.left)
/-- The distance between two functions is controlled by the supremum of the pointwise distances -/
lemma dist_le (C0 : (0 : ℝ) ≤ C) : dist f g ≤ C ↔ ∀x:α, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h, λ H, cInf_le ⟨0, λ C, and.left⟩ ⟨C0, H⟩⟩
lemma dist_le_iff_of_nonempty [nonempty α] :
dist f g ≤ C ↔ ∀ x, dist (f x) (g x) ≤ C :=
⟨λ h x, le_trans (dist_coe_le_dist x) h,
λ w, (dist_le (le_trans dist_nonneg (w (nonempty.some ‹_›)))).mpr w⟩
lemma dist_lt_of_nonempty_compact [nonempty α] [compact_space α]
(w : ∀x:α, dist (f x) (g x) < C) : dist f g < C :=
begin
have c : continuous (λ x, dist (f x) (g x)), { continuity, },
obtain ⟨x, -, le⟩ :=
is_compact.exists_forall_ge compact_univ set.univ_nonempty (continuous.continuous_on c),
exact lt_of_le_of_lt (dist_le_iff_of_nonempty.mpr (λ y, le y trivial)) (w x),
end
lemma dist_lt_iff_of_compact [compact_space α] (C0 : (0 : ℝ) < C) :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
begin
fsplit,
{ intros w x,
exact lt_of_le_of_lt (dist_coe_le_dist x) w, },
{ by_cases h : nonempty α,
{ resetI,
exact dist_lt_of_nonempty_compact, },
{ rintro -,
convert C0,
apply le_antisymm _ dist_nonneg',
rw [dist_eq],
exact cInf_le ⟨0, λ C, and.left⟩ ⟨le_refl _, λ x, false.elim (h (nonempty.intro x))⟩, }, },
end
lemma dist_lt_iff_of_nonempty_compact [nonempty α] [compact_space α] :
dist f g < C ↔ ∀x:α, dist (f x) (g x) < C :=
⟨λ w x, lt_of_le_of_lt (dist_coe_le_dist x) w, dist_lt_of_nonempty_compact⟩
/-- On an empty space, bounded continuous functions are at distance 0 -/
lemma dist_zero_of_empty (e : ¬ nonempty α) : dist f g = 0 :=
le_antisymm ((dist_le (le_refl _)).2 $ λ x, e.elim ⟨x⟩) dist_nonneg'
/-- The type of bounded continuous functions, with the uniform distance, is a metric space. -/
instance : metric_space (α →ᵇ β) :=
{ dist_self := λ f, le_antisymm ((dist_le (le_refl _)).2 $ λ x, by simp) dist_nonneg',
eq_of_dist_eq_zero := λ f g hfg, by ext x; exact
eq_of_dist_eq_zero (le_antisymm (hfg ▸ dist_coe_le_dist _) dist_nonneg),
dist_comm := λ f g, by simp [dist_eq, dist_comm],
dist_triangle := λ f g h,
(dist_le (add_nonneg dist_nonneg' dist_nonneg')).2 $ λ x,
le_trans (dist_triangle _ _ _) (add_le_add (dist_coe_le_dist _) (dist_coe_le_dist _)) }
variables (α) {β}
/-- Constant as a continuous bounded function. -/
def const (b : β) : α →ᵇ β := ⟨continuous_map.const b, 0, by simp [le_refl]⟩
variable {α}
@[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl
lemma const_apply (a : α) (b : β) : (const α b : α → β) a = b := rfl
/-- If the target space is inhabited, so is the space of bounded continuous functions -/
instance [inhabited β] : inhabited (α →ᵇ β) := ⟨const α (default β)⟩
/-- The evaluation map is continuous, as a joint function of `u` and `x` -/
@[continuity] theorem continuous_eval : continuous (λ p : (α →ᵇ β) × α, p.1 p.2) :=
continuous_iff'.2 $ λ ⟨f, x⟩ ε ε0,
/- use the continuity of `f` to find a neighborhood of `x` where it varies at most by ε/2 -/
have Hs : _ := continuous_iff'.1 f.continuous x (ε/2) (half_pos ε0),
mem_sets_of_superset (prod_is_open.mem_nhds (ball_mem_nhds _ (half_pos ε0)) Hs) $
λ ⟨g, y⟩ ⟨hg, hy⟩, calc dist (g y) (f x)
≤ dist (g y) (f y) + dist (f y) (f x) : dist_triangle _ _ _
... < ε/2 + ε/2 : add_lt_add (lt_of_le_of_lt (dist_coe_le_dist _) hg) hy
... = ε : add_halves _
/-- In particular, when `x` is fixed, `f → f x` is continuous -/
@[continuity] theorem continuous_evalx {x : α} : continuous (λ f : α →ᵇ β, f x) :=
continuous_eval.comp (continuous_id.prod_mk continuous_const)
/-- Bounded continuous functions taking values in a complete space form a complete space. -/
instance [complete_space β] : complete_space (α →ᵇ β) :=
complete_of_cauchy_seq_tendsto $ λ (f : ℕ → α →ᵇ β) (hf : cauchy_seq f),
begin
/- We have to show that `f n` converges to a bounded continuous function.
For this, we prove pointwise convergence to define the limit, then check
it is a continuous bounded function, and then check the norm convergence. -/
rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, b0, b_bound, b_lim⟩,
have f_bdd := λx n m N hn hm, le_trans (dist_coe_le_dist x) (b_bound n m N hn hm),
have fx_cau : ∀x, cauchy_seq (λn, f n x) :=
λx, cauchy_seq_iff_le_tendsto_0.2 ⟨b, b0, f_bdd x, b_lim⟩,
choose F hF using λx, cauchy_seq_tendsto_of_complete (fx_cau x),
/- F : α → β, hF : ∀ (x : α), tendsto (λ (n : ℕ), f n x) at_top (𝓝 (F x))
`F` is the desired limit function. Check that it is uniformly approximated by `f N` -/
have fF_bdd : ∀x N, dist (f N x) (F x) ≤ b N :=
λ x N, le_of_tendsto (tendsto_const_nhds.dist (hF x))
(filter.eventually_at_top.2 ⟨N, λn hn, f_bdd x N n N (le_refl N) hn⟩),
refine ⟨⟨⟨F, _⟩, _⟩, _⟩,
{ /- Check that `F` is continuous, as a uniform limit of continuous functions -/
have : tendsto_uniformly (λn x, f n x) F at_top,
{ refine metric.tendsto_uniformly_iff.2 (λ ε ε0, _),
refine ((tendsto_order.1 b_lim).2 ε ε0).mono (λ n hn x, _),
rw dist_comm,
exact lt_of_le_of_lt (fF_bdd x n) hn },
exact this.continuous (λN, (f N).continuous) },
{ /- Check that `F` is bounded -/
rcases (f 0).bounded with ⟨C, hC⟩,
refine ⟨C + (b 0 + b 0), λ x y, _⟩,
calc dist (F x) (F y) ≤ dist (f 0 x) (f 0 y) + (dist (f 0 x) (F x) + dist (f 0 y) (F y)) :
dist_triangle4_left _ _ _ _
... ≤ C + (b 0 + b 0) : by mono* },
{ /- Check that `F` is close to `f N` in distance terms -/
refine tendsto_iff_dist_tendsto_zero.2 (squeeze_zero (λ _, dist_nonneg) _ b_lim),
exact λ N, (dist_le (b0 _)).2 (λx, fF_bdd x N) }
end
/-- Composition (in the target) of a bounded continuous function with a Lipschitz map again
gives a bounded continuous function -/
def comp (G : β → γ) {C : ℝ≥0} (H : lipschitz_with C G)
(f : α →ᵇ β) : α →ᵇ γ :=
⟨⟨λx, G (f x), H.continuous.comp f.continuous⟩,
let ⟨D, hD⟩ := f.bounded in
⟨max C 0 * D, λ x y, calc
dist (G (f x)) (G (f y)) ≤ C * dist (f x) (f y) : H.dist_le_mul _ _
... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left C 0) dist_nonneg
... ≤ max C 0 * D : mul_le_mul_of_nonneg_left (hD _ _) (le_max_right C 0)⟩⟩
/-- The composition operator (in the target) with a Lipschitz map is Lipschitz -/
lemma lipschitz_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
lipschitz_with C (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
lipschitz_with.of_dist_le_mul $ λ f g,
(dist_le (mul_nonneg C.2 dist_nonneg)).2 $ λ x,
calc dist (G (f x)) (G (g x)) ≤ C * dist (f x) (g x) : H.dist_le_mul _ _
... ≤ C * dist f g : mul_le_mul_of_nonneg_left (dist_coe_le_dist _) C.2
/-- The composition operator (in the target) with a Lipschitz map is uniformly continuous -/
lemma uniform_continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
uniform_continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).uniform_continuous
/-- The composition operator (in the target) with a Lipschitz map is continuous -/
lemma continuous_comp {G : β → γ} {C : ℝ≥0} (H : lipschitz_with C G) :
continuous (comp G H : (α →ᵇ β) → α →ᵇ γ) :=
(lipschitz_comp H).continuous
/-- Restriction (in the target) of a bounded continuous function taking values in a subset -/
def cod_restrict (s : set β) (f : α →ᵇ β) (H : ∀x, f x ∈ s) : α →ᵇ s :=
⟨⟨s.cod_restrict f H, continuous_subtype_mk _ f.continuous⟩, f.bounded⟩
end basics
section arzela_ascoli
variables [topological_space α] [compact_space α] [metric_space β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
/- Arzela-Ascoli theorem asserts that, on a compact space, a set of functions sharing
a common modulus of continuity and taking values in a compact set forms a compact
subset for the topology of uniform convergence. In this section, we prove this theorem
and several useful variations around it. -/
/-- First version, with pointwise equicontinuity and range in a compact space -/
theorem arzela_ascoli₁ [compact_space β]
(A : set (α →ᵇ β))
(closed : is_closed A)
(H : ∀ (x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
begin
refine compact_of_totally_bounded_is_closed _ closed,
refine totally_bounded_of_finite_discretization (λ ε ε0, _),
rcases exists_between ε0 with ⟨ε₁, ε₁0, εε₁⟩,
let ε₂ := ε₁/2/2,
/- We have to find a finite discretization of `u`, i.e., finite information
that is sufficient to reconstruct `u` up to ε. This information will be
provided by the values of `u` on a sufficiently dense set tα,
slightly translated to fit in a finite ε₂-dense set tβ in the image. Such
sets exist by compactness of the source and range. Then, to check that these
data determine the function up to ε, one uses the control on the modulus of
continuity to extend the closeness on tα to closeness everywhere. -/
have ε₂0 : ε₂ > 0 := half_pos (half_pos ε₁0),
have : ∀x:α, ∃U, x ∈ U ∧ is_open U ∧ ∀ (y z ∈ U) {f : α →ᵇ β},
f ∈ A → dist (f y) (f z) < ε₂ := λ x,
let ⟨U, nhdsU, hU⟩ := H x _ ε₂0,
⟨V, VU, openV, xV⟩ := _root_.mem_nhds_iff.1 nhdsU in
⟨V, xV, openV, λy z hy hz f hf, hU y z (VU hy) (VU hz) f hf⟩,
choose U hU using this,
/- For all x, the set hU x is an open set containing x on which the elements of A
fluctuate by at most ε₂.
We extract finitely many of these sets that cover the whole space, by compactness -/
rcases compact_univ.elim_finite_subcover_image
(λx _, (hU x).2.1) (λx hx, mem_bUnion (mem_univ _) (hU x).1)
with ⟨tα, _, ⟨_⟩, htα⟩,
/- tα : set α, htα : univ ⊆ ⋃x ∈ tα, U x -/
rcases @finite_cover_balls_of_compact β _ _ compact_univ _ ε₂0
with ⟨tβ, _, ⟨_⟩, htβ⟩, resetI,
/- tβ : set β, htβ : univ ⊆ ⋃y ∈ tβ, ball y ε₂ -/
/- Associate to every point `y` in the space a nearby point `F y` in tβ -/
choose F hF using λy, show ∃z∈tβ, dist y z < ε₂, by simpa using htβ (mem_univ y),
/- F : β → β, hF : ∀ (y : β), F y ∈ tβ ∧ dist y (F y) < ε₂ -/
/- Associate to every function a discrete approximation, mapping each point in `tα`
to a point in `tβ` close to its true image by the function. -/
refine ⟨tα → tβ, by apply_instance, λ f a, ⟨F (f a), (hF (f a)).1⟩, _⟩,
rintro ⟨f, hf⟩ ⟨g, hg⟩ f_eq_g,
/- If two functions have the same approximation, then they are within distance ε -/
refine lt_of_le_of_lt ((dist_le $ le_of_lt ε₁0).2 (λ x, _)) εε₁,
obtain ⟨x', x'tα, hx'⟩ : ∃x' ∈ tα, x ∈ U x' := mem_bUnion_iff.1 (htα (mem_univ x)),
refine calc dist (f x) (g x)
≤ dist (f x) (f x') + dist (g x) (g x') + dist (f x') (g x') : dist_triangle4_right _ _ _ _
... ≤ ε₂ + ε₂ + ε₁/2 : le_of_lt (add_lt_add (add_lt_add _ _) _)
... = ε₁ : by rw [add_halves, add_halves],
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hf },
{ exact (hU x').2.2 _ _ hx' ((hU x').1) hg },
{ have F_f_g : F (f x') = F (g x') :=
(congr_arg (λ f:tα → tβ, (f ⟨x', x'tα⟩ : β)) f_eq_g : _),
calc dist (f x') (g x')
≤ dist (f x') (F (f x')) + dist (g x') (F (f x')) : dist_triangle_right _ _ _
... = dist (f x') (F (f x')) + dist (g x') (F (g x')) : by rw F_f_g
... < ε₂ + ε₂ : add_lt_add (hF (f x')).2 (hF (g x')).2
... = ε₁/2 : add_halves _ }
end
/-- Second version, with pointwise equicontinuity and range in a compact subset -/
theorem arzela_ascoli₂
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(closed : is_closed A)
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact A :=
/- This version is deduced from the previous one by restricting to the compact type in the target,
using compactness there and then lifting everything to the original space. -/
begin
have M : lipschitz_with 1 coe := lipschitz_with.subtype_coe s,
let F : (α →ᵇ s) → α →ᵇ β := comp coe M,
refine compact_of_is_closed_subset
((_ : is_compact (F ⁻¹' A)).image (continuous_comp M)) closed (λ f hf, _),
{ haveI : compact_space s := is_compact_iff_compact_space.1 hs,
refine arzela_ascoli₁ _ (continuous_iff_is_closed.1 (continuous_comp M) _ closed)
(λ x ε ε0, bex.imp_right (λ U U_nhds hU y z hy hz f hf, _) (H x ε ε0)),
calc dist (f y) (f z) = dist (F f y) (F f z) : rfl
... < ε : hU y z hy hz (F f) hf },
{ let g := cod_restrict s f (λx, in_s f x hf),
rw [show f = F g, by ext; refl] at hf ⊢,
exact ⟨g, hf, rfl⟩ }
end
/-- Third (main) version, with pointwise equicontinuity and range in a compact subset, but
without closedness. The closure is then compact -/
theorem arzela_ascoli
(s : set β) (hs : is_compact s)
(A : set (α →ᵇ β))
(in_s : ∀(f : α →ᵇ β) (x : α), f ∈ A → f x ∈ s)
(H : ∀(x:α) (ε > 0), ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε) :
is_compact (closure A) :=
/- This version is deduced from the previous one by checking that the closure of A, in
addition to being closed, still satisfies the properties of compact range and equicontinuity -/
arzela_ascoli₂ s hs (closure A) is_closed_closure
(λ f x hf, (mem_of_closed' hs.is_closed).2 $ λ ε ε0,
let ⟨g, gA, dist_fg⟩ := metric.mem_closure_iff.1 hf ε ε0 in
⟨g x, in_s g x gA, lt_of_le_of_lt (dist_coe_le_dist _) dist_fg⟩)
(λ x ε ε0, show ∃ U ∈ 𝓝 x,
∀ y z ∈ U, ∀ (f : α →ᵇ β), f ∈ closure A → dist (f y) (f z) < ε,
begin
refine bex.imp_right (λ U U_set hU y z hy hz f hf, _) (H x (ε/2) (half_pos ε0)),
rcases metric.mem_closure_iff.1 hf (ε/2/2) (half_pos (half_pos ε0)) with ⟨g, gA, dist_fg⟩,
replace dist_fg := λ x, lt_of_le_of_lt (dist_coe_le_dist x) dist_fg,
calc dist (f y) (f z) ≤ dist (f y) (g y) + dist (f z) (g z) + dist (g y) (g z) :
dist_triangle4_right _ _ _ _
... < ε/2/2 + ε/2/2 + ε/2 :
add_lt_add (add_lt_add (dist_fg y) (dist_fg z)) (hU y z hy hz g gA)
... = ε : by rw [add_halves, add_halves]
end)
/- To apply the previous theorems, one needs to check the equicontinuity. An important
instance is when the source space is a metric space, and there is a fixed modulus of continuity
for all the functions in the set A -/
lemma equicontinuous_of_continuity_modulus {α : Type u} [metric_space α]
(b : ℝ → ℝ) (b_lim : tendsto b (𝓝 0) (𝓝 0))
(A : set (α →ᵇ β))
(H : ∀(x y:α) (f : α →ᵇ β), f ∈ A → dist (f x) (f y) ≤ b (dist x y))
(x:α) (ε : ℝ) (ε0 : 0 < ε) : ∃U ∈ 𝓝 x, ∀ (y z ∈ U) (f : α →ᵇ β),
f ∈ A → dist (f y) (f z) < ε :=
begin
rcases tendsto_nhds_nhds.1 b_lim ε ε0 with ⟨δ, δ0, hδ⟩,
refine ⟨ball x (δ/2), ball_mem_nhds x (half_pos δ0), λ y z hy hz f hf, _⟩,
have : dist y z < δ := calc
dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... < δ/2 + δ/2 : add_lt_add hy hz
... = δ : add_halves _,
calc
dist (f y) (f z) ≤ b (dist y z) : H y z f hf
... ≤ abs (b (dist y z)) : le_abs_self _
... = dist (b (dist y z)) 0 : by simp [real.dist_eq]
... < ε : hδ (by simpa [real.dist_eq] using this),
end
end arzela_ascoli
section normed_group
/- In this section, if β is a normed group, then we show that the space of bounded
continuous functions from α to β inherits a normed group structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] [normed_group β]
variables (f g : α →ᵇ β) {x : α} {C : ℝ}
instance : has_zero (α →ᵇ β) := ⟨const α 0⟩
@[simp] lemma coe_zero : ((0 : α →ᵇ β) : α → β) = 0 := rfl
instance : has_norm (α →ᵇ β) := ⟨λu, dist u 0⟩
lemma norm_def : ∥f∥ = dist f 0 := rfl
/-- The norm of a bounded continuous function is the supremum of `∥f x∥`.
We use `Inf` to ensure that the definition works if `α` has no elements. -/
lemma norm_eq (f : α →ᵇ β) :
∥f∥ = Inf {C : ℝ | 0 ≤ C ∧ ∀ (x : α), ∥f x∥ ≤ C} :=
by simp [norm_def, bounded_continuous_function.dist_eq]
lemma norm_coe_le_norm (x : α) : ∥f x∥ ≤ ∥f∥ := calc
∥f x∥ = dist (f x) ((0 : α →ᵇ β) x) : by simp [dist_zero_right]
... ≤ ∥f∥ : dist_coe_le_dist _
lemma dist_le_two_norm' {f : γ → β} {C : ℝ} (hC : ∀ x, ∥f x∥ ≤ C) (x y : γ) :
dist (f x) (f y) ≤ 2 * C :=
calc dist (f x) (f y) ≤ ∥f x∥ + ∥f y∥ : dist_le_norm_add_norm _ _
... ≤ C + C : add_le_add (hC x) (hC y)
... = 2 * C : (two_mul _).symm
/-- Distance between the images of any two points is at most twice the norm of the function. -/
lemma dist_le_two_norm (x y : α) : dist (f x) (f y) ≤ 2 * ∥f∥ :=
dist_le_two_norm' f.norm_coe_le_norm x y
variable {f}
/-- The norm of a function is controlled by the supremum of the pointwise norms -/
lemma norm_le (C0 : (0 : ℝ) ≤ C) : ∥f∥ ≤ C ↔ ∀x:α, ∥f x∥ ≤ C :=
by simpa using @dist_le _ _ _ _ f 0 _ C0
lemma norm_le_of_nonempty [nonempty α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ ≤ M ↔ ∀ x, ∥f x∥ ≤ M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_le_iff_of_nonempty,
end
lemma norm_lt_iff_of_compact [compact_space α]
{f : α →ᵇ β} {M : ℝ} (M0 : 0 < M) : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_compact M0,
end
lemma norm_lt_iff_of_nonempty_compact [nonempty α] [compact_space α]
{f : α →ᵇ β} {M : ℝ} : ∥f∥ < M ↔ ∀ x, ∥f x∥ < M :=
begin
simp_rw [norm_def, ←dist_zero_right],
exact dist_lt_iff_of_nonempty_compact,
end
variable (f)
/-- Norm of `const α b` is less than or equal to `∥b∥`. If `α` is nonempty,
then it is equal to `∥b∥`. -/
lemma norm_const_le (b : β) : ∥const α b∥ ≤ ∥b∥ :=
(norm_le (norm_nonneg b)).2 $ λ x, le_refl _
@[simp] lemma norm_const_eq [h : nonempty α] (b : β) : ∥const α b∥ = ∥b∥ :=
le_antisymm (norm_const_le b) $ h.elim $ λ x, (const α b).norm_coe_le_norm x
/-- Constructing a bounded continuous function from a uniformly bounded continuous
function taking values in a normed group. -/
def of_normed_group {α : Type u} {β : Type v} [topological_space α] [normed_group β]
(f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) : α →ᵇ β :=
⟨⟨λn, f n, Hf⟩, ⟨_, dist_le_two_norm' H⟩⟩
@[simp] lemma coe_of_normed_group
{α : Type u} {β : Type v} [topological_space α] [normed_group β]
(f : α → β) (Hf : continuous f) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_group f Hf C H : α → β) = f := rfl
lemma norm_of_normed_group_le {f : α → β} (hfc : continuous f) {C : ℝ} (hC : 0 ≤ C)
(hfC : ∀ x, ∥f x∥ ≤ C) : ∥of_normed_group f hfc C hfC∥ ≤ C :=
(norm_le hC).2 hfC
/-- Constructing a bounded continuous function from a uniformly bounded
function on a discrete space, taking values in a normed group -/
def of_normed_group_discrete {α : Type u} {β : Type v}
[topological_space α] [discrete_topology α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, norm (f x) ≤ C) : α →ᵇ β :=
of_normed_group f continuous_of_discrete_topology C H
@[simp] lemma coe_of_normed_group_discrete
{α : Type u} {β : Type v} [topological_space α] [discrete_topology α] [normed_group β]
(f : α → β) (C : ℝ) (H : ∀x, ∥f x∥ ≤ C) :
(of_normed_group_discrete f C H : α → β) = f := rfl
/-- The pointwise sum of two bounded continuous functions is again bounded continuous. -/
instance : has_add (α →ᵇ β) :=
⟨λf g, of_normed_group (f + g) (f.continuous.add g.continuous) (∥f∥ + ∥g∥) $ λ x,
le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) (g.norm_coe_le_norm x))⟩
/-- The pointwise opposite of a bounded continuous function is again bounded continuous. -/
instance : has_neg (α →ᵇ β) :=
⟨λf, of_normed_group (-f) f.continuous.neg ∥f∥ $ λ x,
trans_rel_right _ (norm_neg _) (f.norm_coe_le_norm x)⟩
/-- The pointwise difference of two bounded continuous functions is again bounded continuous. -/
instance : has_sub (α →ᵇ β) :=
⟨λf g, of_normed_group (f - g) (f.continuous.sub g.continuous) (∥f∥ + ∥g∥) $ λ x,
by { simp only [sub_eq_add_neg],
exact le_trans (norm_add_le _ _) (add_le_add (f.norm_coe_le_norm x) $
trans_rel_right _ (norm_neg _) (g.norm_coe_le_norm x)) }⟩
@[simp] lemma coe_add : ⇑(f + g) = f + g := rfl
lemma add_apply : (f + g) x = f x + g x := rfl
@[simp] lemma coe_neg : ⇑(-f) = -f := rfl
lemma neg_apply : (-f) x = -f x := rfl
lemma forall_coe_zero_iff_zero : (∀x, f x = 0) ↔ f = 0 :=
(@ext_iff _ _ _ _ f 0).symm
instance : add_comm_group (α →ᵇ β) :=
{ add_assoc := assume f g h, by ext; simp [add_assoc],
zero_add := assume f, by ext; simp,
add_zero := assume f, by ext; simp,
add_left_neg := assume f, by ext; simp,
add_comm := assume f g, by ext; simp [add_comm],
sub_eq_add_neg := assume f g, by { ext, apply sub_eq_add_neg },
..bounded_continuous_function.has_add,
..bounded_continuous_function.has_neg,
..bounded_continuous_function.has_sub,
..bounded_continuous_function.has_zero }
@[simp] lemma coe_sub : ⇑(f - g) = f - g := rfl
lemma sub_apply : (f - g) x = f x - g x := rfl
/-- Coercion of a `normed_group_hom` is an `add_monoid_hom`. Similar to `add_monoid_hom.coe_fn` -/
@[simps]
def coe_fn_add_hom : (α →ᵇ β) →+ (α → β) :=
{ to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add}
open_locale big_operators
@[simp] lemma coe_sum {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) :
⇑(∑ i in s, f i) = (∑ i in s, (f i : α → β)) :=
(@coe_fn_add_hom α β _ _).map_sum f s
lemma sum_apply {ι : Type*} (s : finset ι) (f : ι → (α →ᵇ β)) (a : α) :
(∑ i in s, f i) a = (∑ i in s, f i a) :=
by simp
instance : normed_group (α →ᵇ β) :=
{ dist_eq := λ f g, by simp only [norm_eq, dist_eq, dist_eq_norm, sub_apply] }
lemma abs_diff_coe_le_dist : ∥f x - g x∥ ≤ dist f g :=
by { rw dist_eq_norm, exact (f - g).norm_coe_le_norm x }
lemma coe_le_coe_add_dist {f g : α →ᵇ ℝ} : f x ≤ g x + dist f g :=
sub_le_iff_le_add'.1 $ (abs_le.1 $ @dist_coe_le_dist _ _ _ _ f g x).2
variables (α β)
/--
The additive map forgetting that a bounded continuous function is bounded.
-/
@[simps]
def forget_boundedness_add_hom : (α →ᵇ β) →+ C(α, β) :=
{ to_fun := forget_boundedness α β,
map_zero' := by { ext, simp, },
map_add' := by { intros, ext, simp, }, }
end normed_group
section normed_space
/-!
### Normed space structure
In this section, if `β` is a normed space, then we show that the space of bounded
continuous functions from `α` to `β` inherits a normed space structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*} [normed_field 𝕜]
variables [topological_space α] [normed_group β] [normed_space 𝕜 β]
variables {f g : α →ᵇ β} {x : α} {C : ℝ}
instance : has_scalar 𝕜 (α →ᵇ β) :=
⟨λ c f, of_normed_group (c • f) (f.continuous.const_smul c) (∥c∥ * ∥f∥) $ λ x,
trans_rel_right _ (norm_smul _ _)
(mul_le_mul_of_nonneg_left (f.norm_coe_le_norm _) (norm_nonneg _))⟩
@[simp] lemma coe_smul (c : 𝕜) (f : α →ᵇ β) : ⇑(c • f) = λ x, c • (f x) := rfl
lemma smul_apply (c : 𝕜) (f : α →ᵇ β) (x : α) : (c • f) x = c • f x := rfl
instance : module 𝕜 (α →ᵇ β) :=
module.of_core $
{ smul := (•),
smul_add := λ c f g, ext $ λ x, smul_add c (f x) (g x),
add_smul := λ c₁ c₂ f, ext $ λ x, add_smul c₁ c₂ (f x),
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul c₁ c₂ (f x),
one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) }
instance : normed_space 𝕜 (α →ᵇ β) := ⟨λ c f, norm_of_normed_group_le _
(mul_nonneg (norm_nonneg _) (norm_nonneg _)) _⟩
variables (𝕜)
/-- The evaluation at a point, as a continuous linear map from `α →ᵇ β` to `β`. -/
def eval_clm (x : α) : (α →ᵇ β) →L[𝕜] β :=
{ to_fun := λ f, f x,
map_add' := λ f g, by simp only [pi.add_apply, coe_add],
map_smul' := λ c f, by simp only [coe_smul] }
@[simp] lemma eval_clm_apply (x : α) (f : α →ᵇ β) :
eval_clm 𝕜 x f = f x := rfl
variables (α β)
/-- The linear map forgetting that a bounded continuous function is bounded. -/
@[simps]
def forget_boundedness_linear_map : (α →ᵇ β) →ₗ[𝕜] C(α, β) :=
{ to_fun := forget_boundedness α β,
map_smul' := by { intros, ext, simp, },
map_add' := by { intros, ext, simp, }, }
end normed_space
section normed_ring
/-!
### Normed ring structure
In this section, if `R` is a normed ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*} [normed_ring R]
instance : ring (α →ᵇ R) :=
{ one := const α 1,
mul := λ f g, of_normed_group (f * g) (f.continuous.mul g.continuous) (∥f∥ * ∥g∥) $ λ x,
le_trans (normed_ring.norm_mul (f x) (g x)) $
mul_le_mul (f.norm_coe_le_norm x) (g.norm_coe_le_norm x) (norm_nonneg _) (norm_nonneg _),
one_mul := λ f, ext $ λ x, one_mul (f x),
mul_one := λ f, ext $ λ x, mul_one (f x),
mul_assoc := λ f₁ f₂ f₃, ext $ λ x, mul_assoc _ _ _,
left_distrib := λ f₁ f₂ f₃, ext $ λ x, left_distrib _ _ _,
right_distrib := λ f₁ f₂ f₃, ext $ λ x, right_distrib _ _ _,
.. bounded_continuous_function.add_comm_group }
@[simp] lemma coe_mul (f g : α →ᵇ R) : ⇑(f * g) = f * g := rfl
lemma mul_apply (f g : α →ᵇ R) (x : α) : (f * g) x = f x * g x := rfl
instance : normed_ring (α →ᵇ R) :=
{ norm_mul := λ f g, norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _,
.. bounded_continuous_function.normed_group }
end normed_ring
section normed_comm_ring
/-!
### Normed commutative ring structure
In this section, if `R` is a normed commutative ring, then we show that the space of bounded
continuous functions from `α` to `R` inherits a normed commutative ring structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables [topological_space α] {R : Type*} [normed_comm_ring R]
instance : comm_ring (α →ᵇ R) :=
{ mul_comm := λ f₁ f₂, ext $ λ x, mul_comm _ _,
.. bounded_continuous_function.ring }
instance : normed_comm_ring (α →ᵇ R) :=
{ .. bounded_continuous_function.comm_ring, .. bounded_continuous_function.normed_group }
end normed_comm_ring
section normed_algebra
/-!
### Normed algebra structure
In this section, if `γ` is a normed algebra, then we show that the space of bounded
continuous functions from `α` to `γ` inherits a normed algebra structure, by using
pointwise operations and checking that they are compatible with the uniform distance. -/
variables {𝕜 : Type*} [normed_field 𝕜]
variables [topological_space α] [normed_group β] [normed_space 𝕜 β]
variables [normed_ring γ] [normed_algebra 𝕜 γ]
variables {f g : α →ᵇ γ} {x : α} {c : 𝕜}
/-- `bounded_continuous_function.const` as a `ring_hom`. -/
def C : 𝕜 →+* (α →ᵇ γ) :=
{ to_fun := λ (c : 𝕜), const α ((algebra_map 𝕜 γ) c),
map_one' := ext $ λ x, (algebra_map 𝕜 γ).map_one,
map_mul' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_mul _ _,
map_zero' := ext $ λ x, (algebra_map 𝕜 γ).map_zero,
map_add' := λ c₁ c₂, ext $ λ x, (algebra_map 𝕜 γ).map_add _ _ }
instance : algebra 𝕜 (α →ᵇ γ) :=
{ to_ring_hom := C,
commutes' := λ c f, ext $ λ x, algebra.commutes' _ _,
smul_def' := λ c f, ext $ λ x, algebra.smul_def' _ _,
..bounded_continuous_function.module,
..bounded_continuous_function.ring }
@[simp] lemma algebra_map_apply (k : 𝕜) (a : α) :
algebra_map 𝕜 (α →ᵇ γ) k a = k • 1 :=
by { rw algebra.algebra_map_eq_smul_one, refl, }
instance [nonempty α] : normed_algebra 𝕜 (α →ᵇ γ) :=
{ norm_algebra_map_eq := λ c, begin
calc ∥ (algebra_map 𝕜 (α →ᵇ γ)).to_fun c∥ = ∥(algebra_map 𝕜 γ) c∥ : _
... = ∥c∥ : norm_algebra_map_eq _ _,
apply norm_const_eq ((algebra_map 𝕜 γ) c), assumption,
end,
..bounded_continuous_function.algebra }
/-!
### Structure as normed module over scalar functions
If `β` is a normed `𝕜`-space, then we show that the space of bounded continuous
functions from `α` to `β` is naturally a module over the algebra of bounded continuous
functions from `α` to `𝕜`. -/
instance has_scalar' : has_scalar (α →ᵇ 𝕜) (α →ᵇ β) :=
⟨λ (f : α →ᵇ 𝕜) (g : α →ᵇ β), of_normed_group (λ x, (f x) • (g x))
(f.continuous.smul g.continuous) (∥f∥ * ∥g∥) (λ x, calc
∥f x • g x∥ ≤ ∥f x∥ * ∥g x∥ : normed_space.norm_smul_le _ _
... ≤ ∥f∥ * ∥g∥ : mul_le_mul (f.norm_coe_le_norm _) (g.norm_coe_le_norm _) (norm_nonneg _)
(norm_nonneg _)) ⟩
instance module' : module (α →ᵇ 𝕜) (α →ᵇ β) :=
module.of_core $
{ smul := (•),
smul_add := λ c f₁ f₂, ext $ λ x, smul_add _ _ _,
add_smul := λ c₁ c₂ f, ext $ λ x, add_smul _ _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
one_smul := λ f, ext $ λ x, one_smul 𝕜 (f x) }
lemma norm_smul_le (f : α →ᵇ 𝕜) (g : α →ᵇ β) : ∥f • g∥ ≤ ∥f∥ * ∥g∥ :=
norm_of_normed_group_le _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _
/- TODO: When `normed_module` has been added to `normed_space.basic`, the above facts
show that the space of bounded continuous functions from `α` to `β` is naturally a normed
module over the algebra of bounded continuous functions from `α` to `𝕜`. -/
end normed_algebra
end bounded_continuous_function
|
d13b903eb056dc236a488278a6ef407914aa17f7 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /src/Lean/Attributes.lean | 0b60c2355387183c55bcc420b3224f31d7d9f6d9 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 20,516 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.CoreM
import Lean.MonadEnv
namespace Lean
inductive AttributeApplicationTime where
| afterTypeChecking | afterCompilation | beforeElaboration
deriving Inhabited, BEq
abbrev AttrM := CoreM
instance : MonadLift ImportM AttrM where
monadLift x := do liftM (m := IO) (x { env := (← getEnv), opts := (← getOptions) })
structure AttributeImplCore where
/-- This is used as the target for go-to-definition queries for simple attributes -/
ref : Name := by exact decl_name%
name : Name
descr : String
applicationTime := AttributeApplicationTime.afterTypeChecking
deriving Inhabited
/-- You can tag attributes with the 'local' or 'scoped' kind.
For example: `attribute [local myattr, scoped yourattr, theirattr]`.
This is used to indicate how an attribute should be scoped.
- local means that the attribute should only be applied in the current scope and forgotten once the current section, namespace, or file is closed.
- scoped means that the attribute should only be applied while the namespace is open.
- global means that the attribute should always be applied.
Note that the attribute handler (`AttributeImpl.add`) is responsible for interpreting the kind and
making sure that these kinds are respected.
-/
inductive AttributeKind
| global | local | scoped
deriving BEq, Inhabited
instance : ToString AttributeKind where
toString
| .global => "global"
| .local => "local"
| .scoped => "scoped"
structure AttributeImpl extends AttributeImplCore where
/-- This is run when the attribute is applied to a declaration `decl`. `stx` is the syntax of the attribute including arguments. -/
add (decl : Name) (stx : Syntax) (kind : AttributeKind) : AttrM Unit
erase (decl : Name) : AttrM Unit := throwError "attribute cannot be erased"
deriving Inhabited
builtin_initialize attributeMapRef : IO.Ref (PersistentHashMap Name AttributeImpl) ← IO.mkRef {}
/-- Low level attribute registration function. -/
def registerBuiltinAttribute (attr : AttributeImpl) : IO Unit := do
let m ← attributeMapRef.get
if m.contains attr.name then throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attr.name ++ "' has already been used"))
unless (← initializing) do
throw (IO.userError "failed to register attribute, attributes can only be registered during initialization")
attributeMapRef.modify fun m => m.insert attr.name attr
/-!
Helper methods for decoding the parameters of builtin attributes that are defined before `Lean.Parser`.
We have the following ones:
```
@[builtinAttrParser] def simple := leading_parser ident >> optional ident >> optional priorityParser
/- We can't use `simple` for `class`, `instance`, `export` and `macro` because they are keywords. -/
@[builtinAttrParser] def «class» := leading_parser "class"
@[builtinAttrParser] def «instance» := leading_parser "instance" >> optional priorityParser
@[builtinAttrParser] def «macro» := leading_parser "macro " >> ident
```
Note that we need the parsers for `class`, `instance`, and `macros` because they are keywords.
-/
def Attribute.Builtin.ensureNoArgs (stx : Syntax) : AttrM Unit := do
if stx.getKind == `Lean.Parser.Attr.simple && stx[1].isNone && stx[2].isNone then
return ()
else if stx.getKind == `Lean.Parser.Attr.«class» then
return ()
else match stx with
| Syntax.missing => return () -- In the elaborator, we use `Syntax.missing` when creating attribute views for simple attributes such as `class and `inline
| _ => throwErrorAt stx "unexpected attribute argument"
def Attribute.Builtin.getIdent? (stx : Syntax) : AttrM (Option Syntax) := do
if stx.getKind == `Lean.Parser.Attr.simple then
if !stx[1].isNone && stx[1][0].isIdent then
return some stx[1][0]
else
return none
/- We handle `macro` here because it is handled by the generic `KeyedDeclsAttribute -/
else if stx.getKind == `Lean.Parser.Attr.«macro» || stx.getKind == `Lean.Parser.Attr.«export» then
return some stx[1]
else
throwErrorAt stx "unexpected attribute argument"
def Attribute.Builtin.getIdent (stx : Syntax) : AttrM Syntax := do
match (← getIdent? stx) with
| some id => return id
| none => throwErrorAt stx "unexpected attribute argument, identifier expected"
def Attribute.Builtin.getId? (stx : Syntax) : AttrM (Option Name) := do
let ident? ← getIdent? stx
return Syntax.getId <$> ident?
def Attribute.Builtin.getId (stx : Syntax) : AttrM Name := do
return (← getIdent stx).getId
def getAttrParamOptPrio (optPrioStx : Syntax) : AttrM Nat :=
if optPrioStx.isNone then
return eval_prio default
else match optPrioStx[0].isNatLit? with
| some prio => return prio
| none => throwErrorAt optPrioStx "priority expected"
def Attribute.Builtin.getPrio (stx : Syntax) : AttrM Nat := do
if stx.getKind == `Lean.Parser.Attr.simple then
getAttrParamOptPrio stx[1]
else
throwErrorAt stx "unexpected attribute argument, optional priority expected"
/--
Tag attributes are simple and efficient. They are useful for marking declarations in the modules where
they were defined.
The startup cost for this kind of attribute is very small since `addImportedFn` is a constant function.
They provide the predicate `tagAttr.hasTag env decl` which returns true iff declaration `decl`
is tagged in the environment `env`. -/
structure TagAttribute where
attr : AttributeImpl
ext : PersistentEnvExtension Name Name NameSet
deriving Inhabited
def registerTagAttribute (name : Name) (descr : String)
(validate : Name → AttrM Unit := fun _ => pure ()) (ref : Name := by exact decl_name%) : IO TagAttribute := do
let ext : PersistentEnvExtension Name Name NameSet ← registerPersistentEnvExtension {
name := name
mkInitial := pure {}
addImportedFn := fun _ _ => pure {}
addEntryFn := fun (s : NameSet) n => s.insert n
exportEntriesFn := fun es =>
let r : Array Name := es.fold (fun a e => a.push e) #[]
r.qsort Name.quickLt
statsFn := fun s => "tag attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrImpl : AttributeImpl := {
ref := ref
name := name
descr := descr
add := fun decl stx kind => do
Attribute.Builtin.ensureNoArgs stx
unless kind == AttributeKind.global do throwError "invalid attribute '{name}', must be global"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError "invalid attribute '{name}', declaration is in an imported module"
validate decl
modifyEnv fun env => ext.addEntry env decl
}
registerBuiltinAttribute attrImpl
return { attr := attrImpl, ext := ext }
namespace TagAttribute
def hasTag (attr : TagAttribute) (env : Environment) (decl : Name) : Bool :=
match env.getModuleIdxFor? decl with
| some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt
| none => (attr.ext.getState env).contains decl
end TagAttribute
/--
A `TagAttribute` variant where we can attach parameters to attributes.
It is slightly more expensive and consumes a little bit more memory than `TagAttribute`.
They provide the function `pAttr.getParam env decl` which returns `some p` iff declaration `decl`
contains the attribute `pAttr` with parameter `p`. -/
structure ParametricAttribute (α : Type) where
attr : AttributeImpl
ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α)
deriving Inhabited
structure ParametricAttributeImpl (α : Type) extends AttributeImplCore where
/-- This is used as the target for go-to-definition queries for simple attributes -/
getParam : Name → Syntax → AttrM α
afterSet : Name → α → AttrM Unit := fun _ _ _ => pure ()
afterImport : Array (Array (Name × α)) → ImportM Unit := fun _ => pure ()
def registerParametricAttribute [Inhabited α] (impl : ParametricAttributeImpl α) : IO (ParametricAttribute α) := do
let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := impl.name
mkInitial := pure {}
addImportedFn := fun s => impl.afterImport s *> pure {}
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[]
r.qsort (fun a b => Name.quickLt a.1 b.1)
statsFn := fun s => "parametric attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrImpl : AttributeImpl := {
ref := impl.ref
name := impl.name
descr := impl.descr
add := fun decl stx kind => do
unless kind == AttributeKind.global do throwError "invalid attribute '{impl.name}', must be global"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError "invalid attribute '{impl.name}', declaration is in an imported module"
let val ← impl.getParam decl stx
modifyEnv fun env => ext.addEntry env (decl, val)
try impl.afterSet decl val catch _ => setEnv env
}
registerBuiltinAttribute attrImpl
pure { attr := attrImpl, ext := ext }
namespace ParametricAttribute
def getParam? [Inhabited α] (attr : ParametricAttribute α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, default) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setParam (attr : ParametricAttribute α) (env : Environment) (decl : Name) (param : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, declaration is in an imported module")
else if ((attr.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, attribute has already been set")
else
Except.ok (attr.ext.addEntry env (decl, param))
end ParametricAttribute
/--
Given a list `[a₁, ..., a_n]` of elements of type `α`, `EnumAttributes` provides an attribute `Attr_i` for
associating a value `a_i` with an declaration. `α` is usually an enumeration type.
Note that whenever we register an `EnumAttributes`, we create `n` attributes, but only one environment extension. -/
structure EnumAttributes (α : Type) where
attrs : List AttributeImpl
ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α)
deriving Inhabited
def registerEnumAttributes [Inhabited α] (extName : Name) (attrDescrs : List (Name × String × α))
(validate : Name → α → AttrM Unit := fun _ _ => pure ())
(applicationTime := AttributeApplicationTime.afterTypeChecking)
(ref : Name := by exact decl_name%) : IO (EnumAttributes α) := do
let ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := extName
mkInitial := pure {}
addImportedFn := fun _ _ => pure {}
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[]
r.qsort (fun a b => Name.quickLt a.1 b.1)
statsFn := fun s => "enumeration attribute extension" ++ Format.line ++ "number of local entries: " ++ format s.size
}
let attrs := attrDescrs.map fun (name, descr, val) => {
ref := ref
name := name
descr := descr
add := fun decl stx kind => do
Attribute.Builtin.ensureNoArgs stx
unless kind == AttributeKind.global do throwError "invalid attribute '{name}', must be global"
let env ← getEnv
unless (env.getModuleIdxFor? decl).isNone do
throwError "invalid attribute '{name}', declaration is in an imported module"
validate decl val
modifyEnv fun env => ext.addEntry env (decl, val)
applicationTime := applicationTime
: AttributeImpl
}
attrs.forM registerBuiltinAttribute
pure { ext := ext, attrs := attrs }
namespace EnumAttributes
def getValue [Inhabited α] (attr : EnumAttributes α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, default) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setValue (attrs : EnumAttributes α) (env : Environment) (decl : Name) (val : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, declaration is in an imported module")
else if ((attrs.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, attribute has already been set")
else
Except.ok (attrs.ext.addEntry env (decl, val))
end EnumAttributes
/-!
Attribute extension and builders. We use builders to implement attribute factories for parser categories.
-/
abbrev AttributeImplBuilder := Name → List DataValue → Except String AttributeImpl
abbrev AttributeImplBuilderTable := HashMap Name AttributeImplBuilder
builtin_initialize attributeImplBuilderTableRef : IO.Ref AttributeImplBuilderTable ← IO.mkRef {}
def registerAttributeImplBuilder (builderId : Name) (builder : AttributeImplBuilder) : IO Unit := do
let table ← attributeImplBuilderTableRef.get
if table.contains builderId then throw (IO.userError ("attribute implementation builder '" ++ toString builderId ++ "' has already been declared"))
attributeImplBuilderTableRef.modify fun table => table.insert builderId builder
def mkAttributeImplOfBuilder (builderId ref : Name) (args : List DataValue) : IO AttributeImpl := do
let table ← attributeImplBuilderTableRef.get
match table.find? builderId with
| none => throw (IO.userError ("unknown attribute implementation builder '" ++ toString builderId ++ "'"))
| some builder => IO.ofExcept <| builder ref args
inductive AttributeExtensionOLeanEntry where
| decl (declName : Name) -- `declName` has type `AttributeImpl`
| builder (builderId ref : Name) (args : List DataValue)
structure AttributeExtensionState where
newEntries : List AttributeExtensionOLeanEntry := []
map : PersistentHashMap Name AttributeImpl
deriving Inhabited
abbrev AttributeExtension := PersistentEnvExtension AttributeExtensionOLeanEntry (AttributeExtensionOLeanEntry × AttributeImpl) AttributeExtensionState
private def AttributeExtension.mkInitial : IO AttributeExtensionState := do
let map ← attributeMapRef.get
pure { map := map }
unsafe def mkAttributeImplOfConstantUnsafe (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl :=
match env.find? declName with
| none => throw ("unknow constant '" ++ toString declName ++ "'")
| some info =>
match info.type with
| Expr.const `Lean.AttributeImpl _ => env.evalConst AttributeImpl opts declName
| _ => throw ("unexpected attribute implementation type at '" ++ toString declName ++ "' (`AttributeImpl` expected")
@[implementedBy mkAttributeImplOfConstantUnsafe]
opaque mkAttributeImplOfConstant (env : Environment) (opts : Options) (declName : Name) : Except String AttributeImpl
def mkAttributeImplOfEntry (env : Environment) (opts : Options) (e : AttributeExtensionOLeanEntry) : IO AttributeImpl :=
match e with
| .decl declName => IO.ofExcept <| mkAttributeImplOfConstant env opts declName
| .builder builderId ref args => mkAttributeImplOfBuilder builderId ref args
private def AttributeExtension.addImported (es : Array (Array AttributeExtensionOLeanEntry)) : ImportM AttributeExtensionState := do
let ctx ← read
let map ← attributeMapRef.get
let map ← es.foldlM
(fun map entries =>
entries.foldlM
(fun (map : PersistentHashMap Name AttributeImpl) entry => do
let attrImpl ← mkAttributeImplOfEntry ctx.env ctx.opts entry
return map.insert attrImpl.name attrImpl)
map)
map
pure { map := map }
private def addAttrEntry (s : AttributeExtensionState) (e : AttributeExtensionOLeanEntry × AttributeImpl) : AttributeExtensionState :=
{ s with map := s.map.insert e.2.name e.2, newEntries := e.1 :: s.newEntries }
builtin_initialize attributeExtension : AttributeExtension ←
registerPersistentEnvExtension {
name := `attrExt
mkInitial := AttributeExtension.mkInitial
addImportedFn := AttributeExtension.addImported
addEntryFn := addAttrEntry
exportEntriesFn := fun s => s.newEntries.reverse.toArray
statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length
}
/-- Return true iff `n` is the name of a registered attribute. -/
@[export lean_is_attribute]
def isBuiltinAttribute (n : Name) : IO Bool := do
let m ← attributeMapRef.get; pure (m.contains n)
/-- Return the name of all registered attributes. -/
def getBuiltinAttributeNames : IO (List Name) :=
return (← attributeMapRef.get).foldl (init := []) fun r n _ => n::r
def getBuiltinAttributeImpl (attrName : Name) : IO AttributeImpl := do
let m ← attributeMapRef.get
match m.find? attrName with
| some attr => pure attr
| none => throw (IO.userError ("unknown attribute '" ++ toString attrName ++ "'"))
@[export lean_attribute_application_time]
def getBuiltinAttributeApplicationTime (n : Name) : IO AttributeApplicationTime := do
let attr ← getBuiltinAttributeImpl n
pure attr.applicationTime
def isAttribute (env : Environment) (attrName : Name) : Bool :=
(attributeExtension.getState env).map.contains attrName
def getAttributeNames (env : Environment) : List Name :=
let m := (attributeExtension.getState env).map
m.foldl (fun r n _ => n::r) []
def getAttributeImpl (env : Environment) (attrName : Name) : Except String AttributeImpl :=
let m := (attributeExtension.getState env).map
match m.find? attrName with
| some attr => pure attr
| none => throw ("unknown attribute '" ++ toString attrName ++ "'")
def registerAttributeOfDecl (env : Environment) (opts : Options) (attrDeclName : Name) : Except String Environment := do
let attrImpl ← mkAttributeImplOfConstant env opts attrDeclName
if isAttribute env attrImpl.name then
throw ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used")
else
return attributeExtension.addEntry env (.decl attrDeclName, attrImpl)
def registerAttributeOfBuilder (env : Environment) (builderId ref : Name) (args : List DataValue) : IO Environment := do
let attrImpl ← mkAttributeImplOfBuilder builderId ref args
if isAttribute env attrImpl.name then
throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used"))
else
return attributeExtension.addEntry env (.builder builderId ref args, attrImpl)
def Attribute.add (declName : Name) (attrName : Name) (stx : Syntax) (kind := AttributeKind.global) : AttrM Unit := do
let attr ← ofExcept <| getAttributeImpl (← getEnv) attrName
attr.add declName stx kind
def Attribute.erase (declName : Name) (attrName : Name) : AttrM Unit := do
let attr ← ofExcept <| getAttributeImpl (← getEnv) attrName
attr.erase declName
/-- `updateEnvAttributes` implementation -/
@[export lean_update_env_attributes]
def updateEnvAttributesImpl (env : Environment) : IO Environment := do
let map ← attributeMapRef.get
let s := attributeExtension.getState env
let s := map.foldl (init := s) fun s attrName attrImpl =>
if s.map.contains attrName then
s
else
{ s with map := s.map.insert attrName attrImpl }
return attributeExtension.setState env s
/-- `getNumBuiltinAttributes` implementation -/
@[export lean_get_num_attributes] def getNumBuiltiAttributesImpl : IO Nat :=
return (← attributeMapRef.get).size
end Lean
|
9062125bbb1169b02930d8195e38e25b695cd0ca | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/multiset/antidiagonal.lean | 819ad5fb53b8ef1461971eec578bcbdc7ebf3a16 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 2,976 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.multiset.powerset
/-!
# The antidiagonal on a multiset.
The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities.
-/
namespace multiset
open list
variables {α β : Type*}
/-- The antidiagonal of a multiset `s` consists of all pairs `(t₁, t₂)`
such that `t₁ + t₂ = s`. These pairs are counted with multiplicities. -/
def antidiagonal (s : multiset α) : multiset (multiset α × multiset α) :=
quot.lift_on s
(λ l, (revzip (powerset_aux l) : multiset (multiset α × multiset α)))
(λ l₁ l₂ h, quot.sound (revzip_powerset_aux_perm h))
theorem antidiagonal_coe (l : list α) :
@antidiagonal α l = revzip (powerset_aux l) := rfl
@[simp] theorem antidiagonal_coe' (l : list α) :
@antidiagonal α l = revzip (powerset_aux' l) :=
quot.sound revzip_powerset_aux_perm_aux'
/-- A pair `(t₁, t₂)` of multisets is contained in `antidiagonal s`
if and only if `t₁ + t₂ = s`. -/
@[simp] theorem mem_antidiagonal {s : multiset α} {x : multiset α × multiset α} :
x ∈ antidiagonal s ↔ x.1 + x.2 = s :=
quotient.induction_on s $ λ l, begin
simp [antidiagonal_coe], refine ⟨λ h, revzip_powerset_aux h, λ h, _⟩,
haveI := classical.dec_eq α,
simp [revzip_powerset_aux_lemma l revzip_powerset_aux, h.symm],
cases x with x₁ x₂,
exact ⟨_, le_add_right _ _, by rw add_sub_cancel_left _ _⟩
end
@[simp] theorem antidiagonal_map_fst (s : multiset α) :
(antidiagonal s).map prod.fst = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_map_snd (s : multiset α) :
(antidiagonal s).map prod.snd = powerset s :=
quotient.induction_on s $ λ l,
by simp [powerset_aux']
@[simp] theorem antidiagonal_zero : @antidiagonal α 0 = (0, 0)::0 := rfl
@[simp] theorem antidiagonal_cons (a : α) (s) : antidiagonal (a::s) =
map (prod.map id (cons a)) (antidiagonal s) +
map (prod.map (cons a) id) (antidiagonal s) :=
quotient.induction_on s $ λ l, begin
simp only [revzip, reverse_append, quot_mk_to_coe, coe_eq_coe, powerset_aux'_cons, cons_coe,
coe_map, antidiagonal_coe', coe_add],
rw [← zip_map, ← zip_map, zip_append, (_ : _++_=_)],
{congr; simp}, {simp}
end
@[simp] theorem card_antidiagonal (s : multiset α) :
card (antidiagonal s) = 2 ^ card s :=
by have := card_powerset s;
rwa [← antidiagonal_map_fst, card_map] at this
lemma prod_map_add [comm_semiring β] {s : multiset α} {f g : α → β} :
prod (s.map (λa, f a + g a)) =
sum ((antidiagonal s).map (λp, (p.1.map f).prod * (p.2.map g).prod)) :=
begin
refine s.induction_on _ _,
{ simp },
{ assume a s ih,
simp [ih, add_mul, mul_comm, mul_left_comm, mul_assoc, sum_map_mul_left.symm],
cc },
end
end multiset
|
88cadabb89144c3acf3fc0955894cb29102a48e0 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/bad_end_error_pos.lean | cf4c7a84cf788387ccf7b7ff1df6fb885df53380 | [
"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 | 312 | lean | example (a b : nat) (f : nat → nat) : f (a + b) = f (b + a) :=
by rw nat.add_comm
example (a b : nat) (f : nat → nat) : f (a * b) = f (b * a) :=
by rw nat.mul_comm
end
example (a b c : nat) (f : nat → nat → nat) : f (b * c) (a * b * c) = f (c * b) (a * (b * c)) :=
by rw [nat.mul_assoc, nat.mul_comm]
|
470736faa9a49fe454643f137a4ddaf2e0899f8c | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/init/data/int/order.lean | b3f566eff37686178bb52a322f21643545cb95a8 | [
"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 | 11,821 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
The order relation on the integers.
-/
prelude
import init.data.int.basic init.data.ordering.basic
namespace int
private def nonneg (a : ℤ) : Prop := int.cases_on a (assume n, true) (assume n, false)
protected def le (a b : ℤ) : Prop := nonneg (b - a)
instance : has_le int := ⟨int.le⟩
protected def lt (a b : ℤ) : Prop := (a + 1) ≤ b
instance : has_lt int := ⟨int.lt⟩
private def decidable_nonneg (a : ℤ) : decidable (nonneg a) :=
int.cases_on a (assume a, decidable.true) (assume a, decidable.false)
instance decidable_le (a b : ℤ) : decidable (a ≤ b) := decidable_nonneg _
instance decidable_lt (a b : ℤ) : decidable (a < b) := decidable_nonneg _
lemma lt_iff_add_one_le (a b : ℤ) : a < b ↔ a + 1 ≤ b := iff.refl _
private lemma nonneg.elim {a : ℤ} : nonneg a → ∃ n : ℕ, a = n :=
int.cases_on a (assume n H, exists.intro n rfl) (assume n', false.elim)
private lemma nonneg_or_nonneg_neg (a : ℤ) : nonneg a ∨ nonneg (-a) :=
int.cases_on a (assume n, or.inl trivial) (assume n, or.inr trivial)
lemma le.intro_sub {a b : ℤ} {n : ℕ} (h : b - a = n) : a ≤ b :=
show nonneg (b - a), by rw h; trivial
lemma le.intro {a b : ℤ} {n : ℕ} (h : a + n = b) : a ≤ b :=
le.intro_sub (by rw [← h]; simp)
lemma le.dest_sub {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, b - a = n := nonneg.elim h
lemma le.dest {a b : ℤ} (h : a ≤ b) : ∃ n : ℕ, a + n = b :=
match (le.dest_sub h) with
| ⟨n, h₁⟩ := exists.intro n begin rw [← h₁, add_comm], simp end
end
lemma le.elim {a b : ℤ} (h : a ≤ b) {P : Prop} (h' : ∀ n : ℕ, a + ↑n = b → P) : P :=
exists.elim (le.dest h) h'
protected lemma le_total (a b : ℤ) : a ≤ b ∨ b ≤ a :=
or.imp_right
(assume H : nonneg (-(b - a)),
have -(b - a) = a - b, by simp,
show nonneg (a - b), from this ▸ H)
(nonneg_or_nonneg_neg (b - a))
lemma coe_nat_le_coe_nat_of_le {m n : ℕ} (h : m ≤ n) : (↑m : ℤ) ≤ ↑n :=
match nat.le.dest h with
| ⟨k, (hk : m + k = n)⟩ := le.intro (begin rw [← hk], reflexivity end)
end
lemma le_of_coe_nat_le_coe_nat {m n : ℕ} (h : (↑m : ℤ) ≤ ↑n) : m ≤ n :=
le.elim h (assume k, assume hk : ↑m + ↑k = ↑n,
have m + k = n, from int.coe_nat_inj ((int.coe_nat_add m k).trans hk),
nat.le.intro this)
lemma coe_nat_le_coe_nat_iff (m n : ℕ) : (↑m : ℤ) ≤ ↑n ↔ m ≤ n :=
iff.intro le_of_coe_nat_le_coe_nat coe_nat_le_coe_nat_of_le
lemma coe_zero_le (n : ℕ) : 0 ≤ (↑n : ℤ) :=
coe_nat_le_coe_nat_of_le n.zero_le
lemma eq_coe_of_zero_le {a : ℤ} (h : 0 ≤ a) : ∃ n : ℕ, a = n :=
by have t := le.dest_sub h; simp at t; exact t
lemma eq_succ_of_zero_lt {a : ℤ} (h : 0 < a) : ∃ n : ℕ, a = n.succ :=
let ⟨n, (h : ↑(1+n) = a)⟩ := le.dest h in
⟨n, by rw add_comm at h; exact h.symm⟩
lemma lt_add_succ (a : ℤ) (n : ℕ) : a < a + ↑(nat.succ n) :=
le.intro (show a + 1 + n = a + nat.succ n, begin simp [int.coe_nat_eq], reflexivity end)
lemma lt.intro {a b : ℤ} {n : ℕ} (h : a + nat.succ n = b) : a < b :=
h ▸ lt_add_succ a n
lemma lt.dest {a b : ℤ} (h : a < b) : ∃ n : ℕ, a + ↑(nat.succ n) = b :=
le.elim h (assume n, assume hn : a + 1 + n = b,
exists.intro n begin rw [← hn, add_assoc, add_comm (1 : int)], reflexivity end)
lemma lt.elim {a b : ℤ} (h : a < b) {P : Prop} (h' : ∀ n : ℕ, a + ↑(nat.succ n) = b → P) : P :=
exists.elim (lt.dest h) h'
lemma coe_nat_lt_coe_nat_iff (n m : ℕ) : (↑n : ℤ) < ↑m ↔ n < m :=
begin rw [lt_iff_add_one_le, ← int.coe_nat_succ, coe_nat_le_coe_nat_iff], reflexivity end
lemma lt_of_coe_nat_lt_coe_nat {m n : ℕ} (h : (↑m : ℤ) < ↑n) : m < n :=
(coe_nat_lt_coe_nat_iff _ _).mp h
lemma coe_nat_lt_coe_nat_of_lt {m n : ℕ} (h : m < n) : (↑m : ℤ) < ↑n :=
(coe_nat_lt_coe_nat_iff _ _).mpr h
/- show that the integers form an ordered additive group -/
protected lemma le_refl (a : ℤ) : a ≤ a :=
le.intro (add_zero a)
protected lemma le_trans {a b c : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ c) : a ≤ c :=
le.elim h₁ (assume n, assume hn : a + n = b,
le.elim h₂ (assume m, assume hm : b + m = c,
begin apply le.intro, rw [← hm, ← hn, add_assoc], reflexivity end))
protected lemma le_antisymm {a b : ℤ} (h₁ : a ≤ b) (h₂ : b ≤ a) : a = b :=
le.elim h₁ (assume n, assume hn : a + n = b,
le.elim h₂ (assume m, assume hm : b + m = a,
have a + ↑(n + m) = a + 0, by rw [int.coe_nat_add, ← add_assoc, hn, hm, add_zero a],
have (↑(n + m) : ℤ) = 0, from add_left_cancel this,
have n + m = 0, from int.coe_nat_inj this,
have n = 0, from nat.eq_zero_of_add_eq_zero_right this,
show a = b, begin rw [← hn, this, int.coe_nat_zero, add_zero a] end))
protected lemma lt_irrefl (a : ℤ) : ¬ a < a :=
assume : a < a,
lt.elim this (assume n, assume hn : a + nat.succ n = a,
have a + nat.succ n = a + 0, by rw [hn, add_zero],
have nat.succ n = 0, from int.coe_nat_inj (add_left_cancel this),
show false, from nat.succ_ne_zero _ this)
protected lemma ne_of_lt {a b : ℤ} (h : a < b) : a ≠ b :=
(assume : a = b, absurd (begin rewrite this at h, exact h end) (int.lt_irrefl b))
lemma le_of_lt {a b : ℤ} (h : a < b) : a ≤ b :=
lt.elim h (assume n, assume hn : a + nat.succ n = b, le.intro hn)
protected lemma lt_iff_le_and_ne (a b : ℤ) : a < b ↔ (a ≤ b ∧ a ≠ b) :=
iff.intro
(assume h, ⟨le_of_lt h, int.ne_of_lt h⟩)
(assume ⟨aleb, aneb⟩,
le.elim aleb (assume n, assume hn : a + n = b,
have n ≠ 0,
from (assume : n = 0, aneb begin rw [← hn, this, int.coe_nat_zero, add_zero] end),
have n = nat.succ (nat.pred n),
from eq.symm (nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero this)),
lt.intro (begin rewrite this at hn, exact hn end)))
lemma lt_succ (a : ℤ) : a < a + 1 :=
int.le_refl (a + 1)
protected lemma add_le_add_left {a b : ℤ} (h : a ≤ b) (c : ℤ) : c + a ≤ c + b :=
le.elim h (assume n, assume hn : a + n = b,
le.intro (show c + a + n = c + b, begin rw [add_assoc, hn] end))
protected lemma add_lt_add_left {a b : ℤ} (h : a < b) (c : ℤ) : c + a < c + b :=
iff.mpr (int.lt_iff_le_and_ne _ _)
(and.intro
(int.add_le_add_left (le_of_lt h) _)
(assume heq, int.lt_irrefl b begin rw add_left_cancel heq at h, exact h end))
protected lemma mul_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b :=
le.elim ha (assume n, assume hn,
le.elim hb (assume m, assume hm,
le.intro (show 0 + ↑n * ↑m = a * b, begin rw [← hn, ← hm], simp [zero_add] end)))
protected lemma mul_pos {a b : ℤ} (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
lt.elim ha (assume n, assume hn,
lt.elim hb (assume m, assume hm,
lt.intro (show 0 + ↑(nat.succ (nat.succ n * m + n)) = a * b,
begin rw [← hn, ← hm], simp [int.coe_nat_zero],
rw [← int.coe_nat_mul], simp [nat.mul_succ, nat.succ_add] end)))
protected lemma zero_lt_one : (0 : ℤ) < 1 := trivial
protected lemma lt_iff_le_not_le {a b : ℤ} : a < b ↔ (a ≤ b ∧ ¬ b ≤ a) :=
begin
simp [int.lt_iff_le_and_ne], split; intro h,
{ cases h with hab hn, split,
{ assumption },
{ intro hba, simp [int.le_antisymm hab hba] at *, contradiction } },
{ cases h with hab hn, split,
{ assumption },
{ intro h, simp [*] at * } }
end
instance : decidable_linear_ordered_comm_ring int :=
{ le := int.le,
le_refl := int.le_refl,
le_trans := @int.le_trans,
le_antisymm := @int.le_antisymm,
lt := int.lt,
lt_iff_le_not_le := @int.lt_iff_le_not_le,
add_le_add_left := @int.add_le_add_left,
add_lt_add_left := @int.add_lt_add_left,
zero_ne_one := int.zero_ne_one,
mul_nonneg := @int.mul_nonneg,
mul_pos := @int.mul_pos,
le_total := int.le_total,
zero_lt_one := int.zero_lt_one,
decidable_eq := int.decidable_eq,
decidable_le := int.decidable_le,
decidable_lt := int.decidable_lt,
..int.comm_ring }
instance : decidable_linear_ordered_comm_group int :=
by apply_instance
lemma eq_nat_abs_of_zero_le {a : ℤ} (h : 0 ≤ a) : a = nat_abs a :=
let ⟨n, e⟩ := eq_coe_of_zero_le h in by rw e; refl
lemma le_nat_abs {a : ℤ} : a ≤ nat_abs a :=
or.elim (le_total 0 a)
(λh, by rw eq_nat_abs_of_zero_le h; refl)
(λh, le_trans h (coe_zero_le _))
lemma neg_succ_lt_zero (n : ℕ) : -[1+ n] < 0 :=
lt_of_not_ge $ λ h, let ⟨m, h⟩ := eq_coe_of_zero_le h in by contradiction
lemma eq_neg_succ_of_lt_zero : ∀ {a : ℤ}, a < 0 → ∃ n : ℕ, a = -[1+ n]
| (n : ℕ) h := absurd h (not_lt_of_ge (coe_zero_le _))
| -[1+ n] h := ⟨n, rfl⟩
/- more facts specific to int -/
theorem of_nat_nonneg (n : ℕ) : 0 ≤ of_nat n := trivial
theorem coe_succ_pos (n : nat) : (nat.succ n : ℤ) > 0 :=
coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem exists_eq_neg_of_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -n :=
let ⟨n, h⟩ := eq_coe_of_zero_le (neg_nonneg_of_nonpos H) in
⟨n, eq_neg_of_eq_neg h.symm⟩
theorem nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : (nat_abs a : ℤ) = a :=
match a, eq_coe_of_zero_le H with ._, ⟨n, rfl⟩ := rfl end
theorem of_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : (nat_abs a : ℤ) = -a :=
by rw [← nat_abs_neg, nat_abs_of_nonneg (neg_nonneg_of_nonpos H)]
theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a
| (n : ℕ) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := H
theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := H
theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 :=
add_le_add_right H 1
theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b :=
le_of_add_le_add_right H
theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b :=
sub_right_lt_of_lt_add $ lt_add_one_of_le H
theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b :=
le_of_lt_add_one $ lt_add_of_sub_right_lt H
theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 :=
le_sub_right_of_add_le H
theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b :=
add_le_of_le_sub_right H
theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := rfl
theorem sign_eq_one_of_pos {a : ℤ} (h : 0 < a) : sign a = 1 :=
match a, eq_succ_of_zero_lt h with ._, ⟨n, rfl⟩ := rfl end
theorem sign_eq_neg_one_of_neg {a : ℤ} (h : a < 0) : sign a = -1 :=
match a, eq_neg_succ_of_lt_zero h with ._, ⟨n, rfl⟩ := rfl end
lemma eq_zero_of_sign_eq_zero : Π {a : ℤ}, sign a = 0 → a = 0
| 0 _ := rfl
theorem pos_of_sign_eq_one : ∀ {a : ℤ}, sign a = 1 → 0 < a
| (n+1:ℕ) _ := coe_nat_lt_coe_nat_of_lt (nat.succ_pos _)
theorem neg_of_sign_eq_neg_one : ∀ {a : ℤ}, sign a = -1 → a < 0
| (n+1:ℕ) h := match h with end
| 0 h := match h with end
| -[1+ n] _ := neg_succ_lt_zero _
theorem sign_eq_one_iff_pos (a : ℤ) : sign a = 1 ↔ 0 < a :=
⟨pos_of_sign_eq_one, sign_eq_one_of_pos⟩
theorem sign_eq_neg_one_iff_neg (a : ℤ) : sign a = -1 ↔ a < 0 :=
⟨neg_of_sign_eq_neg_one, sign_eq_neg_one_of_neg⟩
theorem sign_eq_zero_iff_zero (a : ℤ) : sign a = 0 ↔ a = 0 :=
⟨eq_zero_of_sign_eq_zero, λ h, by rw [h, sign_zero]⟩
theorem sign_mul_abs (a : ℤ) : sign a * abs a = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 :=
eq_of_mul_eq_mul_right Hpos (by rw [one_mul, H])
theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 :=
eq_of_mul_eq_mul_left Hpos (by rw [mul_one, H])
end int
|
6a433da4dd677303629710f6077226fe3787e8d1 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /stage0/src/Init/Data/String/Basic.lean | 6a6635d263d0b0390f767408a9781bc24449e2c2 | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 15,169 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import Init.Data.List.Basic
import Init.Data.Char.Basic
import Init.Data.Option.Basic
universes u
structure String :=
(data : List Char)
abbrev String.Pos := Nat
structure Substring :=
(str : String) (startPos : String.Pos) (stopPos : String.Pos)
attribute [extern "lean_string_mk"] String.mk
attribute [extern "lean_string_data"] String.data
@[extern "lean_string_dec_eq"]
def String.decEq (s₁ s₂ : @& String) : Decidable (s₁ = s₂) :=
match s₁, s₂ with
| ⟨s₁⟩, ⟨s₂⟩ =>
if h : s₁ = s₂ then isTrue (congrArg _ h)
else isFalse (fun h' => String.noConfusion h' (fun h' => absurd h' h))
instance : DecidableEq String :=
String.decEq
def List.asString (s : List Char) : String :=
⟨s⟩
namespace String
instance : HasLess String :=
⟨fun s₁ s₂ => s₁.data < s₂.data⟩
@[extern "lean_string_dec_lt"]
instance decLt (s₁ s₂ : @& String) : Decidable (s₁ < s₂) :=
List.hasDecidableLt s₁.data s₂.data
@[extern "lean_string_length"]
def length : (@& String) → Nat
| ⟨s⟩ => s.length
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_push"]
def push : String → Char → String
| ⟨s⟩, c => ⟨s ++ [c]⟩
/- The internal implementation uses dynamic arrays and will perform destructive updates
if the String is not shared. -/
@[extern "lean_string_append"]
def append : String → (@& String) → String
| ⟨a⟩, ⟨b⟩ => ⟨a ++ b⟩
/- O(n) in the runtime, where n is the length of the String -/
def toList (s : String) : List Char :=
s.data
private def csize (c : Char) : Nat :=
c.utf8Size.toNat
private def utf8ByteSizeAux : List Char → Nat → Nat
| [], r => r
| c::cs, r => utf8ByteSizeAux cs (r + csize c)
@[extern "lean_string_utf8_byte_size"]
def utf8ByteSize : (@& String) → Nat
| ⟨s⟩ => utf8ByteSizeAux s 0
@[inline] def bsize (s : String) : Nat :=
utf8ByteSize s
@[inline] def toSubstring (s : String) : Substring :=
{str := s, startPos := 0, stopPos := s.bsize}
private def utf8GetAux : List Char → Pos → Pos → Char
| [], i, p => arbitrary Char
| c::cs, i, p => if i = p then c else utf8GetAux cs (i + csize c) p
@[extern "lean_string_utf8_get"]
def get : (@& String) → (@& Pos) → Char
| ⟨s⟩, p => utf8GetAux s 0 p
private def utf8SetAux (c' : Char) : List Char → Pos → Pos → List Char
| [], i, p => []
| c::cs, i, p =>
if i = p then (c'::cs) else c::(utf8SetAux cs (i + csize c) p)
@[extern "lean_string_utf8_set"]
def set : String → (@& Pos) → Char → String
| ⟨s⟩, i, c => ⟨utf8SetAux c s 0 i⟩
@[extern "lean_string_utf8_next"]
def next (s : @& String) (p : @& Pos) : Pos :=
let c := get s p;
p + csize c
private def utf8PrevAux : List Char → Pos → Pos → Pos
| [], i, p => 0
| c::cs, i, p =>
let cz := csize c;
let i' := i + cz;
if i' = p then i else utf8PrevAux cs i' p
@[extern "lean_string_utf8_prev"]
def prev : (@& String) → (@& Pos) → Pos
| ⟨s⟩, p => if p = 0 then 0 else utf8PrevAux s 0 p
def front (s : String) : Char :=
get s 0
def back (s : String) : Char :=
get s (prev s (bsize s))
@[extern "lean_string_utf8_at_end"]
def atEnd : (@& String) → (@& Pos) → Bool
| s, p => p ≥ utf8ByteSize s
/- TODO: remove `partial` keywords after we restore the tactic
framework and wellfounded recursion support -/
partial def posOfAux (s : String) (c : Char) (stopPos : Pos) : Pos → Pos
| pos =>
if pos == stopPos then pos
else if s.get pos == c then pos
else posOfAux (s.next pos)
@[inline] def posOf (s : String) (c : Char) : Pos :=
posOfAux s c s.bsize 0
partial def revPosOfAux (s : String) (c : Char) : Pos → Option Pos
| pos =>
if s.get pos == c then some pos
else if pos == 0 then none
else revPosOfAux (s.prev pos)
def revPosOf (s : String) (c : Char) : Option Pos :=
if s.bsize == 0 then none
else revPosOfAux s c (s.prev s.bsize)
private def utf8ExtractAux₂ : List Char → Pos → Pos → List Char
| [], _, _ => []
| c::cs, i, e => if i = e then [] else c :: utf8ExtractAux₂ cs (i + csize c) e
private def utf8ExtractAux₁ : List Char → Pos → Pos → Pos → List Char
| [], _, _, _ => []
| s@(c::cs), i, b, e => if i = b then utf8ExtractAux₂ s i e else utf8ExtractAux₁ cs (i + csize c) b e
@[extern "lean_string_utf8_extract"]
def extract : (@& String) → (@& Pos) → (@& Pos) → String
| ⟨s⟩, b, e => if b ≥ e then ⟨[]⟩ else ⟨utf8ExtractAux₁ s 0 b e⟩
@[specialize] partial def splitAux (s : String) (p : Char → Bool) : Pos → Pos → List String → List String
| b, i, r =>
if s.atEnd i then
let r := if p (s.get i) then ""::(s.extract b (i-1))::r else (s.extract b i)::r;
r.reverse
else if p (s.get i) then
let i := s.next i;
splitAux i i (s.extract b (i-1)::r)
else splitAux b (s.next i) r
@[specialize] def split (s : String) (p : Char → Bool) : List String :=
splitAux s p 0 0 []
partial def splitOnAux (s sep : String) : Pos → Pos → Pos → List String → List String
| b, i, j, r =>
if s.atEnd i then
let r := if sep.atEnd j then ""::(s.extract b (i-j))::r else (s.extract b i)::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 (s.extract b (i-j)::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : String) (sep : String := " ") : List String :=
if sep == "" then [s] else splitOnAux s sep 0 0 0 []
instance : Inhabited String :=
⟨""⟩
instance : HasSizeof String :=
⟨String.length⟩
instance : HasAppend String :=
⟨String.append⟩
def str : String → Char → String := push
def pushn (s : String) (c : Char) (n : Nat) : String :=
n.repeat (fun s => s.push c) s
def isEmpty (s : String) : Bool :=
s.bsize == 0
def join (l : List String) : String :=
l.foldl (fun r s => r ++ s) ""
def singleton (c : Char) : String :=
"".push c
def intercalate (s : String) (ss : List String) : String :=
(List.intercalate s.toList (ss.map toList)).asString
structure Iterator :=
(s : String) (i : Pos)
def mkIterator (s : String) : Iterator :=
⟨s, 0⟩
namespace Iterator
def toString : Iterator → String
| ⟨s, _⟩ => s
def remainingBytes : Iterator → Nat
| ⟨s, i⟩ => s.bsize - i
def pos : Iterator → Pos
| ⟨s, i⟩ => i
def curr : Iterator → Char
| ⟨s, i⟩ => get s i
def next : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.next i⟩
def prev : Iterator → Iterator
| ⟨s, i⟩ => ⟨s, s.prev i⟩
def hasNext : Iterator → Bool
| ⟨s, i⟩ => i < utf8ByteSize s
def hasPrev : Iterator → Bool
| ⟨s, i⟩ => i > 0
def setCurr : Iterator → Char → Iterator
| ⟨s, i⟩, c => ⟨s.set i c, i⟩
def toEnd : Iterator → Iterator
| ⟨s, _⟩ => ⟨s, s.bsize⟩
def extract : Iterator → Iterator → String
| ⟨s₁, b⟩, ⟨s₂, e⟩ =>
if s₁ ≠ s₂ || b > e then ""
else s₁.extract b e
def forward : Iterator → Nat → Iterator
| it, 0 => it
| it, n+1 => forward it.next n
def remainingToString : Iterator → String
| ⟨s, i⟩ => s.extract i s.bsize
/- (isPrefixOfRemaining it₁ it₂) is `true` Iff `it₁.remainingToString` is a prefix
of `it₂.remainingToString`. -/
def isPrefixOfRemaining : Iterator → Iterator → Bool
| ⟨s₁, i₁⟩, ⟨s₂, i₂⟩ => s₁.extract i₁ s₁.bsize = s₂.extract i₂ (i₂ + (s₁.bsize - i₁))
def nextn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => nextn it.next i
def prevn : Iterator → Nat → Iterator
| it, 0 => it
| it, i+1 => prevn it.prev i
end Iterator
partial def offsetOfPosAux (s : String) (pos : Pos) : Pos → Nat → Nat
| i, offset =>
if i == pos || s.atEnd i then offset
else offsetOfPosAux (s.next i) (offset+1)
def offsetOfPos (s : String) (pos : Pos) : Nat :=
offsetOfPosAux s pos 0 0
@[specialize] partial def foldlAux {α : Type u} (f : α → Char → α) (s : String) (stopPos : Pos) : Pos → α → α
| i, a =>
if i == stopPos then a
else foldlAux (s.next i) (f a (s.get i))
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : String) : α :=
foldlAux f s s.bsize 0 a
@[specialize] partial def foldrAux {α : Type u} (f : Char → α → α) (a : α) (s : String) (stopPos : Pos) : Pos → α
| i =>
if i == stopPos then a
else f (s.get i) (foldrAux (s.next i))
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : String) : α :=
foldrAux f a s s.bsize 0
@[specialize] partial def anyAux (s : String) (stopPos : Pos) (p : Char → Bool) : Pos → Bool
| i =>
if i == stopPos then false
else if p (s.get i) then true
else anyAux (s.next i)
@[inline] def any (s : String) (p : Char → Bool) : Bool :=
anyAux s s.bsize p 0
@[inline] def all (s : String) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : String) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def mapAux (f : Char → Char) : Pos → String → String
| i, s =>
if s.atEnd i then s
else
let c := f (s.get i);
let s := s.set i c;
mapAux (s.next i) s
@[inline] def map (f : Char → Char) (s : String) : String :=
mapAux f 0 s
def toNat (s : String) : Nat :=
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
def isNat (s : String) : Bool :=
s.all $ fun c => c.isDigit
partial def isPrefixOfAux (p s : String) : Pos → Bool
| i =>
if p.atEnd i then true
else
let c₁ := p.get i;
let c₂ := s.get i;
c₁ == c₂ && isPrefixOfAux (s.next i)
/- Return true iff `p` is a prefix of `s` -/
def isPrefixOf (p : String) (s : String) : Bool :=
p.length ≤ s.length && isPrefixOfAux p s 0
end String
namespace Substring
@[inline] def toString : Substring → String
| ⟨s, b, e⟩ => s.extract b e
@[inline] def toIterator : Substring → String.Iterator
| ⟨s, b, _⟩ => ⟨s, b⟩
@[inline] def get : Substring → String.Pos → Char
| ⟨s, b, _⟩, p => s.get (b+p)
@[inline] def next : Substring → String.Pos → String.Pos
| ⟨s, b, e⟩, p =>
let p := s.next (b+p);
if p > e then e - b else p - b
@[inline] def prev : Substring → String.Pos → String.Pos
| ⟨s, b, _⟩, p =>
if p = b then p else s.prev (b+p) - b
@[inline] def front (s : Substring) : Char :=
s.get 0
@[inline] def posOf (s : Substring) (c : Char) : String.Pos :=
match s with
| ⟨s, b, e⟩ => (String.posOfAux s c e b) - b
@[inline] def drop : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if b + n ≥ e then "".toSubstring
else ⟨s, b+n, e⟩
@[inline] def dropRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
if e - n ≤ e then "".toSubstring
else ⟨s, b, e - n⟩
@[inline] def take : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let e := if b + n ≥ e then e else b + n;
⟨s, b, e⟩
@[inline] def takeRight : Substring → Nat → Substring
| ⟨s, b, e⟩, n =>
let b := if e - n ≤ b then b else e - n;
⟨s, b, e⟩
@[inline] def atEnd : Substring → String.Pos → Bool
| ⟨s, b, e⟩, p => b + p == e
@[inline] def extract : Substring → String.Pos → String.Pos → Substring
| ⟨s, b, _⟩, b', e' => if b' ≥ e' then ⟨"", 0, 1⟩ else ⟨s, b+b', b+e'⟩
partial def splitOnAux (s sep : String) (stopPos : String.Pos) : String.Pos → String.Pos → String.Pos → List Substring → List Substring
| b, i, j, r =>
if i == stopPos then
let r := if sep.atEnd j then "".toSubstring::{str := s, startPos := b, stopPos := i-j}::r else {str := s, startPos := b, stopPos := i}::r;
r.reverse
else if s.get i == sep.get j then
let i := s.next i;
let j := sep.next j;
if sep.atEnd j then splitOnAux i i 0 ({str := s, startPos := b, stopPos := i-j}::r)
else splitOnAux b i j r
else splitOnAux b (s.next i) 0 r
def splitOn (s : Substring) (sep : String := " ") : List Substring :=
if sep == "" then [s] else splitOnAux s.str sep s.stopPos s.startPos s.startPos 0 []
@[inline] def foldl {α : Type u} (f : α → Char → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldlAux f s e b a
@[inline] def foldr {α : Type u} (f : Char → α → α) (a : α) (s : Substring) : α :=
match s with
| ⟨s, b, e⟩ => String.foldrAux f a s e b
@[inline] def any (s : Substring) (p : Char → Bool) : Bool :=
match s with
| ⟨s, b, e⟩ => String.anyAux s e p b
@[inline] def all (s : Substring) (p : Char → Bool) : Bool :=
!s.any (fun c => !p c)
def contains (s : Substring) (c : Char) : Bool :=
s.any (fun a => a == c)
@[specialize] partial def takeWhileAux (s : String) (stopPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == stopPos then i
else if p (s.get i) then takeWhileAux (s.next i)
else i
@[inline] def takeWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeWhileAux s e p b;
⟨s, b, e⟩
@[inline] def dropWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeWhileAux s e p b;
⟨s, b, e⟩
@[specialize] partial def takeRightWhileAux (s : String) (begPos : String.Pos) (p : Char → Bool) : String.Pos → String.Pos
| i =>
if i == begPos then i
else
let i' := s.prev i;
let c := s.get i';
if !p c then i
else takeRightWhileAux i'
@[inline] def takeRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let b := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def dropRightWhile : Substring → (Char → Bool) → Substring
| ⟨s, b, e⟩, p =>
let e := takeRightWhileAux s b p e;
⟨s, b, e⟩
@[inline] def trimLeft (s : Substring) : Substring :=
s.dropWhile Char.isWhitespace
@[inline] def trimRight (s : Substring) : Substring :=
s.dropRightWhile Char.isWhitespace
@[inline] def trim : Substring → Substring
| ⟨s, b, e⟩ =>
let b := takeWhileAux s e Char.isWhitespace b;
let e := takeRightWhileAux s b Char.isWhitespace e;
⟨s, b, e⟩
def toNat (s : Substring) : Nat :=
s.foldl (fun n c => n*10 + (c.toNat - '0'.toNat)) 0
def isNat (s : Substring) : Bool :=
s.all $ fun c => c.isDigit
end Substring
namespace String
def drop (s : String) (n : Nat) : String :=
(s.toSubstring.drop n).toString
def dropRight (s : String) (n : Nat) : String :=
(s.toSubstring.dropRight n).toString
def take (s : String) (n : Nat) : String :=
(s.toSubstring.take n).toString
def takeRight (s : String) (n : Nat) : String :=
(s.toSubstring.takeRight n).toString
def takeWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.takeWhile p).toString
def dropWhile (s : String) (p : Char → Bool) : String :=
(s.toSubstring.dropWhile p).toString
def trimRight (s : String) : String :=
s.toSubstring.trimRight.toString
def trimLeft (s : String) : String :=
s.toSubstring.trimLeft.toString
def trim (s : String) : String :=
s.toSubstring.trim.toString
end String
protected def Char.toString (c : Char) : String :=
String.singleton c
|
e307c60cc09e8ce58eecc3fbcc1f5aa5d3c81d3c | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/order.lean | e0822efd52e253aa8b56abe04e367a81ed920641 | [] | 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 | 17,422 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.alias
import Mathlib.tactic.lint.default
import Mathlib.PostPort
universes u u_1
namespace Mathlib
/-!
# Lemmas about inequalities
This file contains some lemmas about `≤`/`≥`/`<`/`>`, and `cmp`.
* We simplify `a ≥ b` and `a > b` to `b ≤ a` and `b < a`, respectively. This way we can formulate
all lemmas using `≤`/`<` avoiding duplication.
* In some cases we introduce dot syntax aliases so that, e.g., from
`(hab : a ≤ b) (hbc : b ≤ c) (hbc' : b < c)` one can prove `hab.trans hbc : a ≤ c` and
`hab.trans_lt hbc' : a < c`.
-/
theorem has_le.le.trans {α : Type u} [preorder α] {a : α} {b : α} {c : α} : a ≤ b → b ≤ c → a ≤ c :=
le_trans
theorem has_le.le.trans_lt {α : Type u} [preorder α] {a : α} {b : α} {c : α} : a ≤ b → b < c → a < c :=
lt_of_le_of_lt
theorem has_le.le.antisymm {α : Type u} [partial_order α] {a : α} {b : α} : a ≤ b → b ≤ a → a = b :=
le_antisymm
theorem has_le.le.lt_of_ne {α : Type u} [partial_order α] {a : α} {b : α} : a ≤ b → a ≠ b → a < b :=
lt_of_le_of_ne
theorem has_le.le.lt_of_not_le {α : Type u} [preorder α] {a : α} {b : α} : a ≤ b → ¬b ≤ a → a < b :=
lt_of_le_not_le
theorem has_le.le.lt_or_eq {α : Type u} [partial_order α] {a : α} {b : α} : a ≤ b → a < b ∨ a = b :=
lt_or_eq_of_le
theorem has_lt.lt.le {α : Type u} [preorder α] {a : α} {b : α} : a < b → a ≤ b :=
le_of_lt
theorem has_lt.lt.trans {α : Type u} [preorder α] {a : α} {b : α} {c : α} : a < b → b < c → a < c :=
lt_trans
theorem has_lt.lt.trans_le {α : Type u} [preorder α] {a : α} {b : α} {c : α} : a < b → b ≤ c → a < c :=
lt_of_lt_of_le
theorem has_lt.lt.ne {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) : a ≠ b :=
ne_of_lt
theorem has_lt.lt.not_lt {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) : ¬b < a :=
lt_asymm
theorem eq.le {α : Type u} [preorder α] {a : α} {b : α} : a = b → a ≤ b :=
le_of_eq
/-- A version of `le_refl` where the argument is implicit -/
theorem le_rfl {α : Type u} [preorder α] {x : α} : x ≤ x :=
le_refl x
namespace eq
/--
If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`,
because `le` is used almost exclusively in mathlib.
-/
protected theorem ge {α : Type u} [preorder α] {x : α} {y : α} (h : x = y) : y ≤ x :=
le (Eq.symm h)
end eq
theorem eq.trans_le {α : Type u} [preorder α] {x : α} {y : α} {z : α} (h1 : x = y) (h2 : y ≤ z) : x ≤ z :=
has_le.le.trans (eq.le h1) h2
namespace has_le.le
protected theorem ge {α : Type u} [HasLessEq α] {x : α} {y : α} (h : x ≤ y) : y ≥ x :=
h
theorem trans_eq {α : Type u} [preorder α] {x : α} {y : α} {z : α} (h1 : x ≤ y) (h2 : y = z) : x ≤ z :=
trans h1 (eq.le h2)
theorem lt_iff_ne {α : Type u} [partial_order α] {x : α} {y : α} (h : x ≤ y) : x < y ↔ x ≠ y :=
{ mp := fun (h : x < y) => has_lt.lt.ne h, mpr := lt_of_ne h }
theorem le_iff_eq {α : Type u} [partial_order α] {x : α} {y : α} (h : x ≤ y) : y ≤ x ↔ y = x :=
{ mp := fun (h' : y ≤ x) => antisymm h' h, mpr := eq.le }
theorem lt_or_le {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b :=
or.imp id (fun (hc : a ≥ c) => le_trans hc h) (lt_or_ge a c)
theorem le_or_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b :=
or.imp id (fun (hc : a > c) => lt_of_lt_of_le hc h) (le_or_gt a c)
theorem le_or_le {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b :=
or.elim (le_or_lt h c) Or.inl fun (h : c < b) => Or.inr (le_of_lt h)
end has_le.le
namespace has_lt.lt
protected theorem gt {α : Type u} [HasLess α] {x : α} {y : α} (h : x < y) : y > x :=
h
protected theorem false {α : Type u} [preorder α] {x : α} : x < x → False :=
lt_irrefl x
theorem ne' {α : Type u} [preorder α] {x : α} {y : α} (h : x < y) : y ≠ x :=
ne.symm (ne h)
theorem lt_or_lt {α : Type u} [linear_order α] {x : α} {y : α} (h : x < y) (z : α) : x < z ∨ z < y :=
or.elim (lt_or_ge z y) Or.inr fun (hz : z ≥ y) => Or.inl (trans_le h hz)
end has_lt.lt
namespace ge
end ge
protected theorem ge.le {α : Type u} [HasLessEq α] {x : α} {y : α} (h : x ≥ y) : y ≤ x :=
h
namespace gt
end gt
protected theorem gt.lt {α : Type u} [HasLess α] {x : α} {y : α} (h : x > y) : y < x :=
h
theorem ge_of_eq {α : Type u} [preorder α] {a : α} {b : α} (h : a = b) : a ≥ b :=
eq.ge h
@[simp] theorem ge_iff_le {α : Type u} [preorder α] {a : α} {b : α} : a ≥ b ↔ b ≤ a :=
iff.rfl
@[simp] theorem gt_iff_lt {α : Type u} [preorder α] {a : α} {b : α} : a > b ↔ b < a :=
iff.rfl
theorem not_le_of_lt {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) : ¬b ≤ a :=
and.right (le_not_le_of_lt h)
theorem has_lt.lt.not_le {α : Type u} [preorder α] {a : α} {b : α} (h : a < b) : ¬b ≤ a :=
not_le_of_lt
theorem not_lt_of_le {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : ¬b < a :=
fun (ᾰ : b < a) => idRhs False (has_lt.lt.not_le ᾰ h)
theorem has_le.le.not_lt {α : Type u} [preorder α] {a : α} {b : α} (h : a ≤ b) : ¬b < a :=
not_lt_of_le
theorem le_iff_eq_or_lt {α : Type u} [partial_order α] {a : α} {b : α} : a ≤ b ↔ a = b ∨ a < b :=
iff.trans le_iff_lt_or_eq or.comm
theorem lt_iff_le_and_ne {α : Type u} [partial_order α] {a : α} {b : α} : a < b ↔ a ≤ b ∧ a ≠ b := sorry
theorem eq_iff_le_not_lt {α : Type u} [partial_order α] {a : α} {b : α} : a = b ↔ a ≤ b ∧ ¬a < b := sorry
theorem eq_or_lt_of_le {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≤ b) : a = b ∨ a < b :=
or.symm (has_le.le.lt_or_eq h)
theorem has_le.le.eq_or_lt {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≤ b) : a = b ∨ a < b :=
eq_or_lt_of_le
theorem ne.le_iff_lt {α : Type u} [partial_order α] {a : α} {b : α} (h : a ≠ b) : a ≤ b ↔ a < b :=
{ mp := fun (h' : a ≤ b) => lt_of_le_of_ne h' h, mpr := fun (h : a < b) => has_lt.lt.le h }
@[simp] theorem ne_iff_lt_iff_le {α : Type u} [partial_order α] {a : α} {b : α} : a ≠ b ↔ a < b ↔ a ≤ b :=
{ mp := fun (h : a ≠ b ↔ a < b) => classical.by_cases le_of_eq (le_of_lt ∘ iff.mp h),
mpr := fun (h : a ≤ b) => { mp := lt_of_le_of_ne h, mpr := ne_of_lt } }
theorem lt_of_not_ge' {α : Type u} [linear_order α] {a : α} {b : α} (h : ¬b ≤ a) : a < b :=
has_le.le.lt_of_not_le (or.resolve_right (le_total a b) h) h
theorem lt_iff_not_ge' {α : Type u} [linear_order α] {x : α} {y : α} : x < y ↔ ¬y ≤ x :=
{ mp := not_le_of_gt, mpr := lt_of_not_ge' }
theorem le_of_not_lt {α : Type u} [linear_order α] {a : α} {b : α} : ¬a < b → b ≤ a :=
iff.mp not_lt
theorem lt_or_le {α : Type u} [linear_order α] (a : α) (b : α) : a < b ∨ b ≤ a :=
lt_or_ge
theorem le_or_lt {α : Type u} [linear_order α] (a : α) (b : α) : a ≤ b ∨ b < a :=
le_or_gt
theorem ne.lt_or_lt {α : Type u} [linear_order α] {a : α} {b : α} (h : a ≠ b) : a < b ∨ b < a :=
lt_or_gt_of_ne h
theorem not_lt_iff_eq_or_lt {α : Type u} [linear_order α] {a : α} {b : α} : ¬a < b ↔ a = b ∨ b < a :=
iff.trans not_lt (iff.trans le_iff_eq_or_lt (or_congr eq_comm iff.rfl))
theorem exists_ge_of_linear {α : Type u} [linear_order α] (a : α) (b : α) : ∃ (c : α), a ≤ c ∧ b ≤ c := sorry
theorem lt_imp_lt_of_le_imp_le {α : Type u} {β : Type u_1} [linear_order α] [preorder β] {a : α} {b : α} {c : β} {d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a :=
lt_of_not_ge' fun (h' : a ≤ b) => has_le.le.not_lt (H h') h
theorem le_imp_le_of_lt_imp_lt {α : Type u} {β : Type u_1} [preorder α] [linear_order β] {a : α} {b : α} {c : β} {d : β} (H : d < c → b < a) (h : a ≤ b) : c ≤ d :=
le_of_not_gt fun (h' : c > d) => has_lt.lt.not_le (H h') h
theorem le_imp_le_iff_lt_imp_lt {α : Type u} {β : Type u_1} [linear_order α] [linear_order β] {a : α} {b : α} {c : β} {d : β} : a ≤ b → c ≤ d ↔ d < c → b < a :=
{ mp := lt_imp_lt_of_le_imp_le, mpr := le_imp_le_of_lt_imp_lt }
theorem lt_iff_lt_of_le_iff_le' {α : Type u} {β : Type u_1} [preorder α] [preorder β] {a : α} {b : α} {c : β} {d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c :=
iff.trans lt_iff_le_not_le (iff.trans (and_congr H' (not_congr H)) (iff.symm lt_iff_le_not_le))
theorem lt_iff_lt_of_le_iff_le {α : Type u} {β : Type u_1} [linear_order α] [linear_order β] {a : α} {b : α} {c : β} {d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c :=
iff.trans (iff.symm not_le) (iff.trans (not_congr H) not_le)
theorem le_iff_le_iff_lt_iff_lt {α : Type u} {β : Type u_1} [linear_order α] [linear_order β] {a : α} {b : α} {c : β} {d : β} : a ≤ b ↔ c ≤ d ↔ (b < a ↔ d < c) :=
{ mp := lt_iff_lt_of_le_iff_le,
mpr := fun (H : b < a ↔ d < c) => iff.trans (iff.symm not_lt) (iff.trans (not_congr H) not_lt) }
theorem eq_of_forall_le_iff {α : Type u} [partial_order α] {a : α} {b : α} (H : ∀ (c : α), c ≤ a ↔ c ≤ b) : a = b :=
le_antisymm (iff.mp (H a) (le_refl a)) (iff.mpr (H b) (le_refl b))
theorem le_of_forall_le {α : Type u} [preorder α] {a : α} {b : α} (H : ∀ (c : α), c ≤ a → c ≤ b) : a ≤ b :=
H a (le_refl a)
theorem le_of_forall_le' {α : Type u} [preorder α] {a : α} {b : α} (H : ∀ (c : α), a ≤ c → b ≤ c) : b ≤ a :=
H a (le_refl a)
theorem le_of_forall_lt {α : Type u} [linear_order α] {a : α} {b : α} (H : ∀ (c : α), c < a → c < b) : a ≤ b :=
le_of_not_lt fun (h : b < a) => lt_irrefl b (H b h)
theorem forall_lt_iff_le {α : Type u} [linear_order α] {a : α} {b : α} : (∀ {c : α}, c < a → c < b) ↔ a ≤ b :=
{ mp := le_of_forall_lt, mpr := fun (h : a ≤ b) (c : α) (hca : c < a) => lt_of_lt_of_le hca h }
theorem le_of_forall_lt' {α : Type u} [linear_order α] {a : α} {b : α} (H : ∀ (c : α), a < c → b < c) : b ≤ a :=
le_of_not_lt fun (h : a < b) => lt_irrefl b (H b h)
theorem forall_lt_iff_le' {α : Type u} [linear_order α] {a : α} {b : α} : (∀ {c : α}, a < c → b < c) ↔ b ≤ a :=
{ mp := le_of_forall_lt', mpr := fun (h : b ≤ a) (c : α) (hac : a < c) => lt_of_le_of_lt h hac }
theorem eq_of_forall_ge_iff {α : Type u} [partial_order α] {a : α} {b : α} (H : ∀ (c : α), a ≤ c ↔ b ≤ c) : a = b :=
le_antisymm (iff.mpr (H b) (le_refl b)) (iff.mp (H a) (le_refl a))
/-- monotonicity of `≤` with respect to `→` -/
theorem le_implies_le_of_le_of_le {α : Type u} {a : α} {b : α} {c : α} {d : α} [preorder α] (h₀ : c ≤ a) (h₁ : b ≤ d) : a ≤ b → c ≤ d :=
fun (h₂ : a ≤ b) => le_trans (le_trans h₀ h₂) h₁
namespace decidable
-- See Note [decidable namespace]
theorem le_imp_le_iff_lt_imp_lt {α : Type u} {β : Type u_1} [linear_order α] [linear_order β] {a : α} {b : α} {c : β} {d : β} : a ≤ b → c ≤ d ↔ d < c → b < a :=
{ mp := lt_imp_lt_of_le_imp_le, mpr := le_imp_le_of_lt_imp_lt }
-- See Note [decidable namespace]
theorem le_iff_le_iff_lt_iff_lt {α : Type u} {β : Type u_1} [linear_order α] [linear_order β] {a : α} {b : α} {c : β} {d : β} : a ≤ b ↔ c ≤ d ↔ (b < a ↔ d < c) :=
{ mp := lt_iff_lt_of_le_iff_le,
mpr := fun (H : b < a ↔ d < c) => iff.trans (iff.symm not_lt) (iff.trans (not_congr H) not_lt) }
end decidable
/-- Like `cmp`, but uses a `≤` on the type instead of `<`. Given two elements
`x` and `y`, returns a three-way comparison result `ordering`. -/
def cmp_le {α : Type u_1} [HasLessEq α] [DecidableRel LessEq] (x : α) (y : α) : ordering :=
ite (x ≤ y) (ite (y ≤ x) ordering.eq ordering.lt) ordering.gt
theorem cmp_le_swap {α : Type u_1} [HasLessEq α] [is_total α LessEq] [DecidableRel LessEq] (x : α) (y : α) : ordering.swap (cmp_le x y) = cmp_le y x := sorry
theorem cmp_le_eq_cmp {α : Type u_1} [preorder α] [is_total α LessEq] [DecidableRel LessEq] [DecidableRel Less] (x : α) (y : α) : cmp_le x y = cmp x y := sorry
namespace ordering
/-- `compares o a b` means that `a` and `b` have the ordering relation
`o` between them, assuming that the relation `a < b` is defined -/
@[simp] def compares {α : Type u} [HasLess α] : ordering → α → α → Prop :=
sorry
theorem compares_swap {α : Type u} [HasLess α] {a : α} {b : α} {o : ordering} : compares (swap o) a b ↔ compares o b a :=
ordering.cases_on o iff.rfl eq_comm iff.rfl
theorem compares.of_swap {α : Type u} [HasLess α] {a : α} {b : α} {o : ordering} : compares (swap o) a b → compares o b a :=
iff.mp compares_swap
theorem swap_eq_iff_eq_swap {o : ordering} {o' : ordering} : swap o = o' ↔ o = swap o' := sorry
theorem compares.eq_lt {α : Type u} [preorder α] {o : ordering} {a : α} {b : α} : compares o a b → (o = lt ↔ a < b) := sorry
theorem compares.ne_lt {α : Type u} [preorder α] {o : ordering} {a : α} {b : α} : compares o a b → (o ≠ lt ↔ b ≤ a) := sorry
theorem compares.eq_eq {α : Type u} [preorder α] {o : ordering} {a : α} {b : α} : compares o a b → (o = eq ↔ a = b) := sorry
theorem compares.eq_gt {α : Type u} [preorder α] {o : ordering} {a : α} {b : α} (h : compares o a b) : o = gt ↔ b < a :=
iff.trans (iff.symm swap_eq_iff_eq_swap) (compares.eq_lt (compares.swap h))
theorem compares.ne_gt {α : Type u} [preorder α] {o : ordering} {a : α} {b : α} (h : compares o a b) : o ≠ gt ↔ a ≤ b :=
iff.trans (not_congr (iff.symm swap_eq_iff_eq_swap)) (compares.ne_lt (compares.swap h))
theorem compares.le_total {α : Type u} [preorder α] {a : α} {b : α} {o : ordering} : compares o a b → a ≤ b ∨ b ≤ a := sorry
theorem compares.le_antisymm {α : Type u} [preorder α] {a : α} {b : α} {o : ordering} : compares o a b → a ≤ b → b ≤ a → a = b := sorry
theorem compares.inj {α : Type u} [preorder α] {o₁ : ordering} {o₂ : ordering} {a : α} {b : α} : compares o₁ a b → compares o₂ a b → o₁ = o₂ := sorry
theorem compares_iff_of_compares_impl {α : Type u} {β : Type u_1} [linear_order α] [preorder β] {a : α} {b : α} {a' : β} {b' : β} (h : ∀ {o : ordering}, compares o a b → compares o a' b') (o : ordering) : compares o a b ↔ compares o a' b' := sorry
theorem swap_or_else (o₁ : ordering) (o₂ : ordering) : swap (or_else o₁ o₂) = or_else (swap o₁) (swap o₂) :=
ordering.cases_on o₁ (Eq.refl (swap (or_else lt o₂))) (Eq.refl (swap (or_else eq o₂))) (Eq.refl (swap (or_else gt o₂)))
theorem or_else_eq_lt (o₁ : ordering) (o₂ : ordering) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ o₁ = eq ∧ o₂ = lt :=
ordering.cases_on o₁ (ordering.cases_on o₂ (of_as_true trivial) (of_as_true trivial) (of_as_true trivial))
(ordering.cases_on o₂ (of_as_true trivial) (of_as_true trivial) (of_as_true trivial))
(ordering.cases_on o₂ (of_as_true trivial) (of_as_true trivial) (of_as_true trivial))
end ordering
theorem cmp_compares {α : Type u} [linear_order α] (a : α) (b : α) : ordering.compares (cmp a b) a b := sorry
theorem cmp_swap {α : Type u} [preorder α] [DecidableRel Less] (a : α) (b : α) : ordering.swap (cmp a b) = cmp b a := sorry
/-- Generate a linear order structure from a preorder and `cmp` function. -/
def linear_order_of_compares {α : Type u} [preorder α] (cmp : α → α → ordering) (h : ∀ (a b : α), ordering.compares (cmp a b) a b) : linear_order α :=
linear_order.mk preorder.le preorder.lt preorder.le_refl preorder.le_trans sorry sorry
(fun (a b : α) => decidable_of_iff (cmp a b ≠ ordering.gt) sorry)
(fun (a b : α) => decidable_of_iff (cmp a b = ordering.eq) sorry)
fun (a b : α) => decidable_of_iff (cmp a b = ordering.lt) sorry
@[simp] theorem cmp_eq_lt_iff {α : Type u} [linear_order α] (x : α) (y : α) : cmp x y = ordering.lt ↔ x < y :=
ordering.compares.eq_lt (cmp_compares x y)
@[simp] theorem cmp_eq_eq_iff {α : Type u} [linear_order α] (x : α) (y : α) : cmp x y = ordering.eq ↔ x = y :=
ordering.compares.eq_eq (cmp_compares x y)
@[simp] theorem cmp_eq_gt_iff {α : Type u} [linear_order α] (x : α) (y : α) : cmp x y = ordering.gt ↔ y < x :=
ordering.compares.eq_gt (cmp_compares x y)
@[simp] theorem cmp_self_eq_eq {α : Type u} [linear_order α] (x : α) : cmp x x = ordering.eq :=
eq.mpr (id (Eq._oldrec (Eq.refl (cmp x x = ordering.eq)) (propext (cmp_eq_eq_iff x x)))) (Eq.refl x)
theorem cmp_eq_cmp_symm {α : Type u} [linear_order α] {x : α} {y : α} {β : Type u_1} [linear_order β] {x' : β} {y' : β} : cmp x y = cmp x' y' ↔ cmp y x = cmp y' x' := sorry
theorem lt_iff_lt_of_cmp_eq_cmp {α : Type u} [linear_order α] {x : α} {y : α} {β : Type u_1} [linear_order β] {x' : β} {y' : β} (h : cmp x y = cmp x' y') : x < y ↔ x' < y' := sorry
theorem le_iff_le_of_cmp_eq_cmp {α : Type u} [linear_order α] {x : α} {y : α} {β : Type u_1} [linear_order β] {x' : β} {y' : β} (h : cmp x y = cmp x' y') : x ≤ y ↔ x' ≤ y' := sorry
|
df5e7156e74b09ac6b1386df3da6a2dfa9547bcd | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/measure_theory/integral/interval_integral.lean | 24c0a6899878bf03e7181ab11f0203a0414d75a1 | [
"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 | 130,884 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov, Patrick Massot, Sébastien Gouëzel
-/
import analysis.normed_space.dual
import data.set.intervals.disjoint
import measure_theory.measure.haar_lebesgue
import analysis.calculus.extend_deriv
import measure_theory.integral.set_integral
import measure_theory.integral.vitali_caratheodory
/-!
# Integral over an interval
In this file we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ` if `a ≤ b` and
`-∫ x in Ioc b a, f x ∂μ` if `b ≤ a`. We prove a few simple properties and several versions of the
[fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus).
Recall that its first version states that the function `(u, v) ↦ ∫ x in u..v, f x` has derivative
`(δu, δv) ↦ δv • f b - δu • f a` at `(a, b)` provided that `f` is continuous at `a` and `b`,
and its second version states that, if `f` has an integrable derivative on `[a, b]`, then
`∫ x in a..b, f' x = f b - f a`.
## Main statements
### FTC-1 for Lebesgue measure
We prove several versions of FTC-1, all in the `interval_integral` namespace. Many of them follow
the naming scheme `integral_has(_strict?)_(f?)deriv(_within?)_at(_of_tendsto_ae?)(_right|_left?)`.
They formulate FTC in terms of `has(_strict?)_(f?)deriv(_within?)_at`.
Let us explain the meaning of each part of the name:
* `_strict` means that the theorem is about strict differentiability;
* `f` means that the theorem is about differentiability in both endpoints; incompatible with
`_right|_left`;
* `_within` means that the theorem is about one-sided derivatives, see below for details;
* `_of_tendsto_ae` means that instead of continuity the theorem assumes that `f` has a finite limit
almost surely as `x` tends to `a` and/or `b`;
* `_right` or `_left` mean that the theorem is about differentiability in the right (resp., left)
endpoint.
We also reformulate these theorems in terms of `(f?)deriv(_within?)`. These theorems are named
`(f?)deriv(_within?)_integral(_of_tendsto_ae?)(_right|_left?)` with the same meaning of parts of the
name.
### One-sided derivatives
Theorem `integral_has_fderiv_within_at_of_tendsto_ae` states that `(u, v) ↦ ∫ x in u..v, f x` has a
derivative `(δu, δv) ↦ δv • cb - δu • ca` within the set `s × t` at `(a, b)` provided that `f` tends
to `ca` (resp., `cb`) almost surely at `la` (resp., `lb`), where possible values of `s`, `t`, and
corresponding filters `la`, `lb` are given in the following table.
| `s` | `la` | `t` | `lb` |
| ------- | ---- | --- | ---- |
| `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` |
| `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` |
| `{a}` | `⊥` | `{b}` | `⊥` |
| `univ` | `𝓝 a` | `univ` | `𝓝 b` |
We use a typeclass `FTC_filter` to make Lean automatically find `la`/`lb` based on `s`/`t`. This way
we can formulate one theorem instead of `16` (or `8` if we leave only non-trivial ones not covered
by `integral_has_deriv_within_at_of_tendsto_ae_(left|right)` and
`integral_has_fderiv_at_of_tendsto_ae`). Similarly,
`integral_has_deriv_within_at_of_tendsto_ae_right` works for both one-sided derivatives using the
same typeclass to find an appropriate filter.
### FTC for a locally finite measure
Before proving FTC for the Lebesgue measure, we prove a few statements that can be seen as FTC for
any measure. The most general of them,
`measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae`, states the following. Let `(la, la')`
be an `FTC_filter` pair of filters around `a` (i.e., `FTC_filter a la la'`) and let `(lb, lb')` be
an `FTC_filter` pair of filters around `b`. If `f` has finite limits `ca` and `cb` almost surely at
`la'` and `lb'`, respectively, then
`∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ +
o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)` as `ua` and `va` tend to `la` while
`ub` and `vb` tend to `lb`.
### FTC-2 and corollaries
We use FTC-1 to prove several versions of FTC-2 for the Lebesgue measure, using a similar naming
scheme as for the versions of FTC-1. They include:
* `interval_integral.integral_eq_sub_of_has_deriv_right_of_le` - most general version, for functions
with a right derivative
* `interval_integral.integral_eq_sub_of_has_deriv_at'` - version for functions with a derivative on
an open set
* `interval_integral.integral_deriv_eq_sub'` - version that is easiest to use when computing the
integral of a specific function
We then derive additional integration techniques from FTC-2:
* `interval_integral.integral_mul_deriv_eq_deriv_mul` - integration by parts
* `interval_integral.integral_comp_mul_deriv''` - integration by substitution
Many applications of these theorems can be found in the file `analysis.special_functions.integrals`.
Note that the assumptions of FTC-2 are formulated in the form that `f'` is integrable. To use it in
a context with the stronger assumption that `f'` is continuous, one can use
`continuous_on.interval_integrable` or `continuous_on.integrable_on_Icc` or
`continuous_on.integrable_on_interval`.
## Implementation notes
### Avoiding `if`, `min`, and `max`
In order to avoid `if`s in the definition, we define `interval_integrable f μ a b` as
`integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ`. For any `a`, `b` one of these
intervals is empty and the other coincides with `set.interval_oc a b = set.Ioc (min a b) (max a b)`.
Similarly, we define `∫ x in a..b, f x ∂μ` to be `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`.
Again, for any `a`, `b` one of these integrals is zero, and the other gives the expected result.
This way some properties can be translated from integrals over sets without dealing with
the cases `a ≤ b` and `b ≤ a` separately.
### Choice of the interval
We use integral over `set.interval_oc a b = set.Ioc (min a b) (max a b)` instead of one of the other
three possible intervals with the same endpoints for two reasons:
* this way `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ` holds whenever
`f` is integrable on each interval; in particular, it works even if the measure `μ` has an atom
at `b`; this rules out `set.Ioo` and `set.Icc` intervals;
* with this definition for a probability measure `μ`, the integral `∫ x in a..b, 1 ∂μ` equals
the difference $F_μ(b)-F_μ(a)$, where $F_μ(a)=μ(-∞, a]$ is the
[cumulative distribution function](https://en.wikipedia.org/wiki/Cumulative_distribution_function)
of `μ`.
### `FTC_filter` class
As explained above, many theorems in this file rely on the typeclass
`FTC_filter (a : α) (l l' : filter α)` to avoid code duplication. This typeclass combines four
assumptions:
- `pure a ≤ l`;
- `l' ≤ 𝓝 a`;
- `l'` has a basis of measurable sets;
- if `u n` and `v n` tend to `l`, then for any `s ∈ l'`, `Ioc (u n) (v n)` is eventually included
in `s`.
This typeclass has the following “real” instances: `(a, pure a, ⊥)`, `(a, 𝓝[≥] a, 𝓝[>] a)`,
`(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`.
Furthermore, we have the following instances that are equal to the previously mentioned instances:
`(a, 𝓝[{a}] a, ⊥)` and `(a, 𝓝[univ] a, 𝓝[univ] a)`.
While the difference between `Ici a` and `Ioi a` doesn't matter for theorems about Lebesgue measure,
it becomes important in the versions of FTC about any locally finite measure if this measure has an
atom at one of the endpoints.
### Combining one-sided and two-sided derivatives
There are some `FTC_filter` instances where the fact that it is one-sided or
two-sided depends on the point, namely `(x, 𝓝[Icc a b] x, 𝓝[Icc a b] x)`
(resp. `(x, 𝓝[[a, b]] x, 𝓝[[a, b]] x)`, where `[a, b] = set.interval a b`),
with `x ∈ Icc a b` (resp. `x ∈ [a, b]`).
This results in a two-sided derivatives for `x ∈ Ioo a b` and one-sided derivatives for
`x ∈ {a, b}`. Other instances could be added when needed (in that case, one also needs to add
instances for `filter.is_measurably_generated` and `filter.tendsto_Ixx_class`).
## Tags
integral, fundamental theorem of calculus, FTC-1, FTC-2, change of variables in integrals
-/
noncomputable theory
open topological_space (second_countable_topology)
open measure_theory set classical filter function
open_locale classical topological_space filter ennreal big_operators interval
variables {α β 𝕜 E F : Type*} [linear_order α] [measurable_space α]
[measurable_space E] [normed_group E]
/-!
### Almost everywhere on an interval
-/
section
variables {μ : measure α} {a b : α} {P : α → Prop}
lemma ae_interval_oc_iff :
(∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔ (∀ᵐ x ∂μ, x ∈ Ioc a b → P x) ∧ (∀ᵐ x ∂μ, x ∈ Ioc b a → P x) :=
by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] }
lemma ae_measurable_interval_oc_iff {μ : measure α} {β : Type*} [measurable_space β] {f : α → β} :
(ae_measurable f $ μ.restrict $ Ι a b) ↔
(ae_measurable f $ μ.restrict $ Ioc a b) ∧ (ae_measurable f $ μ.restrict $ Ioc b a) :=
by { dsimp [interval_oc], cases le_total a b with hab hab ; simp [hab] }
variables [topological_space α] [opens_measurable_space α] [order_closed_topology α]
lemma ae_interval_oc_iff' : (∀ᵐ x ∂μ, x ∈ Ι a b → P x) ↔
(∀ᵐ x ∂ (μ.restrict $ Ioc a b), P x) ∧ (∀ᵐ x ∂ (μ.restrict $ Ioc b a), P x) :=
begin
simp_rw ae_interval_oc_iff,
rw [ae_restrict_eq, eventually_inf_principal, ae_restrict_eq, eventually_inf_principal] ;
exact measurable_set_Ioc
end
end
/-!
### Integrability at an interval
-/
/-- A function `f` is called *interval integrable* with respect to a measure `μ` on an unordered
interval `a..b` if it is integrable on both intervals `(a, b]` and `(b, a]`. One of these
intervals is always empty, so this property is equivalent to `f` being integrable on
`(min a b, max a b]`. -/
def interval_integrable (f : α → E) (μ : measure α) (a b : α) :=
integrable_on f (Ioc a b) μ ∧ integrable_on f (Ioc b a) μ
/-- A function is interval integrable with respect to a given measure `μ` on `interval a b` if and
only if it is integrable on `interval_oc a b` with respect to `μ`. This is an equivalent
defintion of `interval_integrable`. -/
lemma interval_integrable_iff {f : α → E} {a b : α} {μ : measure α} :
interval_integrable f μ a b ↔ integrable_on f (Ι a b) μ :=
by cases le_total a b; simp [h, interval_integrable, interval_oc]
/-- If a function is interval integrable with respect to a given measure `μ` on `interval a b` then
it is integrable on `interval_oc a b` with respect to `μ`. -/
lemma interval_integrable.def {f : α → E} {a b : α} {μ : measure α}
(h : interval_integrable f μ a b) :
integrable_on f (Ι a b) μ :=
interval_integrable_iff.mp h
lemma interval_integrable_iff_integrable_Ioc_of_le
{f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} :
interval_integrable f μ a b ↔ integrable_on f (Ioc a b) μ :=
by rw [interval_integrable_iff, interval_oc_of_le hab]
/-- If a function is integrable with respect to a given measure `μ` then it is interval integrable
with respect to `μ` on `interval a b`. -/
lemma measure_theory.integrable.interval_integrable {f : α → E} {a b : α} {μ : measure α}
(hf : integrable f μ) :
interval_integrable f μ a b :=
⟨hf.integrable_on, hf.integrable_on⟩
lemma measure_theory.integrable_on.interval_integrable {f : α → E} {a b : α} {μ : measure α}
(hf : integrable_on f (interval a b) μ) :
interval_integrable f μ a b :=
⟨measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval),
measure_theory.integrable_on.mono_set hf (Ioc_subset_Icc_self.trans Icc_subset_interval')⟩
lemma interval_integrable_const_iff {a b : α} {μ : measure α} {c : E} :
interval_integrable (λ _, c) μ a b ↔ c = 0 ∨ μ (Ι a b) < ∞ :=
by simp only [interval_integrable_iff, integrable_on_const]
@[simp] lemma interval_integrable_const [topological_space α] [compact_Icc_space α]
{μ : measure α} [is_locally_finite_measure μ] {a b : α} {c : E} :
interval_integrable (λ _, c) μ a b :=
interval_integrable_const_iff.2 $ or.inr measure_Ioc_lt_top
namespace interval_integrable
section
variables {f : α → E} {a b c d : α} {μ ν : measure α}
@[symm] lemma symm (h : interval_integrable f μ a b) : interval_integrable f μ b a :=
h.symm
@[refl] lemma refl : interval_integrable f μ a a :=
by split; simp
@[trans] lemma trans (hab : interval_integrable f μ a b) (hbc : interval_integrable f μ b c) :
interval_integrable f μ a c :=
⟨(hab.1.union hbc.1).mono_set Ioc_subset_Ioc_union_Ioc,
(hbc.2.union hab.2).mono_set Ioc_subset_Ioc_union_Ioc⟩
lemma trans_iterate {a : ℕ → α} {n : ℕ} (hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) :
interval_integrable f μ (a 0) (a n) :=
begin
induction n with n hn,
{ simp },
{ exact (hn (λ k hk, hint k (hk.trans n.lt_succ_self))).trans (hint n n.lt_succ_self) }
end
lemma neg [borel_space E] (h : interval_integrable f μ a b) : interval_integrable (-f) μ a b :=
⟨h.1.neg, h.2.neg⟩
lemma norm [opens_measurable_space E] (h : interval_integrable f μ a b) :
interval_integrable (λ x, ∥f x∥) μ a b :=
⟨h.1.norm, h.2.norm⟩
lemma abs {f : α → ℝ} (h : interval_integrable f μ a b) :
interval_integrable (λ x, |f x|) μ a b :=
h.norm
lemma mono
(hf : interval_integrable f ν a b) (h1 : interval c d ⊆ interval a b) (h2 : μ ≤ ν) :
interval_integrable f μ c d :=
let ⟨h1₁, h1₂⟩ := interval_subset_interval_iff_le.mp h1 in
interval_integrable_iff.mpr $ hf.def.mono (Ioc_subset_Ioc h1₁ h1₂) h2
lemma mono_set
(hf : interval_integrable f μ a b) (h : interval c d ⊆ interval a b) :
interval_integrable f μ c d :=
hf.mono h rfl.le
lemma mono_measure
(hf : interval_integrable f ν a b) (h : μ ≤ ν) :
interval_integrable f μ a b :=
hf.mono rfl.subset h
lemma mono_set_ae
(hf : interval_integrable f μ a b) (h : Ι c d ≤ᵐ[μ] Ι a b) :
interval_integrable f μ c d :=
interval_integrable_iff.mpr $ hf.def.mono_set_ae h
lemma mono_fun {F : Type*} [normed_group F] [measurable_space F] {g : α → F}
(hf : interval_integrable f μ a b) (hgm : ae_measurable g (μ.restrict (Ι a b)))
(hle : (λ x, ∥g x∥) ≤ᵐ[μ.restrict (Ι a b)] (λ x, ∥f x∥)) : interval_integrable g μ a b :=
interval_integrable_iff.2 $ hf.def.integrable.mono hgm hle
lemma mono_fun' {g : α → ℝ} (hg : interval_integrable g μ a b)
(hfm : ae_measurable f (μ.restrict (Ι a b)))
(hle : (λ x, ∥f x∥) ≤ᵐ[μ.restrict (Ι a b)] g) : interval_integrable f μ a b :=
interval_integrable_iff.2 $ hg.def.integrable.mono' hfm hle
protected lemma ae_measurable (h : interval_integrable f μ a b) :
ae_measurable f (μ.restrict (Ioc a b)):=
h.1.ae_measurable
protected lemma ae_measurable' (h : interval_integrable f μ a b) :
ae_measurable f (μ.restrict (Ioc b a)):=
h.2.ae_measurable
end
variables [borel_space E] {f g : α → E} {a b : α} {μ : measure α}
lemma smul [normed_field 𝕜] [normed_space 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜]
{f : α → E} {a b : α} {μ : measure α} (h : interval_integrable f μ a b) (r : 𝕜) :
interval_integrable (r • f) μ a b :=
⟨h.1.smul r, h.2.smul r⟩
@[simp] lemma add [second_countable_topology E] (hf : interval_integrable f μ a b)
(hg : interval_integrable g μ a b) : interval_integrable (λ x, f x + g x) μ a b :=
⟨hf.1.add hg.1, hf.2.add hg.2⟩
@[simp] lemma sub [second_countable_topology E] (hf : interval_integrable f μ a b)
(hg : interval_integrable g μ a b) : interval_integrable (λ x, f x - g x) μ a b :=
⟨hf.1.sub hg.1, hf.2.sub hg.2⟩
lemma mul_continuous_on {α : Type*} [conditionally_complete_linear_order α] [measurable_space α]
[topological_space α] [order_topology α] [opens_measurable_space α]
{μ : measure α} {a b : α} {f g : α → ℝ}
(hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) :
interval_integrable (λ x, f x * g x) μ a b :=
begin
rw interval_integrable_iff at hf ⊢,
exact hf.mul_continuous_on_of_subset hg measurable_set_Ioc is_compact_interval Ioc_subset_Icc_self
end
lemma continuous_on_mul {α : Type*} [conditionally_complete_linear_order α] [measurable_space α]
[topological_space α] [order_topology α] [opens_measurable_space α]
{μ : measure α} {a b : α} {f g : α → ℝ}
(hf : interval_integrable f μ a b) (hg : continuous_on g (interval a b)) :
interval_integrable (λ x, g x * f x) μ a b :=
by simpa [mul_comm] using hf.mul_continuous_on hg
end interval_integrable
section
variables {μ : measure ℝ} [is_locally_finite_measure μ]
lemma continuous_on.interval_integrable [borel_space E] {u : ℝ → E} {a b : ℝ}
(hu : continuous_on u (interval a b)) : interval_integrable u μ a b :=
(continuous_on.integrable_on_Icc hu).interval_integrable
lemma continuous_on.interval_integrable_of_Icc [borel_space E] {u : ℝ → E} {a b : ℝ} (h : a ≤ b)
(hu : continuous_on u (Icc a b)) : interval_integrable u μ a b :=
continuous_on.interval_integrable ((interval_of_le h).symm ▸ hu)
/-- A continuous function on `ℝ` is `interval_integrable` with respect to any locally finite measure
`ν` on ℝ. -/
lemma continuous.interval_integrable [borel_space E] {u : ℝ → E} (hu : continuous u) (a b : ℝ) :
interval_integrable u μ a b :=
hu.continuous_on.interval_integrable
end
section
variables {ι : Type*} [topological_space ι] [conditionally_complete_linear_order ι]
[order_topology ι] [measurable_space ι] [borel_space ι] {μ : measure ι}
[is_locally_finite_measure μ] [conditionally_complete_linear_order E] [order_topology E]
[second_countable_topology E] [borel_space E]
lemma monotone_on.interval_integrable {u : ι → E} {a b : ι} (hu : monotone_on u (interval a b)) :
interval_integrable u μ a b :=
begin
rw interval_integrable_iff,
exact (monotone_on.integrable_on_compact is_compact_interval hu).mono_set Ioc_subset_Icc_self,
end
lemma antitone_on.interval_integrable {u : ι → E} {a b : ι} (hu : antitone_on u (interval a b)) :
interval_integrable u μ a b :=
@monotone_on.interval_integrable (order_dual E) _ ‹_› ι _ _ _ _ _ _ _ _ _ ‹_› ‹_› u a b hu
lemma monotone.interval_integrable {u : ι → E} {a b : ι} (hu : monotone u) :
interval_integrable u μ a b :=
(hu.monotone_on _).interval_integrable
lemma antitone.interval_integrable {u : ι → E} {a b : ι} (hu :antitone u) :
interval_integrable u μ a b :=
(hu.antitone_on _).interval_integrable
end
/-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'`
eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`.
Suppose that `f : α → E` has a finite limit at `l' ⊓ μ.ae`. Then `f` is interval integrable on
`u..v` provided that both `u` and `v` tend to `l`.
Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so
`apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and
`tendsto_Ixx_class Ioc ?m_1 l'`. -/
lemma filter.tendsto.eventually_interval_integrable_ae {f : α → E} {μ : measure α}
{l l' : filter α} (hfm : measurable_at_filter f l' μ)
[tendsto_Ixx_class Ioc l l'] [is_measurably_generated l']
(hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
{u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) :
∀ᶠ t in lt, interval_integrable f μ (u t) (v t) :=
have _ := (hf.integrable_at_filter_ae hfm hμ).eventually,
((hu.Ioc hv).eventually this).and $ (hv.Ioc hu).eventually this
/-- Let `l'` be a measurably generated filter; let `l` be a of filter such that each `s ∈ l'`
eventually includes `Ioc u v` as both `u` and `v` tend to `l`. Let `μ` be a measure finite at `l'`.
Suppose that `f : α → E` has a finite limit at `l`. Then `f` is interval integrable on `u..v`
provided that both `u` and `v` tend to `l`.
Typeclass instances allow Lean to find `l'` based on `l` but not vice versa, so
`apply tendsto.eventually_interval_integrable_ae` will generate goals `filter α` and
`tendsto_Ixx_class Ioc ?m_1 l'`. -/
lemma filter.tendsto.eventually_interval_integrable {f : α → E} {μ : measure α}
{l l' : filter α} (hfm : measurable_at_filter f l' μ)
[tendsto_Ixx_class Ioc l l'] [is_measurably_generated l']
(hμ : μ.finite_at_filter l') {c : E} (hf : tendsto f l' (𝓝 c))
{u v : β → α} {lt : filter β} (hu : tendsto u lt l) (hv : tendsto v lt l) :
∀ᶠ t in lt, interval_integrable f μ (u t) (v t) :=
(hf.mono_left inf_le_left).eventually_interval_integrable_ae hfm hμ hu hv
/-!
### Interval integral: definition and basic properties
In this section we define `∫ x in a..b, f x ∂μ` as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`
and prove some basic properties.
-/
variables [second_countable_topology E] [complete_space E] [normed_space ℝ E]
[borel_space E]
/-- The interval integral `∫ x in a..b, f x ∂μ` is defined
as `∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ`. If `a ≤ b`, then it equals
`∫ x in Ioc a b, f x ∂μ`, otherwise it equals `-∫ x in Ioc b a, f x ∂μ`. -/
def interval_integral (f : α → E) (a b : α) (μ : measure α) :=
∫ x in Ioc a b, f x ∂μ - ∫ x in Ioc b a, f x ∂μ
notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, f) ` ∂` μ:70 := interval_integral r a b μ
notation `∫` binders ` in ` a `..` b `, ` r:(scoped:60 f, interval_integral f a b volume) := r
namespace interval_integral
section basic
variables {a b : α} {f g : α → E} {μ : measure α}
@[simp] lemma integral_zero : ∫ x in a..b, (0 : E) ∂μ = 0 :=
by simp [interval_integral]
lemma integral_of_le (h : a ≤ b) : ∫ x in a..b, f x ∂μ = ∫ x in Ioc a b, f x ∂μ :=
by simp [interval_integral, h]
@[simp] lemma integral_same : ∫ x in a..a, f x ∂μ = 0 :=
sub_self _
lemma integral_symm (a b) : ∫ x in b..a, f x ∂μ = -∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, neg_sub]
lemma integral_of_ge (h : b ≤ a) : ∫ x in a..b, f x ∂μ = -∫ x in Ioc b a, f x ∂μ :=
by simp only [integral_symm b, integral_of_le h]
lemma interval_integral_eq_integral_interval_oc (f : α → E) (a b : α) (μ : measure α) :
∫ x in a..b, f x ∂μ = (if a ≤ b then 1 else -1 : ℝ) • ∫ x in Ι a b, f x ∂μ :=
begin
split_ifs with h,
{ simp only [integral_of_le h, interval_oc_of_le h, one_smul] },
{ simp only [integral_of_ge (not_le.1 h).le, interval_oc_of_lt (not_le.1 h), neg_one_smul] }
end
lemma integral_cases (f : α → E) (a b) :
∫ x in a..b, f x ∂μ ∈ ({∫ x in Ι a b, f x ∂μ, -∫ x in Ι a b, f x ∂μ} : set E) :=
by { rw interval_integral_eq_integral_interval_oc, split_ifs; simp }
lemma integral_undef (h : ¬ interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 :=
by cases le_total a b with hab hab;
simp only [integral_of_le, integral_of_ge, hab, neg_eq_zero];
refine integral_undef (not_imp_not.mpr integrable.integrable_on' _);
simpa [hab] using not_and_distrib.mp h
lemma integral_non_ae_measurable
(hf : ¬ ae_measurable f (μ.restrict (Ι a b))) :
∫ x in a..b, f x ∂μ = 0 :=
by rw [interval_integral_eq_integral_interval_oc, integral_non_ae_measurable hf, smul_zero]
lemma integral_non_ae_measurable_of_le (h : a ≤ b)
(hf : ¬ ae_measurable f (μ.restrict (Ioc a b))) :
∫ x in a..b, f x ∂μ = 0 :=
integral_non_ae_measurable $ by rwa [interval_oc_of_le h]
lemma norm_integral_min_max (f : α → E) :
∥∫ x in min a b..max a b, f x ∂μ∥ = ∥∫ x in a..b, f x ∂μ∥ :=
by cases le_total a b; simp [*, integral_symm a b]
lemma norm_integral_eq_norm_integral_Ioc (f : α → E) :
∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ι a b, f x ∂μ∥ :=
by rw [← norm_integral_min_max, integral_of_le min_le_max, interval_oc]
lemma abs_integral_eq_abs_integral_interval_oc (f : α → ℝ) :
|∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| :=
norm_integral_eq_norm_integral_Ioc f
lemma norm_integral_le_integral_norm_Ioc :
∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in Ι a b, ∥f x∥ ∂μ :=
calc ∥∫ x in a..b, f x ∂μ∥ = ∥∫ x in Ι a b, f x ∂μ∥ :
norm_integral_eq_norm_integral_Ioc f
... ≤ ∫ x in Ι a b, ∥f x∥ ∂μ :
norm_integral_le_integral_norm f
lemma norm_integral_le_abs_integral_norm : ∥∫ x in a..b, f x ∂μ∥ ≤ |∫ x in a..b, ∥f x∥ ∂μ| :=
begin
simp only [← real.norm_eq_abs, norm_integral_eq_norm_integral_Ioc],
exact le_trans (norm_integral_le_integral_norm _) (le_abs_self _)
end
lemma norm_integral_le_integral_norm (h : a ≤ b) :
∥∫ x in a..b, f x ∂μ∥ ≤ ∫ x in a..b, ∥f x∥ ∂μ :=
norm_integral_le_integral_norm_Ioc.trans_eq $ by rw [interval_oc_of_le h, integral_of_le h]
lemma norm_integral_le_of_norm_le_const_ae {a b C : ℝ} {f : ℝ → E}
(h : ∀ᵐ x, x ∈ Ι a b → ∥f x∥ ≤ C) :
∥∫ x in a..b, f x∥ ≤ C * |b - a| :=
begin
rw [norm_integral_eq_norm_integral_Ioc],
convert norm_set_integral_le_of_norm_le_const_ae'' _ measurable_set_Ioc h,
{ rw [real.volume_Ioc, max_sub_min_eq_abs, ennreal.to_real_of_real (abs_nonneg _)] },
{ simp only [real.volume_Ioc, ennreal.of_real_lt_top] },
end
lemma norm_integral_le_of_norm_le_const {a b C : ℝ} {f : ℝ → E}
(h : ∀ x ∈ Ι a b, ∥f x∥ ≤ C) :
∥∫ x in a..b, f x∥ ≤ C * |b - a| :=
norm_integral_le_of_norm_le_const_ae $ eventually_of_forall h
@[simp] lemma integral_add (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
∫ x in a..b, f x + g x ∂μ = ∫ x in a..b, f x ∂μ + ∫ x in a..b, g x ∂μ :=
by simp only [interval_integral_eq_integral_interval_oc, integral_add hf.def hg.def, smul_add]
lemma integral_finset_sum {ι} {s : finset ι} {f : ι → α → E}
(h : ∀ i ∈ s, interval_integrable (f i) μ a b) :
∫ x in a..b, ∑ i in s, f i x ∂μ = ∑ i in s, ∫ x in a..b, f i x ∂μ :=
by simp only [interval_integral_eq_integral_interval_oc,
integral_finset_sum s (λ i hi, (h i hi).def), finset.smul_sum]
@[simp] lemma integral_neg : ∫ x in a..b, -f x ∂μ = -∫ x in a..b, f x ∂μ :=
by { simp only [interval_integral, integral_neg], abel }
@[simp] lemma integral_sub (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b) :
∫ x in a..b, f x - g x ∂μ = ∫ x in a..b, f x ∂μ - ∫ x in a..b, g x ∂μ :=
by simpa only [sub_eq_add_neg] using (integral_add hf hg.neg).trans (congr_arg _ integral_neg)
@[simp] lemma integral_smul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E]
[smul_comm_class ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜]
(r : 𝕜) (f : α → E) : ∫ x in a..b, r • f x ∂μ = r • ∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, integral_smul, smul_sub]
@[simp] lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E]
(f : α → 𝕜) (c : E) :
∫ x in a..b, f x • c ∂μ = (∫ x in a..b, f x ∂μ) • c :=
by simp only [interval_integral_eq_integral_interval_oc, integral_smul_const, smul_assoc]
@[simp] lemma integral_const_mul {𝕜 : Type*} [is_R_or_C 𝕜]
(r : 𝕜) (f : α → 𝕜) : ∫ x in a..b, r * f x ∂μ = r * ∫ x in a..b, f x ∂μ :=
integral_smul r f
@[simp] lemma integral_mul_const {𝕜 : Type*} [is_R_or_C 𝕜]
(r : 𝕜) (f : α → 𝕜) : ∫ x in a..b, f x * r ∂μ = ∫ x in a..b, f x ∂μ * r :=
by simpa only [mul_comm r] using integral_const_mul r f
@[simp] lemma integral_div {𝕜 : Type*} [is_R_or_C 𝕜]
(r : 𝕜) (f : α → 𝕜) : ∫ x in a..b, f x / r ∂μ = ∫ x in a..b, f x ∂μ / r :=
by simpa only [div_eq_mul_inv] using integral_mul_const r⁻¹ f
lemma integral_const' (c : E) :
∫ x in a..b, c ∂μ = ((μ $ Ioc a b).to_real - (μ $ Ioc b a).to_real) • c :=
by simp only [interval_integral, set_integral_const, sub_smul]
@[simp] lemma integral_const {a b : ℝ} (c : E) : ∫ x in a..b, c = (b - a) • c :=
by simp only [integral_const', real.volume_Ioc, ennreal.to_real_of_real', ← neg_sub b,
max_zero_sub_eq_self]
lemma integral_smul_measure (c : ℝ≥0∞) :
∫ x in a..b, f x ∂(c • μ) = c.to_real • ∫ x in a..b, f x ∂μ :=
by simp only [interval_integral, measure.restrict_smul, integral_smul_measure, smul_sub]
variables [normed_group F] [second_countable_topology F] [complete_space F] [normed_space ℝ F]
[measurable_space F] [borel_space F]
lemma _root_.continuous_linear_map.interval_integral_comp_comm
(L : E →L[ℝ] F) (hf : interval_integrable f μ a b) :
∫ x in a..b, L (f x) ∂μ = L (∫ x in a..b, f x ∂μ) :=
begin
rw [interval_integral, interval_integral, L.integral_comp_comm, L.integral_comp_comm, L.map_sub],
exacts [hf.2, hf.1]
end
end basic
section comp
variables {a b c d : ℝ} (f : ℝ → E)
@[simp] lemma integral_comp_mul_right (hc : c ≠ 0) :
∫ x in a..b, f (x * c) = c⁻¹ • ∫ x in a*c..b*c, f x :=
begin
have A : measurable_embedding (λ x, x * c) :=
(homeomorph.mul_right₀ c hc).closed_embedding.measurable_embedding,
conv_rhs { rw [← real.smul_map_volume_mul_right hc] },
simp_rw [integral_smul_measure, interval_integral, A.set_integral_map,
ennreal.to_real_of_real (abs_nonneg c)],
cases hc.lt_or_lt,
{ simp [h, mul_div_cancel, hc, abs_of_neg, measure.restrict_congr_set Ico_ae_eq_Ioc] },
{ simp [h, mul_div_cancel, hc, abs_of_pos] }
end
@[simp] lemma smul_integral_comp_mul_right (c) :
c • ∫ x in a..b, f (x * c) = ∫ x in a*c..b*c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_mul_left (hc : c ≠ 0) :
∫ x in a..b, f (c * x) = c⁻¹ • ∫ x in c*a..c*b, f x :=
by simpa only [mul_comm c] using integral_comp_mul_right f hc
@[simp] lemma smul_integral_comp_mul_left (c) :
c • ∫ x in a..b, f (c * x) = ∫ x in c*a..c*b, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div (hc : c ≠ 0) :
∫ x in a..b, f (x / c) = c • ∫ x in a/c..b/c, f x :=
by simpa only [inv_inv₀] using integral_comp_mul_right f (inv_ne_zero hc)
@[simp] lemma inv_smul_integral_comp_div (c) :
c⁻¹ • ∫ x in a..b, f (x / c) = ∫ x in a/c..b/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_right (d) :
∫ x in a..b, f (x + d) = ∫ x in a+d..b+d, f x :=
have A : measurable_embedding (λ x, x + d) :=
(homeomorph.add_right d).closed_embedding.measurable_embedding,
calc ∫ x in a..b, f (x + d)
= ∫ x in a+d..b+d, f x ∂(measure.map (λ x, x + d) volume)
: by simp [interval_integral, A.set_integral_map]
... = ∫ x in a+d..b+d, f x : by rw [real.map_volume_add_right]
@[simp] lemma integral_comp_add_left (d) :
∫ x in a..b, f (d + x) = ∫ x in d+a..d+b, f x :=
by simpa only [add_comm] using integral_comp_add_right f d
@[simp] lemma integral_comp_mul_add (hc : c ≠ 0) (d) :
∫ x in a..b, f (c * x + d) = c⁻¹ • ∫ x in c*a+d..c*b+d, f x :=
by rw [← integral_comp_add_right, ← integral_comp_mul_left _ hc]
@[simp] lemma smul_integral_comp_mul_add (c d) :
c • ∫ x in a..b, f (c * x + d) = ∫ x in c*a+d..c*b+d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_mul (hc : c ≠ 0) (d) :
∫ x in a..b, f (d + c * x) = c⁻¹ • ∫ x in d+c*a..d+c*b, f x :=
by rw [← integral_comp_add_left, ← integral_comp_mul_left _ hc]
@[simp] lemma smul_integral_comp_add_mul (c d) :
c • ∫ x in a..b, f (d + c * x) = ∫ x in d+c*a..d+c*b, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div_add (hc : c ≠ 0) (d) :
∫ x in a..b, f (x / c + d) = c • ∫ x in a/c+d..b/c+d, f x :=
by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_add f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_div_add (c d) :
c⁻¹ • ∫ x in a..b, f (x / c + d) = ∫ x in a/c+d..b/c+d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_add_div (hc : c ≠ 0) (d) :
∫ x in a..b, f (d + x / c) = c • ∫ x in d+a/c..d+b/c, f x :=
by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_add_mul f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_add_div (c d) :
c⁻¹ • ∫ x in a..b, f (d + x / c) = ∫ x in d+a/c..d+b/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_mul_sub (hc : c ≠ 0) (d) :
∫ x in a..b, f (c * x - d) = c⁻¹ • ∫ x in c*a-d..c*b-d, f x :=
by simpa only [sub_eq_add_neg] using integral_comp_mul_add f hc (-d)
@[simp] lemma smul_integral_comp_mul_sub (c d) :
c • ∫ x in a..b, f (c * x - d) = ∫ x in c*a-d..c*b-d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_mul (hc : c ≠ 0) (d) :
∫ x in a..b, f (d - c * x) = c⁻¹ • ∫ x in d-c*b..d-c*a, f x :=
begin
simp only [sub_eq_add_neg, neg_mul_eq_neg_mul],
rw [integral_comp_add_mul f (neg_ne_zero.mpr hc) d, integral_symm],
simp only [inv_neg, smul_neg, neg_neg, neg_smul],
end
@[simp] lemma smul_integral_comp_sub_mul (c d) :
c • ∫ x in a..b, f (d - c * x) = ∫ x in d-c*b..d-c*a, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_div_sub (hc : c ≠ 0) (d) :
∫ x in a..b, f (x / c - d) = c • ∫ x in a/c-d..b/c-d, f x :=
by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_mul_sub f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_div_sub (c d) :
c⁻¹ • ∫ x in a..b, f (x / c - d) = ∫ x in a/c-d..b/c-d, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_div (hc : c ≠ 0) (d) :
∫ x in a..b, f (d - x / c) = c • ∫ x in d-b/c..d-a/c, f x :=
by simpa only [div_eq_inv_mul, inv_inv₀] using integral_comp_sub_mul f (inv_ne_zero hc) d
@[simp] lemma inv_smul_integral_comp_sub_div (c d) :
c⁻¹ • ∫ x in a..b, f (d - x / c) = ∫ x in d-b/c..d-a/c, f x :=
by by_cases hc : c = 0; simp [hc]
@[simp] lemma integral_comp_sub_right (d) :
∫ x in a..b, f (x - d) = ∫ x in a-d..b-d, f x :=
by simpa only [sub_eq_add_neg] using integral_comp_add_right f (-d)
@[simp] lemma integral_comp_sub_left (d) :
∫ x in a..b, f (d - x) = ∫ x in d-b..d-a, f x :=
by simpa only [one_mul, one_smul, inv_one] using integral_comp_sub_mul f one_ne_zero d
@[simp] lemma integral_comp_neg : ∫ x in a..b, f (-x) = ∫ x in -b..-a, f x :=
by simpa only [zero_sub] using integral_comp_sub_left f 0
end comp
/-!
### Integral is an additive function of the interval
In this section we prove that `∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ`
as well as a few other identities trivially equivalent to this one. We also prove that
`∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ` provided that `support f ⊆ Ioc a b`.
-/
section order_closed_topology
variables [topological_space α] [order_closed_topology α] [opens_measurable_space α]
{a b c d : α} {f g : α → E} {μ : measure α}
lemma integrable_on_Icc_iff_integrable_on_Ioc'
{E : Type*} [measurable_space E] [normed_group E]
{f : α → E} {a b : α} (ha : μ {a} ≠ ⊤) :
integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ :=
begin
cases le_or_lt a b with hab hab,
{ have : Icc a b = Icc a a ∪ Ioc a b := (Icc_union_Ioc_eq_Icc le_rfl hab).symm,
rw [this, integrable_on_union],
simp [lt_top_iff_ne_top.2 ha] },
{ simp [hab, hab.le] },
end
lemma integrable_on_Icc_iff_integrable_on_Ioc
{E : Type*} [measurable_space E] [normed_group E] [has_no_atoms μ] {f : α → E} {a b : α} :
integrable_on f (Icc a b) μ ↔ integrable_on f (Ioc a b) μ :=
integrable_on_Icc_iff_integrable_on_Ioc' (by simp)
lemma interval_integrable_iff_integrable_Icc_of_le
{E : Type*} [measurable_space E] [normed_group E]
{f : α → E} {a b : α} (hab : a ≤ b) {μ : measure α} [has_no_atoms μ] :
interval_integrable f μ a b ↔ integrable_on f (Icc a b) μ :=
by rw [interval_integrable_iff_integrable_Ioc_of_le hab, integrable_on_Icc_iff_integrable_on_Ioc]
/-- If two functions are equal in the relevant interval, their interval integrals are also equal. -/
lemma integral_congr {a b : α} (h : eq_on f g (interval a b)) :
∫ x in a..b, f x ∂μ = ∫ x in a..b, g x ∂μ :=
by cases le_total a b with hab hab; simpa [hab, integral_of_le, integral_of_ge]
using set_integral_congr measurable_set_Ioc (h.mono Ioc_subset_Icc_self)
lemma integral_add_adjacent_intervals_cancel (hab : interval_integrable f μ a b)
(hbc : interval_integrable f μ b c) :
∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ + ∫ x in c..a, f x ∂μ = 0 :=
begin
have hac := hab.trans hbc,
simp only [interval_integral, ← add_sub_comm, sub_eq_zero],
iterate 4 { rw ← integral_union },
{ suffices : Ioc a b ∪ Ioc b c ∪ Ioc c a = Ioc b a ∪ Ioc c b ∪ Ioc a c, by rw this,
rw [Ioc_union_Ioc_union_Ioc_cycle, union_right_comm, Ioc_union_Ioc_union_Ioc_cycle,
min_left_comm, max_left_comm] },
all_goals { simp [*, measurable_set.union, measurable_set_Ioc, Ioc_disjoint_Ioc_same,
Ioc_disjoint_Ioc_same.symm, hab.1, hab.2, hbc.1, hbc.2, hac.1, hac.2] }
end
lemma integral_add_adjacent_intervals (hab : interval_integrable f μ a b)
(hbc : interval_integrable f μ b c) :
∫ x in a..b, f x ∂μ + ∫ x in b..c, f x ∂μ = ∫ x in a..c, f x ∂μ :=
by rw [← add_neg_eq_zero, ← integral_symm, integral_add_adjacent_intervals_cancel hab hbc]
lemma sum_integral_adjacent_intervals {a : ℕ → α} {n : ℕ}
(hint : ∀ k < n, interval_integrable f μ (a k) (a $ k+1)) :
∑ (k : ℕ) in finset.range n, ∫ x in (a k)..(a $ k+1), f x ∂μ = ∫ x in (a 0)..(a n), f x ∂μ :=
begin
induction n with n hn,
{ simp },
{ rw [finset.sum_range_succ, hn (λ k hk, hint k (hk.trans n.lt_succ_self))],
exact integral_add_adjacent_intervals
(interval_integrable.trans_iterate $ λ k hk, hint k (hk.trans n.lt_succ_self))
(hint n n.lt_succ_self) }
end
lemma integral_interval_sub_left (hab : interval_integrable f μ a b)
(hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in a..c, f x ∂μ = ∫ x in c..b, f x ∂μ :=
sub_eq_of_eq_add' $ eq.symm $ integral_add_adjacent_intervals hac (hac.symm.trans hab)
lemma integral_interval_add_interval_comm (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ + ∫ x in c..d, f x ∂μ = ∫ x in a..d, f x ∂μ + ∫ x in c..b, f x ∂μ :=
by rw [← integral_add_adjacent_intervals hac hcd, add_assoc, add_left_comm,
integral_add_adjacent_intervals hac (hac.symm.trans hab), add_comm]
lemma integral_interval_sub_interval_comm (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in a..c, f x ∂μ - ∫ x in b..d, f x ∂μ :=
by simp only [sub_eq_add_neg, ← integral_symm,
integral_interval_add_interval_comm hab hcd.symm (hac.trans hcd)]
lemma integral_interval_sub_interval_comm' (hab : interval_integrable f μ a b)
(hcd : interval_integrable f μ c d) (hac : interval_integrable f μ a c) :
∫ x in a..b, f x ∂μ - ∫ x in c..d, f x ∂μ = ∫ x in d..b, f x ∂μ - ∫ x in c..a, f x ∂μ :=
by { rw [integral_interval_sub_interval_comm hab hcd hac, integral_symm b d, integral_symm a c,
sub_neg_eq_add, sub_eq_neg_add], }
lemma integral_Iic_sub_Iic (ha : integrable_on f (Iic a) μ) (hb : integrable_on f (Iic b) μ) :
∫ x in Iic b, f x ∂μ - ∫ x in Iic a, f x ∂μ = ∫ x in a..b, f x ∂μ :=
begin
wlog hab : a ≤ b using [a b] tactic.skip,
{ rw [sub_eq_iff_eq_add', integral_of_le hab, ← integral_union (Iic_disjoint_Ioc le_rfl),
Iic_union_Ioc_eq_Iic hab],
exacts [measurable_set_Ioc, ha, hb.mono_set (λ _, and.right)] },
{ intros ha hb,
rw [integral_symm, ← this hb ha, neg_sub] }
end
/-- If `μ` is a finite measure then `∫ x in a..b, c ∂μ = (μ (Iic b) - μ (Iic a)) • c`. -/
lemma integral_const_of_cdf [is_finite_measure μ] (c : E) :
∫ x in a..b, c ∂μ = ((μ (Iic b)).to_real - (μ (Iic a)).to_real) • c :=
begin
simp only [sub_smul, ← set_integral_const],
refine (integral_Iic_sub_Iic _ _).symm;
simp only [integrable_on_const, measure_lt_top, or_true]
end
lemma integral_eq_integral_of_support_subset {f : α → E} {a b} (h : support f ⊆ Ioc a b) :
∫ x in a..b, f x ∂μ = ∫ x, f x ∂μ :=
begin
cases le_total a b with hab hab,
{ rw [integral_of_le hab, ← integral_indicator measurable_set_Ioc, indicator_eq_self.2 h];
apply_instance },
{ rw [Ioc_eq_empty hab.not_lt, subset_empty_iff, support_eq_empty_iff] at h,
simp [h] }
end
lemma integral_congr_ae' {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ioc a b → f x = g x)
(h' : ∀ᵐ x ∂μ, x ∈ Ioc b a → f x = g x) :
∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ :=
by simp only [interval_integral, set_integral_congr_ae (measurable_set_Ioc) h,
set_integral_congr_ae (measurable_set_Ioc) h']
lemma integral_congr_ae {f g : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = g x) :
∫ (x : α) in a..b, f x ∂μ = ∫ (x : α) in a..b, g x ∂μ :=
integral_congr_ae' (ae_interval_oc_iff.mp h).1 (ae_interval_oc_iff.mp h).2
lemma integral_zero_ae {f : α → E} (h : ∀ᵐ x ∂μ, x ∈ Ι a b → f x = 0) :
∫ (x : α) in a..b, f x ∂μ = 0 :=
calc ∫ x in a..b, f x ∂μ = ∫ x in a..b, 0 ∂μ : integral_congr_ae h
... = 0 : integral_zero
lemma integral_indicator {a₁ a₂ a₃ : α} (h : a₂ ∈ Icc a₁ a₃) {f : α → E} :
∫ x in a₁..a₃, indicator {x | x ≤ a₂} f x ∂ μ = ∫ x in a₁..a₂, f x ∂ μ :=
begin
have : {x | x ≤ a₂} ∩ Ioc a₁ a₃ = Ioc a₁ a₂, from Iic_inter_Ioc_of_le h.2,
rw [integral_of_le h.1, integral_of_le (h.1.trans h.2),
integral_indicator, measure.restrict_restrict, this],
exact measurable_set_Iic,
all_goals { apply measurable_set_Iic },
end
/-- Lebesgue dominated convergence theorem for filters with a countable basis -/
lemma tendsto_integral_filter_of_dominated_convergence {ι} {l : filter ι}
[l.is_countably_generated] {F : ι → α → E} (bound : α → ℝ)
(hF_meas : ∀ᶠ n in l, ae_measurable (F n) (μ.restrict (Ι a b)))
(h_bound : ∀ᶠ n in l, ∀ᵐ x ∂μ, x ∈ Ι a b → ∥F n x∥ ≤ bound x)
(bound_integrable : interval_integrable bound μ a b)
(h_lim : ∀ᵐ x ∂μ, x ∈ Ι a b → tendsto (λ n, F n x) l (𝓝 (f x))) :
tendsto (λn, ∫ x in a..b, F n x ∂μ) l (𝓝 $ ∫ x in a..b, f x ∂μ) :=
begin
simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc,
← ae_restrict_iff' measurable_set_interval_oc] at *,
exact tendsto_const_nhds.smul
(tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_lim)
end
/-- Lebesgue dominated convergence theorem for series. -/
lemma has_sum_integral_of_dominated_convergence {ι} [encodable ι]
{F : ι → α → E} (bound : ι → α → ℝ)
(hF_meas : ∀ n, ae_measurable (F n) (μ.restrict (Ι a b)))
(h_bound : ∀ n, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F n t∥ ≤ bound n t)
(bound_summable : ∀ᵐ t ∂μ, t ∈ Ι a b → summable (λ n, bound n t))
(bound_integrable : interval_integrable (λ t, ∑' n, bound n t) μ a b)
(h_lim : ∀ᵐ t ∂μ, t ∈ Ι a b → has_sum (λ n, F n t) (f t)) :
has_sum (λn, ∫ t in a..b, F n t ∂μ) (∫ t in a..b, f t ∂μ) :=
begin
simp only [interval_integrable_iff, interval_integral_eq_integral_interval_oc,
← ae_restrict_iff' measurable_set_interval_oc] at *,
exact (has_sum_integral_of_dominated_convergence bound hF_meas h_bound bound_summable
bound_integrable h_lim).const_smul
end
open topological_space
variables {X : Type*} [topological_space X] [first_countable_topology X]
/-- Continuity of interval integral with respect to a parameter, at a point within a set.
Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a
neighborhood of `x₀` within `s` and at `x₀`, and assume it is bounded by a function integrable
on `[a, b]` independent of `x` in a neighborhood of `x₀` within `s`. If `(λ x, F x t)`
is continuous at `x₀` within `s` for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_within_at_of_dominated_interval
{F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α} {s : set X}
(hF_meas : ∀ᶠ x in 𝓝[s] x₀, ae_measurable (F x) (μ.restrict $ Ι a b))
(h_bound : ∀ᶠ x in 𝓝[s] x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_within_at (λ x, F x t) s x₀) :
continuous_within_at (λ x, ∫ t in a..b, F x t ∂μ) s x₀ :=
tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont
/-- Continuity of interval integral with respect to a parameter at a point.
Given `F : X → α → E`, assume `F x` is ae-measurable on `[a, b]` for `x` in a
neighborhood of `x₀`, and assume it is bounded by a function integrable on
`[a, b]` independent of `x` in a neighborhood of `x₀`. If `(λ x, F x t)`
is continuous at `x₀` for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_at_of_dominated_interval
{F : X → α → E} {x₀ : X} {bound : α → ℝ} {a b : α}
(hF_meas : ∀ᶠ x in 𝓝 x₀, ae_measurable (F x) (μ.restrict $ Ι a b))
(h_bound : ∀ᶠ x in 𝓝 x₀, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous_at (λ x, F x t) x₀) :
continuous_at (λ x, ∫ t in a..b, F x t ∂μ) x₀ :=
tendsto_integral_filter_of_dominated_convergence bound hF_meas h_bound bound_integrable h_cont
/-- Continuity of interval integral with respect to a parameter.
Given `F : X → α → E`, assume each `F x` is ae-measurable on `[a, b]`,
and assume it is bounded by a function integrable on `[a, b]` independent of `x`.
If `(λ x, F x t)` is continuous for almost every `t` in `[a, b]`
then the same holds for `(λ x, ∫ t in a..b, F x t ∂μ) s x₀`. -/
lemma continuous_of_dominated_interval {F : X → α → E} {bound : α → ℝ} {a b : α}
(hF_meas : ∀ x, ae_measurable (F x) $ μ.restrict $ Ι a b)
(h_bound : ∀ x, ∀ᵐ t ∂μ, t ∈ Ι a b → ∥F x t∥ ≤ bound t)
(bound_integrable : interval_integrable bound μ a b)
(h_cont : ∀ᵐ t ∂μ, t ∈ Ι a b → continuous (λ x, F x t)) :
continuous (λ x, ∫ t in a..b, F x t ∂μ) :=
continuous_iff_continuous_at.mpr (λ x₀, continuous_at_of_dominated_interval
(eventually_of_forall hF_meas) (eventually_of_forall h_bound) bound_integrable $ h_cont.mono $
λ x himp hx, (himp hx).continuous_at)
end order_closed_topology
section continuous_primitive
open topological_space
variables [topological_space α] [order_topology α] [opens_measurable_space α]
[first_countable_topology α] {a b : α} {μ : measure α}
lemma continuous_within_at_primitive {f : α → E} {a b₀ b₁ b₂ : α} (hb₀ : μ {b₀} = 0)
(h_int : interval_integrable f μ (min a b₁) (max a b₂)) :
continuous_within_at (λ b, ∫ x in a .. b, f x ∂ μ) (Icc b₁ b₂) b₀ :=
begin
by_cases h₀ : b₀ ∈ Icc b₁ b₂,
{ have h₁₂ : b₁ ≤ b₂ := h₀.1.trans h₀.2,
have min₁₂ : min b₁ b₂ = b₁ := min_eq_left h₁₂,
have h_int' : ∀ {x}, x ∈ Icc b₁ b₂ → interval_integrable f μ b₁ x,
{ rintros x ⟨h₁, h₂⟩,
apply h_int.mono_set,
apply interval_subset_interval,
{ exact ⟨min_le_of_left_le (min_le_right a b₁),
h₁.trans (h₂.trans $ le_max_of_le_right $ le_max_right _ _)⟩ },
{ exact ⟨min_le_of_left_le $ (min_le_right _ _).trans h₁,
le_max_of_le_right $ h₂.trans $ le_max_right _ _⟩ } },
have : ∀ b ∈ Icc b₁ b₂, ∫ x in a..b, f x ∂μ = ∫ x in a..b₁, f x ∂μ + ∫ x in b₁..b, f x ∂μ,
{ rintros b ⟨h₁, h₂⟩,
rw ← integral_add_adjacent_intervals _ (h_int' ⟨h₁, h₂⟩),
apply h_int.mono_set,
apply interval_subset_interval,
{ exact ⟨min_le_of_left_le (min_le_left a b₁), le_max_of_le_right (le_max_left _ _)⟩ },
{ exact ⟨min_le_of_left_le (min_le_right _ _),
le_max_of_le_right (h₁.trans $ h₂.trans (le_max_right a b₂))⟩ } },
apply continuous_within_at.congr _ this (this _ h₀), clear this,
refine continuous_within_at_const.add _,
have : (λ b, ∫ x in b₁..b, f x ∂μ) =ᶠ[𝓝[Icc b₁ b₂] b₀]
λ b, ∫ x in b₁..b₂, indicator {x | x ≤ b} f x ∂ μ,
{ apply eventually_eq_of_mem self_mem_nhds_within,
exact λ b b_in, (integral_indicator b_in).symm },
apply continuous_within_at.congr_of_eventually_eq _ this (integral_indicator h₀).symm,
have : interval_integrable (λ x, ∥f x∥) μ b₁ b₂,
from interval_integrable.norm (h_int' $ right_mem_Icc.mpr h₁₂),
refine continuous_within_at_of_dominated_interval _ _ this _ ; clear this,
{ apply eventually.mono (self_mem_nhds_within),
intros x hx,
erw [ae_measurable_indicator_iff, measure.restrict_restrict, Iic_inter_Ioc_of_le],
{ rw min₁₂,
exact (h_int' hx).1.ae_measurable },
{ exact le_max_of_le_right hx.2 },
exacts [measurable_set_Iic, measurable_set_Iic] },
{ refine eventually_of_forall (λ (x : α), eventually_of_forall (λ (t : α), _)),
dsimp [indicator],
split_ifs ; simp },
{ have : ∀ᵐ t ∂μ, t < b₀ ∨ b₀ < t,
{ apply eventually.mono (compl_mem_ae_iff.mpr hb₀),
intros x hx,
exact ne.lt_or_lt hx },
apply this.mono,
rintros x₀ (hx₀ | hx₀) -,
{ have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = f x₀,
{ apply mem_nhds_within_of_mem_nhds,
apply eventually.mono (Ioi_mem_nhds hx₀),
intros x hx,
simp [hx.le] },
apply continuous_within_at_const.congr_of_eventually_eq this,
simp [hx₀.le] },
{ have : ∀ᶠ x in 𝓝[Icc b₁ b₂] b₀, {t : α | t ≤ x}.indicator f x₀ = 0,
{ apply mem_nhds_within_of_mem_nhds,
apply eventually.mono (Iio_mem_nhds hx₀),
intros x hx,
simp [hx] },
apply continuous_within_at_const.congr_of_eventually_eq this,
simp [hx₀] } } },
{ apply continuous_within_at_of_not_mem_closure,
rwa [closure_Icc] }
end
lemma continuous_on_primitive {f : α → E} {a b : α} [has_no_atoms μ]
(h_int : integrable_on f (Icc a b) μ) :
continuous_on (λ x, ∫ t in Ioc a x, f t ∂ μ) (Icc a b) :=
begin
by_cases h : a ≤ b,
{ have : ∀ x ∈ Icc a b, ∫ (t : α) in Ioc a x, f t ∂μ = ∫ (t : α) in a..x, f t ∂μ,
{ intros x x_in,
simp_rw [← interval_oc_of_le h, integral_of_le x_in.1] },
rw continuous_on_congr this,
intros x₀ hx₀,
refine continuous_within_at_primitive (measure_singleton x₀) _,
simp only [interval_integrable_iff_integrable_Ioc_of_le, min_eq_left, max_eq_right, h],
exact h_int.mono Ioc_subset_Icc_self le_rfl },
{ rw Icc_eq_empty h,
exact continuous_on_empty _ },
end
lemma continuous_on_primitive_Icc {f : α → E} {a b : α} [has_no_atoms μ]
(h_int : integrable_on f (Icc a b) μ) :
continuous_on (λ x, ∫ t in Icc a x, f t ∂ μ) (Icc a b) :=
begin
rw show (λ x, ∫ t in Icc a x, f t ∂μ) = λ x, ∫ t in Ioc a x, f t ∂μ,
by { ext x, exact integral_Icc_eq_integral_Ioc },
exact continuous_on_primitive h_int
end
/-- Note: this assumes that `f` is `interval_integrable`, in contrast to some other lemmas here. -/
lemma continuous_on_primitive_interval' {f : α → E} {a b₁ b₂ : α} [has_no_atoms μ]
(h_int : interval_integrable f μ b₁ b₂) (ha : a ∈ [b₁, b₂]) :
continuous_on (λ b, ∫ x in a..b, f x ∂ μ) [b₁, b₂] :=
begin
intros b₀ hb₀,
refine continuous_within_at_primitive (measure_singleton _) _,
rw [min_eq_right ha.1, max_eq_right ha.2],
simpa [interval_integrable_iff, interval_oc] using h_int,
end
lemma continuous_on_primitive_interval {f : α → E} {a b : α} [has_no_atoms μ]
(h_int : integrable_on f (interval a b) μ) :
continuous_on (λ x, ∫ t in a..x, f t ∂ μ) (interval a b) :=
continuous_on_primitive_interval' h_int.interval_integrable left_mem_interval
lemma continuous_on_primitive_interval_left {f : α → E} {a b : α} [has_no_atoms μ]
(h_int : integrable_on f (interval a b) μ) :
continuous_on (λ x, ∫ t in x..b, f t ∂ μ) (interval a b) :=
begin
rw interval_swap a b at h_int ⊢,
simp only [integral_symm b],
exact (continuous_on_primitive_interval h_int).neg,
end
variables [no_min_order α] [no_max_order α] [has_no_atoms μ]
lemma continuous_primitive {f : α → E} (h_int : ∀ a b : α, interval_integrable f μ a b) (a : α) :
continuous (λ b, ∫ x in a..b, f x ∂ μ) :=
begin
rw continuous_iff_continuous_at,
intro b₀,
cases exists_lt b₀ with b₁ hb₁,
cases exists_gt b₀ with b₂ hb₂,
apply continuous_within_at.continuous_at _ (Icc_mem_nhds hb₁ hb₂),
exact continuous_within_at_primitive (measure_singleton b₀) (h_int _ _)
end
lemma _root_.measure_theory.integrable.continuous_primitive {f : α → E} (h_int : integrable f μ)
(a : α) : continuous (λ b, ∫ x in a..b, f x ∂ μ) :=
continuous_primitive (λ _ _, h_int.interval_integrable) a
end continuous_primitive
section
variables {f g : α → ℝ} {a b : α} {μ : measure α}
lemma integral_eq_zero_iff_of_le_of_nonneg_ae (hab : a ≤ b)
(hf : 0 ≤ᵐ[μ.restrict (Ioc a b)] f) (hfi : interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b)] 0 :=
by rw [integral_of_le hab, integral_eq_zero_iff_of_nonneg_ae hf hfi.1]
lemma integral_eq_zero_iff_of_nonneg_ae
(hf : 0 ≤ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] f) (hfi : interval_integrable f μ a b) :
∫ x in a..b, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict (Ioc a b ∪ Ioc b a)] 0 :=
begin
cases le_total a b with hab hab;
simp only [Ioc_eq_empty hab.not_lt, empty_union, union_empty] at hf ⊢,
{ exact integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi },
{ rw [integral_symm, neg_eq_zero, integral_eq_zero_iff_of_le_of_nonneg_ae hab hf hfi.symm] }
end
/-- If `f` is nonnegative and integrable on the unordered interval `set.interval_oc a b`, then its
integral over `a..b` is positive if and only if `a < b` and the measure of
`function.support f ∩ set.Ioc a b` is positive. -/
lemma integral_pos_iff_support_of_nonneg_ae'
(hf : 0 ≤ᵐ[μ.restrict (Ι a b)] f) (hfi : interval_integrable f μ a b) :
0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) :=
begin
cases lt_or_le a b with hab hba,
{ rw interval_oc_of_le hab.le at hf,
simp only [hab, true_and, integral_of_le hab.le,
set_integral_pos_iff_support_of_nonneg_ae hf hfi.1] },
{ suffices : ∫ x in a..b, f x ∂μ ≤ 0, by simp only [this.not_lt, hba.not_lt, false_and],
rw [integral_of_ge hba, neg_nonpos],
rw [interval_oc_swap, interval_oc_of_le hba] at hf,
exact integral_nonneg_of_ae hf }
end
/-- If `f` is nonnegative a.e.-everywhere and it is integrable on the unordered interval
`set.interval_oc a b`, then its integral over `a..b` is positive if and only if `a < b` and the
measure of `function.support f ∩ set.Ioc a b` is positive. -/
lemma integral_pos_iff_support_of_nonneg_ae (hf : 0 ≤ᵐ[μ] f) (hfi : interval_integrable f μ a b) :
0 < ∫ x in a..b, f x ∂μ ↔ a < b ∧ 0 < μ (support f ∩ Ioc a b) :=
integral_pos_iff_support_of_nonneg_ae' (ae_mono measure.restrict_le_self hf) hfi
/-- If `f` and `g` are two functions that are interval integrable on `a..b`, `a ≤ b`,
`f x ≤ g x` for a.e. `x ∈ set.Ioc a b`, and `f x < g x` on a subset of `set.Ioc a b`
of nonzero measure, then `∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ`. -/
lemma integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero (hab : a ≤ b)
(hfi : interval_integrable f μ a b) (hgi : interval_integrable g μ a b)
(hle : f ≤ᵐ[μ.restrict (Ioc a b)] g) (hlt : μ.restrict (Ioc a b) {x | f x < g x} ≠ 0) :
∫ x in a..b, f x ∂μ < ∫ x in a..b, g x ∂μ :=
begin
rw [← sub_pos, ← integral_sub hgi hfi, integral_of_le hab,
measure_theory.integral_pos_iff_support_of_nonneg_ae],
{ refine pos_iff_ne_zero.2 (mt (measure_mono_null _) hlt),
exact λ x hx, (sub_pos.2 hx).ne' },
exacts [hle.mono (λ x, sub_nonneg.2), hgi.1.sub hfi.1]
end
/-- If `f` and `g` are continuous on `[a, b]`, `a < b`, `f x ≤ g x` on this interval, and
`f c < g c` at some point `c ∈ [a, b]`, then `∫ x in a..b, f x < ∫ x in a..b, g x`. -/
lemma integral_lt_integral_of_continuous_on_of_le_of_exists_lt {f g : ℝ → ℝ} {a b : ℝ}
(hab : a < b) (hfc : continuous_on f (Icc a b)) (hgc : continuous_on g (Icc a b))
(hle : ∀ x ∈ Ioc a b, f x ≤ g x) (hlt : ∃ c ∈ Icc a b, f c < g c) :
∫ x in a..b, f x < ∫ x in a..b, g x :=
begin
refine integral_lt_integral_of_ae_le_of_measure_set_of_lt_ne_zero hab.le
(hfc.interval_integrable_of_Icc hab.le) (hgc.interval_integrable_of_Icc hab.le)
((ae_restrict_mem measurable_set_Ioc).mono hle) _,
contrapose! hlt,
have h_eq : f =ᵐ[volume.restrict (Ioc a b)] g,
{ simp only [← not_le, ← ae_iff] at hlt,
exact eventually_le.antisymm ((ae_restrict_iff' measurable_set_Ioc).2 $
eventually_of_forall hle) hlt },
simp only [measure.restrict_congr_set Ioc_ae_eq_Icc] at h_eq,
exact λ c hc, (measure.eq_on_Icc_of_ae_eq volume hab.ne h_eq hfc hgc hc).ge
end
lemma integral_nonneg_of_ae_restrict (hab : a ≤ b) (hf : 0 ≤ᵐ[μ.restrict (Icc a b)] f) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
let H := ae_restrict_of_ae_restrict_of_subset Ioc_subset_Icc_self hf in
by simpa only [integral_of_le hab] using set_integral_nonneg_of_ae_restrict H
lemma integral_nonneg_of_ae (hab : a ≤ b) (hf : 0 ≤ᵐ[μ] f) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae_restrict hab $ ae_restrict_of_ae hf
lemma integral_nonneg_of_forall (hab : a ≤ b) (hf : ∀ u, 0 ≤ f u) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae hab $ eventually_of_forall hf
lemma integral_nonneg [topological_space α] [opens_measurable_space α] [order_closed_topology α]
(hab : a ≤ b) (hf : ∀ u, u ∈ Icc a b → 0 ≤ f u) :
0 ≤ (∫ u in a..b, f u ∂μ) :=
integral_nonneg_of_ae_restrict hab $ (ae_restrict_iff' measurable_set_Icc).mpr $ ae_of_all μ hf
lemma abs_integral_le_integral_abs (hab : a ≤ b) :
|∫ x in a..b, f x ∂μ| ≤ ∫ x in a..b, |f x| ∂μ :=
by simpa only [← real.norm_eq_abs] using norm_integral_le_integral_norm hab
section mono
variables (hab : a ≤ b) (hf : interval_integrable f μ a b) (hg : interval_integrable g μ a b)
include hab hf hg
lemma integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict (Icc a b)] g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
let H := h.filter_mono $ ae_mono $ measure.restrict_mono Ioc_subset_Icc_self $ le_refl μ in
by simpa only [integral_of_le hab] using set_integral_mono_ae_restrict hf.1 hg.1 H
lemma integral_mono_ae (h : f ≤ᵐ[μ] g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
by simpa only [integral_of_le hab] using set_integral_mono_ae hf.1 hg.1 h
lemma integral_mono_on [topological_space α] [opens_measurable_space α] [order_closed_topology α]
(h : ∀ x ∈ Icc a b, f x ≤ g x) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
let H := λ x hx, h x $ Ioc_subset_Icc_self hx in
by simpa only [integral_of_le hab] using set_integral_mono_on hf.1 hg.1 measurable_set_Ioc H
lemma integral_mono (h : f ≤ g) :
∫ u in a..b, f u ∂μ ≤ ∫ u in a..b, g u ∂μ :=
integral_mono_ae hab hf hg $ ae_of_all _ h
omit hg hab
lemma integral_mono_interval {c d} (hca : c ≤ a) (hab : a ≤ b) (hbd : b ≤ d)
(hf : 0 ≤ᵐ[μ.restrict (Ioc c d)] f) (hfi : interval_integrable f μ c d):
∫ x in a..b, f x ∂μ ≤ ∫ x in c..d, f x ∂μ :=
begin
rw [integral_of_le hab, integral_of_le (hca.trans (hab.trans hbd))],
exact set_integral_mono_set hfi.1 hf (Ioc_subset_Ioc hca hbd).eventually_le
end
lemma abs_integral_mono_interval {c d } (h : Ι a b ⊆ Ι c d)
(hf : 0 ≤ᵐ[μ.restrict (Ι c d)] f) (hfi : interval_integrable f μ c d) :
|∫ x in a..b, f x ∂μ| ≤ |∫ x in c..d, f x ∂μ| :=
have hf' : 0 ≤ᵐ[μ.restrict (Ι a b)] f, from ae_mono (measure.restrict_mono h le_rfl) hf,
calc |∫ x in a..b, f x ∂μ| = |∫ x in Ι a b, f x ∂μ| : abs_integral_eq_abs_integral_interval_oc f
... = ∫ x in Ι a b, f x ∂μ : abs_of_nonneg (measure_theory.integral_nonneg_of_ae hf')
... ≤ ∫ x in Ι c d, f x ∂μ : set_integral_mono_set hfi.def hf h.eventually_le
... ≤ |∫ x in Ι c d, f x ∂μ| : le_abs_self _
... = |∫ x in c..d, f x ∂μ| : (abs_integral_eq_abs_integral_interval_oc f).symm
end mono
end
/-!
### Fundamental theorem of calculus, part 1, for any measure
In this section we prove a few lemmas that can be seen as versions of FTC-1 for interval integrals
w.r.t. any measure. Many theorems are formulated for one or two pairs of filters related by
`FTC_filter a l l'`. This typeclass has exactly four “real” instances: `(a, pure a, ⊥)`,
`(a, 𝓝[≥] a, 𝓝[>] a)`, `(a, 𝓝[≤] a, 𝓝[≤] a)`, `(a, 𝓝 a, 𝓝 a)`, and two instances
that are equal to the first and last “real” instances: `(a, 𝓝[{a}] a, ⊥)` and
`(a, 𝓝[univ] a, 𝓝[univ] a)`. We use this approach to avoid repeating arguments in many very similar
cases. Lean can automatically find both `a` and `l'` based on `l`.
The most general theorem `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` can be seen
as a generalization of lemma `integral_has_strict_fderiv_at` below which states strict
differentiability of `∫ x in u..v, f x` in `(u, v)` at `(a, b)` for a measurable function `f` that
is integrable on `a..b` and is continuous at `a` and `b`. The lemma is generalized in three
directions: first, `measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae` deals with any
locally finite measure `μ`; second, it works for one-sided limits/derivatives; third, it assumes
only that `f` has finite limits almost surely at `a` and `b`.
Namely, let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of
`FTC_filter`s around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f`
has finite limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively. Then
`∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ = ∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ +
o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)`
as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`.
This theorem is formulated with integral of constants instead of measures in the right hand sides
for two reasons: first, this way we avoid `min`/`max` in the statements; second, often it is
possible to write better `simp` lemmas for these integrals, see `integral_const` and
`integral_const_of_cdf`.
In the next subsection we apply this theorem to prove various theorems about differentiability
of the integral w.r.t. Lebesgue measure. -/
/-- An auxiliary typeclass for the Fundamental theorem of calculus, part 1. It is used to formulate
theorems that work simultaneously for left and right one-sided derivatives of `∫ x in u..v, f x`. -/
class FTC_filter {β : Type*} [linear_order β] [measurable_space β] [topological_space β]
(a : out_param β) (outer : filter β) (inner : out_param $ filter β)
extends tendsto_Ixx_class Ioc outer inner : Prop :=
(pure_le : pure a ≤ outer)
(le_nhds : inner ≤ 𝓝 a)
[meas_gen : is_measurably_generated inner]
/- The `dangerous_instance` linter doesn't take `out_param`s into account, so it thinks that
`FTC_filter.to_tendsto_Ixx_class` is dangerous. Disable this linter using `nolint`.
-/
attribute [nolint dangerous_instance] FTC_filter.to_tendsto_Ixx_class
namespace FTC_filter
variables [linear_order β] [measurable_space β] [topological_space β]
instance pure (a : β) : FTC_filter a (pure a) ⊥ :=
{ pure_le := le_rfl,
le_nhds := bot_le }
instance nhds_within_singleton (a : β) : FTC_filter a (𝓝[{a}] a) ⊥ :=
by { rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)], apply_instance }
lemma finite_at_inner {a : β} (l : filter β) {l'} [h : FTC_filter a l l']
{μ : measure β} [is_locally_finite_measure μ] :
μ.finite_at_filter l' :=
(μ.finite_at_nhds a).filter_mono h.le_nhds
variables [opens_measurable_space β] [order_topology β]
instance nhds (a : β) : FTC_filter a (𝓝 a) (𝓝 a) :=
{ pure_le := pure_le_nhds a,
le_nhds := le_rfl }
instance nhds_univ (a : β) : FTC_filter a (𝓝[univ] a) (𝓝 a) :=
by { rw nhds_within_univ, apply_instance }
instance nhds_left (a : β) : FTC_filter a (𝓝[≤] a) (𝓝[≤] a) :=
{ pure_le := pure_le_nhds_within right_mem_Iic,
le_nhds := inf_le_left }
instance nhds_right (a : β) : FTC_filter a (𝓝[≥] a) (𝓝[>] a) :=
{ pure_le := pure_le_nhds_within left_mem_Ici,
le_nhds := inf_le_left }
instance nhds_Icc {x a b : β} [h : fact (x ∈ Icc a b)] :
FTC_filter x (𝓝[Icc a b] x) (𝓝[Icc a b] x) :=
{ pure_le := pure_le_nhds_within h.out,
le_nhds := inf_le_left }
instance nhds_interval {x a b : β} [h : fact (x ∈ [a, b])] :
FTC_filter x (𝓝[[a, b]] x) (𝓝[[a, b]] x) :=
by { haveI : fact (x ∈ set.Icc (min a b) (max a b)) := h, exact FTC_filter.nhds_Icc }
end FTC_filter
open asymptotics
section
variables {f : α → E} {a b : α} {c ca cb : E} {l l' la la' lb lb' : filter α} {lt : filter β}
{μ : measure α} {u v ua va ub vb : β → α}
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`.
If `f` has a finite limit `c` at `l' ⊓ μ.ae`, where `μ` is a measure
finite at `l'`, then `∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both
`u` and `v` tend to `l`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae` for a version assuming
`[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`,
`𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version.
The primed version also works, e.g., for `l = l' = at_top`.
We use integrals of constants instead of measures because this way it is easier to formulate
a statement that works in both cases `u ≤ v` and `v ≤ u`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae'
[is_measurably_generated l'] [tendsto_Ixx_class Ioc l l']
(hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
(hl : μ.finite_at_filter l')
(hu : tendsto u lt l) (hv : tendsto v lt l) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ)
(λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt :=
begin
have A := hf.integral_sub_linear_is_o_ae hfm hl (hu.Ioc hv),
have B := hf.integral_sub_linear_is_o_ae hfm hl (hv.Ioc hu),
simp only [integral_const'],
convert (A.trans_le _).sub (B.trans_le _),
{ ext t,
simp_rw [interval_integral, sub_smul],
abel },
all_goals { intro t, cases le_total (u t) (v t) with huv huv; simp [huv] }
end
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`.
If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure
finite at `l`, then `∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both
`u` and `v` tend to `l` so that `u ≤ v`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le` for a version assuming
`[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`,
`𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version.
The primed version also works, e.g., for `l = l' = at_top`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'
[is_measurably_generated l'] [tendsto_Ixx_class Ioc l l']
(hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
(hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c)
(λ t, (μ $ Ioc (u t) (v t)).to_real) lt :=
(measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf hl hu hv).congr'
(huv.mono $ λ x hx, by simp [integral_const', hx])
(huv.mono $ λ x hx, by simp [integral_const', hx])
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `tendsto_Ixx_class Ioc`.
If `f` has a finite limit `c` at `l ⊓ μ.ae`, where `μ` is a measure
finite at `l`, then `∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both
`u` and `v` tend to `l` so that `v ≤ u`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge` for a version assuming
`[FTC_filter a l l']` and `[is_locally_finite_measure μ]`. If `l` is one of `𝓝[≥] a`,
`𝓝[≤] a`, `𝓝 a`, then it's easier to apply the non-primed version.
The primed version also works, e.g., for `l = l' = at_top`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'
[is_measurably_generated l'] [tendsto_Ixx_class Ioc l l']
(hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
(hl : μ.finite_at_filter l') (hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c)
(λ t, (μ $ Ioc (v t) (u t)).to_real) lt :=
(measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf hl hv hu huv).neg_left.congr_left $
λ t, by simp [integral_symm (u t), add_comm]
variables [topological_space α]
section
variables [is_locally_finite_measure μ] [FTC_filter a l l']
include a
local attribute [instance] FTC_filter.meas_gen
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure.
If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then
`∫ x in u..v, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, 1 ∂μ)` as both `u` and `v` tend to `l`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae'` for a version that also works, e.g., for
`l = l' = at_top`.
We use integrals of constants instead of measures because this way it is easier to formulate
a statement that works in both cases `u ≤ v` and `v ≤ u`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae (hfm : measurable_at_filter f l' μ)
(hf : tendsto f (l' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt l) (hv : tendsto v lt l) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ - ∫ x in u t..v t, c ∂μ)
(λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt :=
measure_integral_sub_linear_is_o_of_tendsto_ae' hfm hf (FTC_filter.finite_at_inner l) hu hv
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure.
If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then
`∫ x in u..v, f x ∂μ = μ (Ioc u v) • c + o(μ(Ioc u v))` as both `u` and `v` tend to `l`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_le'` for a version that also works,
e.g., for `l = l' = at_top`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_le
(hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
(hu : tendsto u lt l) (hv : tendsto v lt l) (huv : u ≤ᶠ[lt] v) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ - (μ (Ioc (u t) (v t))).to_real • c)
(λ t, (μ $ Ioc (u t) (v t)).to_real) lt :=
measure_integral_sub_linear_is_o_of_tendsto_ae_of_le' hfm hf (FTC_filter.finite_at_inner l)
hu hv huv
/-- Fundamental theorem of calculus-1, local version for any measure.
Let filters `l` and `l'` be related by `[FTC_filter a l l']`; let `μ` be a locally finite measure.
If `f` has a finite limit `c` at `l' ⊓ μ.ae`, then
`∫ x in u..v, f x ∂μ = -μ (Ioc v u) • c + o(μ(Ioc v u))` as both `u` and `v` tend to `l`.
See also `measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge'` for a version that also works,
e.g., for `l = l' = at_top`. -/
lemma measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge
(hfm : measurable_at_filter f l' μ) (hf : tendsto f (l' ⊓ μ.ae) (𝓝 c))
(hu : tendsto u lt l) (hv : tendsto v lt l) (huv : v ≤ᶠ[lt] u) :
is_o (λ t, ∫ x in u t..v t, f x ∂μ + (μ (Ioc (v t) (u t))).to_real • c)
(λ t, (μ $ Ioc (v t) (u t)).to_real) lt :=
measure_integral_sub_linear_is_o_of_tendsto_ae_of_ge' hfm hf (FTC_filter.finite_at_inner l)
hu hv huv
end
variables [order_topology α] [borel_space α]
local attribute [instance] FTC_filter.meas_gen
variables [FTC_filter a la la'] [FTC_filter b lb lb'] [is_locally_finite_measure μ]
/-- Fundamental theorem of calculus-1, strict derivative in both limits for a locally finite
measure.
Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s
around `a`; let `(lb, lb')` be a pair of `FTC_filter`s around `b`. Suppose that `f` has finite
limits `ca` and `cb` at `la' ⊓ μ.ae` and `lb' ⊓ μ.ae`, respectively.
Then `∫ x in va..vb, f x ∂μ - ∫ x in ua..ub, f x ∂μ =
∫ x in ub..vb, cb ∂μ - ∫ x in ua..va, ca ∂μ +
o(∥∫ x in ua..va, (1:ℝ) ∂μ∥ + ∥∫ x in ub..vb, (1:ℝ) ∂μ∥)`
as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`.
-/
lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae
(hab : interval_integrable f μ a b)
(hmeas_a : measurable_at_filter f la' μ) (hmeas_b : measurable_at_filter f lb' μ)
(ha_lim : tendsto f (la' ⊓ μ.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ μ.ae) (𝓝 cb))
(hua : tendsto ua lt la) (hva : tendsto va lt la)
(hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) :
is_o (λ t, (∫ x in va t..vb t, f x ∂μ) - (∫ x in ua t..ub t, f x ∂μ) -
(∫ x in ub t..vb t, cb ∂μ - ∫ x in ua t..va t, ca ∂μ))
(λ t, ∥∫ x in ua t..va t, (1:ℝ) ∂μ∥ + ∥∫ x in ub t..vb t, (1:ℝ) ∂μ∥) lt :=
begin
refine
((measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_a ha_lim hua hva).neg_left.add_add
(measure_integral_sub_linear_is_o_of_tendsto_ae hmeas_b hb_lim hub hvb)).congr'
_ eventually_eq.rfl,
have A : ∀ᶠ t in lt, interval_integrable f μ (ua t) (va t) :=
ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la) hua hva,
have A' : ∀ᶠ t in lt, interval_integrable f μ a (ua t) :=
ha_lim.eventually_interval_integrable_ae hmeas_a (FTC_filter.finite_at_inner la)
(tendsto_const_pure.mono_right FTC_filter.pure_le) hua,
have B : ∀ᶠ t in lt, interval_integrable f μ (ub t) (vb t) :=
hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb) hub hvb,
have B' : ∀ᶠ t in lt, interval_integrable f μ b (ub t) :=
hb_lim.eventually_interval_integrable_ae hmeas_b (FTC_filter.finite_at_inner lb)
(tendsto_const_pure.mono_right FTC_filter.pure_le) hub,
filter_upwards [A, A', B, B'] with _ ua_va a_ua ub_vb b_ub,
rw [← integral_interval_sub_interval_comm'],
{ dsimp only [], abel, },
exacts [ub_vb, ua_va, b_ub.symm.trans $ hab.symm.trans a_ua]
end
/-- Fundamental theorem of calculus-1, strict derivative in right endpoint for a locally finite
measure.
Let `f` be a measurable function integrable on `a..b`. Let `(lb, lb')` be a pair of `FTC_filter`s
around `b`. Suppose that `f` has a finite limit `c` at `lb' ⊓ μ.ae`.
Then `∫ x in a..v, f x ∂μ - ∫ x in a..u, f x ∂μ = ∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)`
as `u` and `v` tend to `lb`.
-/
lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right
(hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f lb' μ)
(hf : tendsto f (lb' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) :
is_o (λ t, ∫ x in a..v t, f x ∂μ - ∫ x in a..u t, f x ∂μ - ∫ x in u t..v t, c ∂μ)
(λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt :=
by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae
hab measurable_at_bot hmeas ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left)
hf (tendsto_const_pure : tendsto _ _ (pure a)) tendsto_const_pure hu hv
/-- Fundamental theorem of calculus-1, strict derivative in left endpoint for a locally finite
measure.
Let `f` be a measurable function integrable on `a..b`. Let `(la, la')` be a pair of `FTC_filter`s
around `a`. Suppose that `f` has a finite limit `c` at `la' ⊓ μ.ae`.
Then `∫ x in v..b, f x ∂μ - ∫ x in u..b, f x ∂μ = -∫ x in u..v, c ∂μ + o(∫ x in u..v, (1:ℝ) ∂μ)`
as `u` and `v` tend to `la`.
-/
lemma measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left
(hab : interval_integrable f μ a b) (hmeas : measurable_at_filter f la' μ)
(hf : tendsto f (la' ⊓ μ.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) :
is_o (λ t, ∫ x in v t..b, f x ∂μ - ∫ x in u t..b, f x ∂μ + ∫ x in u t..v t, c ∂μ)
(λ t, ∫ x in u t..v t, (1:ℝ) ∂μ) lt :=
by simpa using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae
hab hmeas measurable_at_bot hf ((tendsto_bot : tendsto _ ⊥ (𝓝 0)).mono_left inf_le_left)
hu hv (tendsto_const_pure : tendsto _ _ (pure b)) tendsto_const_pure
end
/-!
### Fundamental theorem of calculus-1 for Lebesgue measure
In this section we restate theorems from the previous section for Lebesgue measure.
In particular, we prove that `∫ x in u..v, f x` is strictly differentiable in `(u, v)`
at `(a, b)` provided that `f` is integrable on `a..b` and is continuous at `a` and `b`.
-/
variables {f : ℝ → E} {c ca cb : E} {l l' la la' lb lb' : filter ℝ} {lt : filter β}
{a b z : ℝ} {u v ua ub va vb : β → ℝ} [FTC_filter a la la'] [FTC_filter b lb lb']
/-!
#### Auxiliary `is_o` statements
In this section we prove several lemmas that can be interpreted as strict differentiability of
`(u, v) ↦ ∫ x in u..v, f x ∂μ` in `u` and/or `v` at a filter. The statements use `is_o` because
we have no definition of `has_strict_(f)deriv_at_filter` in the library.
-/
/-- Fundamental theorem of calculus-1, local version. If `f` has a finite limit `c` almost surely at
`l'`, where `(l, l')` is an `FTC_filter` pair around `a`, then
`∫ x in u..v, f x ∂μ = (v - u) • c + o (v - u)` as both `u` and `v` tend to `l`. -/
lemma integral_sub_linear_is_o_of_tendsto_ae [FTC_filter a l l']
(hfm : measurable_at_filter f l') (hf : tendsto f (l' ⊓ volume.ae) (𝓝 c))
{u v : β → ℝ} (hu : tendsto u lt l) (hv : tendsto v lt l) :
is_o (λ t, (∫ x in u t..v t, f x) - (v t - u t) • c) (v - u) lt :=
by simpa [integral_const] using measure_integral_sub_linear_is_o_of_tendsto_ae hfm hf hu hv
/-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints.
If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair around
`a`, and `(lb, lb')` is an `FTC_filter` pair around `b`, and `f` has finite limits `ca` and `cb`
almost surely at `la'` and `lb'`, respectively, then
`(∫ x in va..vb, f x) - ∫ x in ua..ub, f x = (vb - ub) • cb - (va - ua) • ca +
o(∥va - ua∥ + ∥vb - ub∥)` as `ua` and `va` tend to `la` while `ub` and `vb` tend to `lb`.
This lemma could've been formulated using `has_strict_fderiv_at_filter` if we had this
definition. -/
lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae
(hab : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f la') (hmeas_b : measurable_at_filter f lb')
(ha_lim : tendsto f (la' ⊓ volume.ae) (𝓝 ca)) (hb_lim : tendsto f (lb' ⊓ volume.ae) (𝓝 cb))
(hua : tendsto ua lt la) (hva : tendsto va lt la)
(hub : tendsto ub lt lb) (hvb : tendsto vb lt lb) :
is_o (λ t, (∫ x in va t..vb t, f x) - (∫ x in ua t..ub t, f x) -
((vb t - ub t) • cb - (va t - ua t) • ca)) (λ t, ∥va t - ua t∥ + ∥vb t - ub t∥) lt :=
by simpa [integral_const]
using measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae hab hmeas_a hmeas_b
ha_lim hb_lim hua hva hub hvb
/-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints.
If `f` is a measurable function integrable on `a..b`, `(lb, lb')` is an `FTC_filter` pair
around `b`, and `f` has a finite limit `c` almost surely at `lb'`, then
`(∫ x in a..v, f x) - ∫ x in a..u, f x = (v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `lb`.
This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/
lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right
(hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f lb')
(hf : tendsto f (lb' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt lb) (hv : tendsto v lt lb) :
is_o (λ t, (∫ x in a..v t, f x) - (∫ x in a..u t, f x) - (v t - u t) • c) (v - u) lt :=
by simpa only [integral_const, smul_eq_mul, mul_one] using
measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hab hmeas hf hu hv
/-- Fundamental theorem of calculus-1, strict differentiability at filter in both endpoints.
If `f` is a measurable function integrable on `a..b`, `(la, la')` is an `FTC_filter` pair
around `a`, and `f` has a finite limit `c` almost surely at `la'`, then
`(∫ x in v..b, f x) - ∫ x in u..b, f x = -(v - u) • c + o(∥v - u∥)` as `u` and `v` tend to `la`.
This lemma could've been formulated using `has_strict_deriv_at_filter` if we had this definition. -/
lemma integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left
(hab : interval_integrable f volume a b) (hmeas : measurable_at_filter f la')
(hf : tendsto f (la' ⊓ volume.ae) (𝓝 c)) (hu : tendsto u lt la) (hv : tendsto v lt la) :
is_o (λ t, (∫ x in v t..b, f x) - (∫ x in u t..b, f x) + (v t - u t) • c) (v - u) lt :=
by simpa only [integral_const, smul_eq_mul, mul_one] using
measure_integral_sub_integral_sub_linear_is_o_of_tendsto_ae_left hab hmeas hf hu hv
open continuous_linear_map (fst snd smul_right sub_apply smul_right_apply coe_fst' coe_snd' map_sub)
/-!
#### Strict differentiability
In this section we prove that for a measurable function `f` integrable on `a..b`,
* `integral_has_strict_fderiv_at_of_tendsto_ae`: the function `(u, v) ↦ ∫ x in u..v, f x` has
derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)` in the sense of strict differentiability
provided that `f` tends to `ca` and `cb` almost surely as `x` tendsto to `a` and `b`,
respectively;
* `integral_has_strict_fderiv_at`: the function `(u, v) ↦ ∫ x in u..v, f x` has
derivative `(u, v) ↦ v • f b - u • f a` at `(a, b)` in the sense of strict differentiability
provided that `f` is continuous at `a` and `b`;
* `integral_has_strict_deriv_at_of_tendsto_ae_right`: the function `u ↦ ∫ x in a..u, f x` has
derivative `c` at `b` in the sense of strict differentiability provided that `f` tends to `c`
almost surely as `x` tends to `b`;
* `integral_has_strict_deriv_at_right`: the function `u ↦ ∫ x in a..u, f x` has derivative `f b` at
`b` in the sense of strict differentiability provided that `f` is continuous at `b`;
* `integral_has_strict_deriv_at_of_tendsto_ae_left`: the function `u ↦ ∫ x in u..b, f x` has
derivative `-c` at `a` in the sense of strict differentiability provided that `f` tends to `c`
almost surely as `x` tends to `a`;
* `integral_has_strict_deriv_at_left`: the function `u ↦ ∫ x in u..b, f x` has derivative `-f a` at
`a` in the sense of strict differentiability provided that `f` is continuous at `a`.
-/
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite
limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then
`(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`
in the sense of strict differentiability. -/
lemma integral_has_strict_fderiv_at_of_tendsto_ae
(hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) :
has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) :=
begin
have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb
((continuous_fst.comp continuous_snd).tendsto ((a, b), (a, b)))
((continuous_fst.comp continuous_fst).tendsto ((a, b), (a, b)))
((continuous_snd.comp continuous_snd).tendsto ((a, b), (a, b)))
((continuous_snd.comp continuous_fst).tendsto ((a, b), (a, b))),
refine (this.congr_left _).trans_is_O _,
{ intro x, simp [sub_smul] },
{ exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left }
end
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca`
at `(a, b)` in the sense of strict differentiability. -/
lemma integral_has_strict_fderiv_at
(hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : continuous_at f a) (hb : continuous_at f b) :
has_strict_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) :=
integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b
(ha.mono_left inf_le_left) (hb.mono_left inf_le_left)
/-- **First Fundamental Theorem of Calculus**: if `f : ℝ → E` is integrable on `a..b` and `f x` has
a finite limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b` in
the sense of strict differentiability. -/
lemma integral_has_strict_deriv_at_of_tendsto_ae_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) c b :=
integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb continuous_at_snd
continuous_at_fst
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b` in the sense of strict
differentiability. -/
lemma integral_has_strict_deriv_at_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : continuous_at f b) : has_strict_deriv_at (λ u, ∫ x in a..u, f x) (f b) b :=
integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left)
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a` in the sense
of strict differentiability. -/
lemma integral_has_strict_deriv_at_of_tendsto_ae_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-c) a :=
by simpa only [← integral_symm]
using (integral_has_strict_deriv_at_of_tendsto_ae_right hf.symm hmeas ha).neg
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a` in the sense of strict
differentiability. -/
lemma integral_has_strict_deriv_at_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(ha : continuous_at f a) : has_strict_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a :=
by simpa only [← integral_symm] using (integral_has_strict_deriv_at_right hf.symm hmeas ha).neg
/-!
#### Fréchet differentiability
In this subsection we restate results from the previous subsection in terms of `has_fderiv_at`,
`has_deriv_at`, `fderiv`, and `deriv`.
-/
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite
limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then
`(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca` at `(a, b)`. -/
lemma integral_has_fderiv_at_of_tendsto_ae (hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) :
has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (a, b) :=
(integral_has_strict_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).has_fderiv_at
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a` and `b`, then `(u, v) ↦ ∫ x in u..v, f x` has derivative `(u, v) ↦ v • cb - u • ca`
at `(a, b)`. -/
lemma integral_has_fderiv_at (hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : continuous_at f a) (hb : continuous_at f b) :
has_fderiv_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (a, b) :=
(integral_has_strict_fderiv_at hf hmeas_a hmeas_b ha hb).has_fderiv_at
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has finite
limits `ca` and `cb` almost surely as `x` tends to `a` and `b`, respectively, then `fderiv`
derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦ v • cb - u • ca`. -/
lemma fderiv_integral_of_tendsto_ae (hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 cb)) :
fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) =
(snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca :=
(integral_has_fderiv_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a` and `b`, then `fderiv` derivative of `(u, v) ↦ ∫ x in u..v, f x` at `(a, b)` equals `(u, v) ↦
v • cb - u • ca`. -/
lemma fderiv_integral (hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f (𝓝 a)) (hmeas_b : measurable_at_filter f (𝓝 b))
(ha : continuous_at f a) (hb : continuous_at f b) :
fderiv ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (a, b) =
(snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a) :=
(integral_has_fderiv_at hf hmeas_a hmeas_b ha hb).fderiv
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `c` at `b`. -/
lemma integral_has_deriv_at_of_tendsto_ae_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in a..u, f x) c b :=
(integral_has_strict_deriv_at_of_tendsto_ae_right hf hmeas hb).has_deriv_at
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `b`, then `u ↦ ∫ x in a..u, f x` has derivative `f b` at `b`. -/
lemma integral_has_deriv_at_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : continuous_at f b) : has_deriv_at (λ u, ∫ x in a..u, f x) (f b) b :=
(integral_has_strict_deriv_at_right hf hmeas hb).has_deriv_at
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite
limit `c` almost surely at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/
lemma deriv_integral_of_tendsto_ae_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : tendsto f (𝓝 b ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in a..u, f x) b = c :=
(integral_has_deriv_at_of_tendsto_ae_right hf hmeas hb).deriv
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `b`, then the derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/
lemma deriv_integral_right
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 b))
(hb : continuous_at f b) :
deriv (λ u, ∫ x in a..u, f x) b = f b :=
(integral_has_deriv_at_right hf hmeas hb).deriv
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-c` at `a`. -/
lemma integral_has_deriv_at_of_tendsto_ae_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(ha : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : has_deriv_at (λ u, ∫ x in u..b, f x) (-c) a :=
(integral_has_strict_deriv_at_of_tendsto_ae_left hf hmeas ha).has_deriv_at
/-- Fundamental theorem of calculus-1: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a`, then `u ↦ ∫ x in u..b, f x` has derivative `-f a` at `a`. -/
lemma integral_has_deriv_at_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(ha : continuous_at f a) :
has_deriv_at (λ u, ∫ x in u..b, f x) (-f a) a :=
(integral_has_strict_deriv_at_left hf hmeas ha).has_deriv_at
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` has a finite
limit `c` almost surely at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/
lemma deriv_integral_of_tendsto_ae_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(hb : tendsto f (𝓝 a ⊓ volume.ae) (𝓝 c)) : deriv (λ u, ∫ x in u..b, f x) a = -c :=
(integral_has_deriv_at_of_tendsto_ae_left hf hmeas hb).deriv
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f` is continuous
at `a`, then the derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/
lemma deriv_integral_left
(hf : interval_integrable f volume a b) (hmeas : measurable_at_filter f (𝓝 a))
(hb : continuous_at f a) :
deriv (λ u, ∫ x in u..b, f x) a = -f a :=
(integral_has_deriv_at_left hf hmeas hb).deriv
/-!
#### One-sided derivatives
-/
/-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x`
has derivative `(u, v) ↦ v • cb - u • ca` within `s × t` at `(a, b)`, where
`s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to `ca`
and `cb` almost surely at the filters `la` and `lb` from the following table.
| `s` | `la` | `t` | `lb` |
| ------- | ---- | --- | ---- |
| `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` |
| `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` |
| `{a}` | `⊥` | `{b}` | `⊥` |
| `univ` | `𝓝 a` | `univ` | `𝓝 b` |
-/
lemma integral_has_fderiv_within_at_of_tendsto_ae
(hf : interval_integrable f volume a b)
{s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb]
(hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb)
(ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb)) :
has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) (s ×ˢ t) (a, b) :=
begin
rw [has_fderiv_within_at, nhds_within_prod_eq],
have := integral_sub_integral_sub_linear_is_o_of_tendsto_ae hf hmeas_a hmeas_b ha hb
(tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[s] a)) tendsto_fst
(tendsto_const_pure.mono_right FTC_filter.pure_le : tendsto _ _ (𝓝[t] b)) tendsto_snd,
refine (this.congr_left _).trans_is_O _,
{ intro x, simp [sub_smul] },
{ exact is_O_fst_prod.norm_left.add is_O_snd_prod.norm_left }
end
/-- Let `f` be a measurable function integrable on `a..b`. The function `(u, v) ↦ ∫ x in u..v, f x`
has derivative `(u, v) ↦ v • f b - u • f a` within `s × t` at `(a, b)`, where
`s ∈ {Iic a, {a}, Ici a, univ}` and `t ∈ {Iic b, {b}, Ici b, univ}` provided that `f` tends to
`f a` and `f b` at the filters `la` and `lb` from the following table. In most cases this assumption
is definitionally equal `continuous_at f _` or `continuous_within_at f _ _`.
| `s` | `la` | `t` | `lb` |
| ------- | ---- | --- | ---- |
| `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` |
| `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` |
| `{a}` | `⊥` | `{b}` | `⊥` |
| `univ` | `𝓝 a` | `univ` | `𝓝 b` |
-/
lemma integral_has_fderiv_within_at
(hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb)
{s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb]
(ha : tendsto f la (𝓝 $ f a)) (hb : tendsto f lb (𝓝 $ f b)) :
has_fderiv_within_at (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x)
((snd ℝ ℝ ℝ).smul_right (f b) - (fst ℝ ℝ ℝ).smul_right (f a)) (s ×ˢ t) (a, b) :=
integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b (ha.mono_left inf_le_left)
(hb.mono_left inf_le_left)
/-- An auxiliary tactic closing goals `unique_diff_within_at ℝ s a` where
`s ∈ {Iic a, Ici a, univ}`. -/
meta def unique_diff_within_at_Ici_Iic_univ : tactic unit :=
`[apply_rules [unique_diff_on.unique_diff_within_at, unique_diff_on_Ici, unique_diff_on_Iic,
left_mem_Ici, right_mem_Iic, unique_diff_within_at_univ]]
/-- Let `f` be a measurable function integrable on `a..b`. Choose `s ∈ {Iic a, Ici a, univ}`
and `t ∈ {Iic b, Ici b, univ}`. Suppose that `f` tends to `ca` and `cb` almost surely at the filters
`la` and `lb` from the table below. Then `fderiv_within ℝ (λ p, ∫ x in p.1..p.2, f x) (s ×ˢ t)`
is equal to `(u, v) ↦ u • cb - v • ca`.
| `s` | `la` | `t` | `lb` |
| ------- | ---- | --- | ---- |
| `Iic a` | `𝓝[≤] a` | `Iic b` | `𝓝[≤] b` |
| `Ici a` | `𝓝[>] a` | `Ici b` | `𝓝[>] b` |
| `{a}` | `⊥` | `{b}` | `⊥` |
| `univ` | `𝓝 a` | `univ` | `𝓝 b` |
-/
lemma fderiv_within_integral_of_tendsto_ae
(hf : interval_integrable f volume a b)
(hmeas_a : measurable_at_filter f la) (hmeas_b : measurable_at_filter f lb)
{s t : set ℝ} [FTC_filter a (𝓝[s] a) la] [FTC_filter b (𝓝[t] b) lb]
(ha : tendsto f (la ⊓ volume.ae) (𝓝 ca)) (hb : tendsto f (lb ⊓ volume.ae) (𝓝 cb))
(hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ)
(ht : unique_diff_within_at ℝ t b . unique_diff_within_at_Ici_Iic_univ) :
fderiv_within ℝ (λ p : ℝ × ℝ, ∫ x in p.1..p.2, f x) (s ×ˢ t) (a, b) =
((snd ℝ ℝ ℝ).smul_right cb - (fst ℝ ℝ ℝ).smul_right ca) :=
(integral_has_fderiv_within_at_of_tendsto_ae hf hmeas_a hmeas_b ha hb).fderiv_within $ hs.prod ht
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely as `x` tends to `b` from the right or from the left,
then `u ↦ ∫ x in a..u, f x` has right (resp., left) derivative `c` at `b`. -/
lemma integral_has_deriv_within_at_of_tendsto_ae_right
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)]
(hmeas : measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c)) :
has_deriv_within_at (λ u, ∫ x in a..u, f x) c s b :=
integral_sub_integral_sub_linear_is_o_of_tendsto_ae_right hf hmeas hb
(tendsto_const_pure.mono_right FTC_filter.pure_le) tendsto_id
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous
from the left or from the right at `b`, then `u ↦ ∫ x in a..u, f x` has left (resp., right)
derivative `f b` at `b`. -/
lemma integral_has_deriv_within_at_right
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)]
(hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b) :
has_deriv_within_at (λ u, ∫ x in a..u, f x) (f b) s b :=
integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas (hb.mono_left inf_le_left)
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely as `x` tends to `b` from the right or from the left, then the right
(resp., left) derivative of `u ↦ ∫ x in a..u, f x` at `b` equals `c`. -/
lemma deriv_within_integral_of_tendsto_ae_right
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)]
(hmeas: measurable_at_filter f (𝓝[t] b)) (hb : tendsto f (𝓝[t] b ⊓ volume.ae) (𝓝 c))
(hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) :
deriv_within (λ u, ∫ x in a..u, f x) s b = c :=
(integral_has_deriv_within_at_of_tendsto_ae_right hf hmeas hb).deriv_within hs
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous
on the right or on the left at `b`, then the right (resp., left) derivative of
`u ↦ ∫ x in a..u, f x` at `b` equals `f b`. -/
lemma deriv_within_integral_right
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter b (𝓝[s] b) (𝓝[t] b)]
(hmeas : measurable_at_filter f (𝓝[t] b)) (hb : continuous_within_at f t b)
(hs : unique_diff_within_at ℝ s b . unique_diff_within_at_Ici_Iic_univ) :
deriv_within (λ u, ∫ x in a..u, f x) s b = f b :=
(integral_has_deriv_within_at_right hf hmeas hb).deriv_within hs
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely as `x` tends to `a` from the right or from the left,
then `u ↦ ∫ x in u..b, f x` has right (resp., left) derivative `-c` at `a`. -/
lemma integral_has_deriv_within_at_of_tendsto_ae_left
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)]
(hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c)) :
has_deriv_within_at (λ u, ∫ x in u..b, f x) (-c) s a :=
by { simp only [integral_symm b],
exact (integral_has_deriv_within_at_of_tendsto_ae_right hf.symm hmeas ha).neg }
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous
from the left or from the right at `a`, then `u ↦ ∫ x in u..b, f x` has left (resp., right)
derivative `-f a` at `a`. -/
lemma integral_has_deriv_within_at_left
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)]
(hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a) :
has_deriv_within_at (λ u, ∫ x in u..b, f x) (-f a) s a :=
integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas (ha.mono_left inf_le_left)
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` has a finite
limit `c` almost surely as `x` tends to `a` from the right or from the left, then the right
(resp., left) derivative of `u ↦ ∫ x in u..b, f x` at `a` equals `-c`. -/
lemma deriv_within_integral_of_tendsto_ae_left
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)]
(hmeas : measurable_at_filter f (𝓝[t] a)) (ha : tendsto f (𝓝[t] a ⊓ volume.ae) (𝓝 c))
(hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) :
deriv_within (λ u, ∫ x in u..b, f x) s a = -c :=
(integral_has_deriv_within_at_of_tendsto_ae_left hf hmeas ha).deriv_within hs
/-- Fundamental theorem of calculus: if `f : ℝ → E` is integrable on `a..b` and `f x` is continuous
on the right or on the left at `a`, then the right (resp., left) derivative of
`u ↦ ∫ x in u..b, f x` at `a` equals `-f a`. -/
lemma deriv_within_integral_left
(hf : interval_integrable f volume a b) {s t : set ℝ} [FTC_filter a (𝓝[s] a) (𝓝[t] a)]
(hmeas : measurable_at_filter f (𝓝[t] a)) (ha : continuous_within_at f t a)
(hs : unique_diff_within_at ℝ s a . unique_diff_within_at_Ici_Iic_univ) :
deriv_within (λ u, ∫ x in u..b, f x) s a = -f a :=
(integral_has_deriv_within_at_left hf hmeas ha).deriv_within hs
/-- The integral of a continuous function is differentiable on a real set `s`. -/
theorem differentiable_on_integral_of_continuous {s : set ℝ}
(hintg : ∀ x ∈ s, interval_integrable f volume a x) (hcont : continuous f) :
differentiable_on ℝ (λ u, ∫ x in a..u, f x) s :=
λ y hy, (integral_has_deriv_at_right (hintg y hy)
hcont.measurable.ae_measurable.measurable_at_filter
hcont.continuous_at) .differentiable_at.differentiable_within_at
/-!
### Fundamental theorem of calculus, part 2
This section contains theorems pertaining to FTC-2 for interval integrals, i.e., the assertion
that `∫ x in a..b, f' x = f b - f a` under suitable assumptions.
The most classical version of this theorem assumes that `f'` is continuous. However, this is
unnecessarily strong: the result holds if `f'` is just integrable. We prove the strong version,
following [Rudin, *Real and Complex Analysis* (Theorem 7.21)][rudin2006real]. The proof is first
given for real-valued functions, and then deduced for functions with a general target space. For
a real-valued function `g`, it suffices to show that `g b - g a ≤ (∫ x in a..b, g' x) + ε` for all
positive `ε`. To prove this, choose a lower-semicontinuous function `G'` with `g' < G'` and with
integral close to that of `g'` (its existence is guaranteed by the Vitali-Carathéodory theorem).
It satisfies `g t - g a ≤ ∫ x in a..t, G' x` for all `t ∈ [a, b]`: this inequality holds at `a`,
and if it holds at `t` then it holds for `u` close to `t` on its right, as the left hand side
increases by `g u - g t ∼ (u -t) g' t`, while the right hand side increases by
`∫ x in t..u, G' x` which is roughly at least `∫ x in t..u, G' t = (u - t) G' t`, by lower
semicontinuity. As `g' t < G' t`, this gives the conclusion. One can therefore push progressively
this inequality to the right until the point `b`, where it gives the desired conclusion.
-/
variables {g' g : ℝ → ℝ}
/-- Hard part of FTC-2 for integrable derivatives, real-valued functions: one has
`g b - g a ≤ ∫ y in a..b, g' y`.
Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/
lemma sub_le_integral_of_has_deriv_right_of_le (hab : a ≤ b)
(hcont : continuous_on g (Icc a b))
(hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x)
(g'int : integrable_on g' (Icc a b)) :
g b - g a ≤ ∫ y in a..b, g' y :=
begin
refine le_of_forall_pos_le_add (λ ε εpos, _),
-- Bound from above `g'` by a lower-semicontinuous function `G'`.
rcases exists_lt_lower_semicontinuous_integral_lt g' g'int εpos with
⟨G', g'_lt_G', G'cont, G'int, G'lt_top, hG'⟩,
-- we will show by "induction" that `g t - g a ≤ ∫ u in a..t, G' u` for all `t ∈ [a, b]`.
set s := {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real} ∩ Icc a b,
-- the set `s` of points where this property holds is closed.
have s_closed : is_closed s,
{ have : continuous_on (λ t, (g t - g a, ∫ u in a..t, (G' u).to_real)) (Icc a b),
{ rw ← interval_of_le hab at G'int ⊢ hcont,
exact (hcont.sub continuous_on_const).prod (continuous_on_primitive_interval G'int) },
simp only [s, inter_comm],
exact this.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' },
have main : Icc a b ⊆ {t | g t - g a ≤ ∫ u in a..t, (G' u).to_real },
{ -- to show that the set `s` is all `[a, b]`, it suffices to show that any point `t` in `s`
-- with `t < b` admits another point in `s` slightly to its right
-- (this is a sort of real induction).
apply s_closed.Icc_subset_of_forall_exists_gt
(by simp only [integral_same, mem_set_of_eq, sub_self]) (λ t ht v t_lt_v, _),
obtain ⟨y, g'_lt_y', y_lt_G'⟩ : ∃ (y : ℝ), (g' t : ereal) < y ∧ (y : ereal) < G' t :=
ereal.lt_iff_exists_real_btwn.1 (g'_lt_G' t),
-- bound from below the increase of `∫ x in a..u, G' x` on the right of `t`, using the lower
-- semicontinuity of `G'`.
have I1 : ∀ᶠ u in 𝓝[>] t, (u - t) * y ≤ ∫ w in t..u, (G' w).to_real,
{ have B : ∀ᶠ u in 𝓝 t, (y : ereal) < G' u :=
G'cont.lower_semicontinuous_at _ _ y_lt_G',
rcases mem_nhds_iff_exists_Ioo_subset.1 B with ⟨m, M, ⟨hm, hM⟩, H⟩,
have : Ioo t (min M b) ∈ 𝓝[>] t := mem_nhds_within_Ioi_iff_exists_Ioo_subset.2
⟨min M b, by simp only [hM, ht.right.right, lt_min_iff, mem_Ioi, and_self], subset.refl _⟩,
filter_upwards [this] with u hu,
have I : Icc t u ⊆ Icc a b := Icc_subset_Icc ht.2.1 (hu.2.le.trans (min_le_right _ _)),
calc (u - t) * y = ∫ v in Icc t u, y :
by simp only [hu.left.le, measure_theory.integral_const, algebra.id.smul_eq_mul, sub_nonneg,
measurable_set.univ, real.volume_Icc, measure.restrict_apply, univ_inter,
ennreal.to_real_of_real]
... ≤ ∫ w in t..u, (G' w).to_real :
begin
rw [interval_integral.integral_of_le hu.1.le, ← integral_Icc_eq_integral_Ioc],
apply set_integral_mono_ae_restrict,
{ simp only [integrable_on_const, real.volume_Icc, ennreal.of_real_lt_top, or_true] },
{ exact integrable_on.mono_set G'int I },
{ have C1 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), G' x < ⊤ :=
ae_mono (measure.restrict_mono I le_rfl) G'lt_top,
have C2 : ∀ᵐ (x : ℝ) ∂volume.restrict (Icc t u), x ∈ Icc t u :=
ae_restrict_mem measurable_set_Icc,
filter_upwards [C1, C2] with x G'x hx,
apply ereal.coe_le_coe_iff.1,
have : x ∈ Ioo m M, by simp only [hm.trans_le hx.left,
(hx.right.trans_lt hu.right).trans_le (min_le_left M b), mem_Ioo, and_self],
convert le_of_lt (H this),
exact ereal.coe_to_real G'x.ne (ne_bot_of_gt (g'_lt_G' x)) }
end },
-- bound from above the increase of `g u - g a` on the right of `t`, using the derivative at `t`
have I2 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ (u - t) * y,
{ have g'_lt_y : g' t < y := ereal.coe_lt_coe_iff.1 g'_lt_y',
filter_upwards [(hderiv t ⟨ht.2.1, ht.2.2⟩).limsup_slope_le'
(not_mem_Ioi.2 le_rfl) g'_lt_y, self_mem_nhds_within] with u hu t_lt_u,
have := mul_le_mul_of_nonneg_left hu.le (sub_pos.2 t_lt_u).le,
rwa [← smul_eq_mul, sub_smul_slope] at this },
-- combine the previous two bounds to show that `g u - g a` increases less quickly than
-- `∫ x in a..u, G' x`.
have I3 : ∀ᶠ u in 𝓝[>] t, g u - g t ≤ ∫ w in t..u, (G' w).to_real,
{ filter_upwards [I1, I2] with u hu1 hu2 using hu2.trans hu1, },
have I4 : ∀ᶠ u in 𝓝[>] t, u ∈ Ioc t (min v b),
{ refine mem_nhds_within_Ioi_iff_exists_Ioc_subset.2 ⟨min v b, _, subset.refl _⟩,
simp only [lt_min_iff, mem_Ioi],
exact ⟨t_lt_v, ht.2.2⟩ },
-- choose a point `x` slightly to the right of `t` which satisfies the above bound
rcases (I3.and I4).exists with ⟨x, hx, h'x⟩,
-- we check that it belongs to `s`, essentially by construction
refine ⟨x, _, Ioc_subset_Ioc le_rfl (min_le_left _ _) h'x⟩,
calc g x - g a = (g t - g a) + (g x - g t) : by abel
... ≤ (∫ w in a..t, (G' w).to_real) + ∫ w in t..x, (G' w).to_real : add_le_add ht.1 hx
... = ∫ w in a..x, (G' w).to_real :
begin
apply integral_add_adjacent_intervals,
{ rw interval_integrable_iff_integrable_Ioc_of_le ht.2.1,
exact integrable_on.mono_set G'int
(Ioc_subset_Icc_self.trans (Icc_subset_Icc le_rfl ht.2.2.le)) },
{ rw interval_integrable_iff_integrable_Ioc_of_le h'x.1.le,
apply integrable_on.mono_set G'int,
refine Ioc_subset_Icc_self.trans (Icc_subset_Icc ht.2.1 (h'x.2.trans (min_le_right _ _))) }
end },
-- now that we know that `s` contains `[a, b]`, we get the desired result by applying this to `b`.
calc g b - g a ≤ ∫ y in a..b, (G' y).to_real : main (right_mem_Icc.2 hab)
... ≤ (∫ y in a..b, g' y) + ε :
begin
convert hG'.le;
{ rw interval_integral.integral_of_le hab,
simp only [integral_Icc_eq_integral_Ioc', real.volume_singleton] },
end
end
/-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`. -/
lemma integral_le_sub_of_has_deriv_right_of_le (hab : a ≤ b)
(hcont : continuous_on g (Icc a b))
(hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x)
(g'int : integrable_on g' (Icc a b)) :
∫ y in a..b, g' y ≤ g b - g a :=
begin
rw ← neg_le_neg_iff,
convert sub_le_integral_of_has_deriv_right_of_le hab hcont.neg (λ x hx, (hderiv x hx).neg)
g'int.neg,
{ abel },
{ simp only [integral_neg] }
end
/-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version -/
lemma integral_eq_sub_of_has_deriv_right_of_le_real (hab : a ≤ b)
(hcont : continuous_on g (Icc a b))
(hderiv : ∀ x ∈ Ico a b, has_deriv_within_at g (g' x) (Ioi x) x)
(g'int : integrable_on g' (Icc a b)) :
∫ y in a..b, g' y = g b - g a :=
le_antisymm
(integral_le_sub_of_has_deriv_right_of_le hab hcont hderiv g'int)
(sub_le_integral_of_has_deriv_right_of_le hab hcont hderiv g'int)
/-- Auxiliary lemma in the proof of `integral_eq_sub_of_has_deriv_right_of_le`: real version, not
requiring differentiability as the left endpoint of the interval. Follows from
`integral_eq_sub_of_has_deriv_right_of_le_real` together with a continuity argument. -/
lemma integral_eq_sub_of_has_deriv_right_of_le_real' (hab : a ≤ b)
(hcont : continuous_on g (Icc a b))
(hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at g (g' x) (Ioi x) x)
(g'int : integrable_on g' (Icc a b)) :
∫ y in a..b, g' y = g b - g a :=
begin
obtain rfl|a_lt_b := hab.eq_or_lt, { simp },
set s := {t | ∫ u in t..b, g' u = g b - g t} ∩ Icc a b,
have s_closed : is_closed s,
{ have : continuous_on (λ t, (∫ u in t..b, g' u, g b - g t)) (Icc a b),
{ rw ← interval_of_le hab at ⊢ hcont g'int,
exact (continuous_on_primitive_interval_left g'int).prod (continuous_on_const.sub hcont) },
simp only [s, inter_comm],
exact this.preimage_closed_of_closed is_closed_Icc is_closed_diagonal, },
have A : closure (Ioc a b) ⊆ s,
{ apply s_closed.closure_subset_iff.2,
assume t ht,
refine ⟨_, ⟨ht.1.le, ht.2⟩⟩,
exact integral_eq_sub_of_has_deriv_right_of_le_real ht.2
(hcont.mono (Icc_subset_Icc ht.1.le le_rfl))
(λ x hx, hderiv x ⟨ht.1.trans_le hx.1, hx.2⟩)
(g'int.mono_set (Icc_subset_Icc ht.1.le le_rfl)) },
rw closure_Ioc a_lt_b.ne at A,
exact (A (left_mem_Icc.2 hab)).1,
end
variable {f' : ℝ → E}
/-- **Fundamental theorem of calculus-2**: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`)
and has a right derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`,
then `∫ y in a..b, f' y` equals `f b - f a`. -/
theorem integral_eq_sub_of_has_deriv_right_of_le (hab : a ≤ b) (hcont : continuous_on f (Icc a b))
(hderiv : ∀ x ∈ Ioo a b, has_deriv_within_at f (f' x) (Ioi x) x)
(f'int : interval_integrable f' volume a b) :
∫ y in a..b, f' y = f b - f a :=
begin
refine (normed_space.eq_iff_forall_dual_eq ℝ).2 (λ g, _),
rw [← g.interval_integral_comp_comm f'int, g.map_sub],
exact integral_eq_sub_of_has_deriv_right_of_le_real' hab (g.continuous.comp_continuous_on hcont)
(λ x hx, g.has_fderiv_at.comp_has_deriv_within_at x (hderiv x hx))
(g.integrable_comp ((interval_integrable_iff_integrable_Icc_of_le hab).1 f'int))
end
/-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` and
has a right derivative at `f' x` for all `x` in `[a, b)`, and `f'` is integrable on `[a, b]` then
`∫ y in a..b, f' y` equals `f b - f a`. -/
theorem integral_eq_sub_of_has_deriv_right (hcont : continuous_on f (interval a b))
(hderiv : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x)
(hint : interval_integrable f' volume a b) :
∫ y in a..b, f' y = f b - f a :=
begin
cases le_total a b with hab hab,
{ simp only [interval_of_le, min_eq_left, max_eq_right, hab] at hcont hderiv hint,
apply integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint },
{ simp only [interval_of_ge, min_eq_right, max_eq_left, hab] at hcont hderiv,
rw [integral_symm, integral_eq_sub_of_has_deriv_right_of_le hab hcont hderiv hint.symm,
neg_sub] }
end
/-- Fundamental theorem of calculus-2: If `f : ℝ → E` is continuous on `[a, b]` (where `a ≤ b`) and
has a derivative at `f' x` for all `x` in `(a, b)`, and `f'` is integrable on `[a, b]`, then
`∫ y in a..b, f' y` equals `f b - f a`. -/
theorem integral_eq_sub_of_has_deriv_at_of_le (hab : a ≤ b)
(hcont : continuous_on f (Icc a b))
(hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b) :
∫ y in a..b, f' y = f b - f a :=
integral_eq_sub_of_has_deriv_right_of_le hab hcont (λ x hx, (hderiv x hx).has_deriv_within_at) hint
/-- Fundamental theorem of calculus-2: If `f : ℝ → E` has a derivative at `f' x` for all `x` in
`[a, b]` and `f'` is integrable on `[a, b]`, then `∫ y in a..b, f' y` equals `f b - f a`. -/
theorem integral_eq_sub_of_has_deriv_at
(hderiv : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(hint : interval_integrable f' volume a b) :
∫ y in a..b, f' y = f b - f a :=
integral_eq_sub_of_has_deriv_right (has_deriv_at.continuous_on hderiv)
(λ x hx, (hderiv _ (mem_Icc_of_Ioo hx)).has_deriv_within_at) hint
theorem integral_eq_sub_of_has_deriv_at_of_tendsto (hab : a < b) {fa fb}
(hderiv : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hint : interval_integrable f' volume a b)
(ha : tendsto f (𝓝[>] a) (𝓝 fa)) (hb : tendsto f (𝓝[<] b) (𝓝 fb)) :
∫ y in a..b, f' y = fb - fa :=
begin
set F : ℝ → E := update (update f a fa) b fb,
have Fderiv : ∀ x ∈ Ioo a b, has_deriv_at F (f' x) x,
{ refine λ x hx, (hderiv x hx).congr_of_eventually_eq _,
filter_upwards [Ioo_mem_nhds hx.1 hx.2] with _ hy, simp only [F],
rw [update_noteq hy.2.ne, update_noteq hy.1.ne'], },
have hcont : continuous_on F (Icc a b),
{ rw [continuous_on_update_iff, continuous_on_update_iff, Icc_diff_right, Ico_diff_left],
refine ⟨⟨λ z hz, (hderiv z hz).continuous_at.continuous_within_at, _⟩, _⟩,
{ exact λ _, ha.mono_left (nhds_within_mono _ Ioo_subset_Ioi_self) },
{ rintro -,
refine (hb.congr' _).mono_left (nhds_within_mono _ Ico_subset_Iio_self),
filter_upwards [Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 hab)]
with _ hz using (update_noteq hz.1.ne' _ _).symm } },
simpa [F, hab.ne, hab.ne'] using integral_eq_sub_of_has_deriv_at_of_le hab.le hcont Fderiv hint
end
/-- Fundamental theorem of calculus-2: If `f : ℝ → E` is differentiable at every `x` in `[a, b]` and
its derivative is integrable on `[a, b]`, then `∫ y in a..b, deriv f y` equals `f b - f a`. -/
theorem integral_deriv_eq_sub (hderiv : ∀ x ∈ interval a b, differentiable_at ℝ f x)
(hint : interval_integrable (deriv f) volume a b) :
∫ y in a..b, deriv f y = f b - f a :=
integral_eq_sub_of_has_deriv_at (λ x hx, (hderiv x hx).has_deriv_at) hint
theorem integral_deriv_eq_sub' (f) (hderiv : deriv f = f')
(hdiff : ∀ x ∈ interval a b, differentiable_at ℝ f x)
(hcont : continuous_on f' (interval a b)) :
∫ y in a..b, f' y = f b - f a :=
begin
rw [← hderiv, integral_deriv_eq_sub hdiff],
rw hderiv,
exact hcont.interval_integrable
end
/-!
### Integration by parts
-/
theorem integral_deriv_mul_eq_sub {u v u' v' : ℝ → ℝ}
(hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x)
(hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x)
(hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) :
∫ x in a..b, u' x * v x + u x * v' x = u b * v b - u a * v a :=
integral_eq_sub_of_has_deriv_at (λ x hx, (hu x hx).mul (hv x hx)) $
(hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add
(hv'.continuous_on_mul ((has_deriv_at.continuous_on hu)))
theorem integral_mul_deriv_eq_deriv_mul {u v u' v' : ℝ → ℝ}
(hu : ∀ x ∈ interval a b, has_deriv_at u (u' x) x)
(hv : ∀ x ∈ interval a b, has_deriv_at v (v' x) x)
(hu' : interval_integrable u' volume a b) (hv' : interval_integrable v' volume a b) :
∫ x in a..b, u x * v' x = u b * v b - u a * v a - ∫ x in a..b, v x * u' x :=
begin
rw [← integral_deriv_mul_eq_sub hu hv hu' hv', ← integral_sub],
{ exact integral_congr (λ x hx, by simp only [mul_comm, add_sub_cancel']) },
{ exact ((hu'.mul_continuous_on (has_deriv_at.continuous_on hv)).add
(hv'.continuous_on_mul (has_deriv_at.continuous_on hu))) },
{ exact hu'.continuous_on_mul (has_deriv_at.continuous_on hv) },
end
/-!
### Integration by substitution / Change of variables
-/
section smul
/--
Change of variables, general form. If `f` is continuous on `[a, b]` and has
continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can
substitute `u = f x` to get `∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`.
We could potentially slightly weaken the conditions, by not requiring that `f'` and `g` are
continuous on the endpoints of these intervals, but in that case we need to additionally assume that
the functions are integrable on that interval.
-/
theorem integral_comp_smul_deriv'' {f f' : ℝ → ℝ} {g : ℝ → E}
(hf : continuous_on f [a, b])
(hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x)
(hf' : continuous_on f' [a, b])
(hg : continuous_on g (f '' [a, b])) :
∫ x in a..b, f' x • (g ∘ f) x= ∫ u in f a..f b, g u :=
begin
have h_cont : continuous_on (λ u, ∫ t in f a..f u, g t) [a, b],
{ rw [hf.image_interval] at hg,
refine (continuous_on_primitive_interval' hg.interval_integrable _).comp hf _,
{ rw [← hf.image_interval], exact mem_image_of_mem f left_mem_interval },
{ rw [← image_subset_iff], exact hf.image_interval.subset } },
have h_der : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at
(λ u, ∫ t in f a..f u, g t) (f' x • ((g ∘ f) x)) (Ioi x) x,
{ intros x hx,
let I := [Inf (f '' [a, b]), Sup (f '' [a, b])],
have hI : f '' [a, b] = I := hf.image_interval,
have h2x : f x ∈ I, { rw [← hI], exact mem_image_of_mem f (Ioo_subset_Icc_self hx) },
have h2g : interval_integrable g volume (f a) (f x),
{ refine (hg.mono $ _).interval_integrable,
exact hf.surj_on_interval left_mem_interval (Ioo_subset_Icc_self hx) },
rw [hI] at hg,
have h3g : measurable_at_filter g (𝓝[I] f x) volume :=
hg.measurable_at_filter_nhds_within measurable_set_Icc (f x),
haveI : fact (f x ∈ I) := ⟨h2x⟩,
have : has_deriv_within_at (λ u, ∫ x in f a..u, g x) (g (f x)) I (f x) :=
integral_has_deriv_within_at_right h2g h3g (hg (f x) h2x),
refine (this.scomp x ((hff' x hx).Ioo_of_Ioi hx.2) _).Ioi_of_Ioo hx.2,
rw ← hI,
exact (maps_to_image _ _).mono (Ioo_subset_Icc_self.trans $ Icc_subset_Icc_left hx.1.le)
subset.rfl },
have h_int : interval_integrable (λ (x : ℝ), f' x • (g ∘ f) x) volume a b :=
(hf'.smul (hg.comp hf $ subset_preimage_image f _)).interval_integrable,
simp_rw [integral_eq_sub_of_has_deriv_right h_cont h_der h_int, integral_same, sub_zero],
end
/--
Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`,
and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get
`∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`.
Compared to `interval_integral.integral_comp_smul_deriv` we only require that `g` is continuous on
`f '' [a, b]`.
-/
theorem integral_comp_smul_deriv' {f f' : ℝ → ℝ} {g : ℝ → E}
(h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) :
∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x :=
integral_comp_smul_deriv'' (λ x hx, (h x hx).continuous_at.continuous_within_at)
(λ x hx, (h x $ Ioo_subset_Icc_self hx).has_deriv_within_at) h' hg
/--
Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`,
and `g` is continuous, then we can substitute `u = f x` to get
`∫ x in a..b, f' x • (g ∘ f) x = ∫ u in f a..f b, g u`.
-/
theorem integral_comp_smul_deriv {f f' : ℝ → ℝ} {g : ℝ → E}
(h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(h' : continuous_on f' (interval a b)) (hg : continuous g) :
∫ x in a..b, f' x • (g ∘ f) x = ∫ x in f a..f b, g x :=
integral_comp_smul_deriv' h h' hg.continuous_on
theorem integral_deriv_comp_smul_deriv' {f f' : ℝ → ℝ} {g g' : ℝ → E}
(hf : continuous_on f [a, b])
(hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x)
(hf' : continuous_on f' [a, b])
(hg : continuous_on g [f a, f b])
(hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x)
(hg' : continuous_on g' (f '' [a, b])) :
∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a :=
begin
rw [integral_comp_smul_deriv'' hf hff' hf' hg',
integral_eq_sub_of_has_deriv_right hg hgg' (hg'.mono _).interval_integrable],
exact intermediate_value_interval hf
end
theorem integral_deriv_comp_smul_deriv {f f' : ℝ → ℝ} {g g' : ℝ → E}
(hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x))
(hf' : continuous_on f' (interval a b)) (hg' : continuous g') :
∫ x in a..b, f' x • (g' ∘ f) x = (g ∘ f) b - (g ∘ f) a :=
integral_eq_sub_of_has_deriv_at (λ x hx, (hg x hx).scomp x $ hf x hx)
(hf'.smul (hg'.comp_continuous_on $ has_deriv_at.continuous_on hf)).interval_integrable
end smul
section mul
/--
Change of variables, general form for scalar functions. If `f` is continuous on `[a, b]` and has
continuous right-derivative `f'` in `(a, b)`, and `g` is continuous on `f '' [a, b]` then we can
substitute `u = f x` to get `∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`.
-/
theorem integral_comp_mul_deriv'' {f f' g : ℝ → ℝ}
(hf : continuous_on f [a, b])
(hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x)
(hf' : continuous_on f' [a, b])
(hg : continuous_on g (f '' [a, b])) :
∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u :=
by simpa [mul_comm] using integral_comp_smul_deriv'' hf hff' hf' hg
/--
Change of variables. If `f` is has continuous derivative `f'` on `[a, b]`,
and `g` is continuous on `f '' [a, b]`, then we can substitute `u = f x` to get
`∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`.
Compared to `interval_integral.integral_comp_mul_deriv` we only require that `g` is continuous on
`f '' [a, b]`.
-/
theorem integral_comp_mul_deriv' {f f' g : ℝ → ℝ}
(h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(h' : continuous_on f' (interval a b)) (hg : continuous_on g (f '' [a, b])) :
∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x :=
by simpa [mul_comm] using integral_comp_smul_deriv' h h' hg
/--
Change of variables, most common version. If `f` is has continuous derivative `f'` on `[a, b]`,
and `g` is continuous, then we can substitute `u = f x` to get
`∫ x in a..b, (g ∘ f) x * f' x = ∫ u in f a..f b, g u`.
-/
theorem integral_comp_mul_deriv {f f' g : ℝ → ℝ}
(h : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(h' : continuous_on f' (interval a b)) (hg : continuous g) :
∫ x in a..b, (g ∘ f) x * f' x = ∫ x in f a..f b, g x :=
integral_comp_mul_deriv' h h' hg.continuous_on
theorem integral_deriv_comp_mul_deriv' {f f' g g' : ℝ → ℝ}
(hf : continuous_on f [a, b])
(hff' : ∀ x ∈ Ioo (min a b) (max a b), has_deriv_within_at f (f' x) (Ioi x) x)
(hf' : continuous_on f' [a, b])
(hg : continuous_on g [f a, f b])
(hgg' : ∀ x ∈ Ioo (min (f a) (f b)) (max (f a) (f b)), has_deriv_within_at g (g' x) (Ioi x) x)
(hg' : continuous_on g' (f '' [a, b])) :
∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a :=
by simpa [mul_comm] using integral_deriv_comp_smul_deriv' hf hff' hf' hg hgg' hg'
theorem integral_deriv_comp_mul_deriv {f f' g g' : ℝ → ℝ}
(hf : ∀ x ∈ interval a b, has_deriv_at f (f' x) x)
(hg : ∀ x ∈ interval a b, has_deriv_at g (g' (f x)) (f x))
(hf' : continuous_on f' (interval a b)) (hg' : continuous g') :
∫ x in a..b, (g' ∘ f) x * f' x = (g ∘ f) b - (g ∘ f) a :=
by simpa [mul_comm] using integral_deriv_comp_smul_deriv hf hg hf' hg'
end mul
end interval_integral
|
1c1a1b0a0d82955122737dc67f274d49beda1973 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /test/tauto.lean | 30d9919b2470713e1e4b8113a6f6b856aa9e9f67 | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 2,498 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import tactic.tauto
section tauto₀
variables p q r : Prop
variables h : p ∧ q ∨ p ∧ r
include h
example : p ∧ p :=
by tauto
end tauto₀
section tauto₁
variables α : Type
variables p q r : α → Prop
variables h : (∃ x, p x ∧ q x) ∨ (∃ x, p x ∧ r x)
include h
example : ∃ x, p x :=
by tauto
end tauto₁
section tauto₂
variables α : Type
variables x : α
variables p q r : α → Prop
variables h₀ : (∀ x, p x → q x → r x) ∨ r x
variables h₁ : p x
variables h₂ : q x
include h₀ h₁ h₂
example : ∃ x, r x :=
by tauto
end tauto₂
section tauto₃
example (p : Prop) : p ∧ true ↔ p := by tauto
example (p : Prop) : p ∨ false ↔ p := by tauto
example (p q r : Prop) [decidable p] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto
example (p q r : Prop) [decidable q] [decidable r] : p ∨ (q ∧ r) ↔ (p ∨ q) ∧ (r ∨ p ∨ r) := by tauto
example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ p) : q := by tauto
example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : p) : ¬ q := by tauto
example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : q) : ¬ p := by tauto
example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) : p := by tauto
example (p q : Prop) [decidable q] [decidable p] (h : ¬ (p ↔ q)) (h' : ¬ q) (h'' : ¬ p) : false :=
by tauto
example (p q r : Prop) [decidable q] [decidable p] (h : p ↔ q) (h' : r ↔ q) (h'' : ¬ r) : ¬ p :=
by tauto
example (p q r : Prop) (h : p ↔ q) (h' : r ↔ q) : p ↔ r :=
by tauto!
example (p q r : Prop) (h : ¬ p = q) (h' : r = q) : p ↔ ¬ r := by tauto!
example (p : Prop) : p → ¬ (p → ¬ p) := by tauto
example (p : Prop) (em : p ∨ ¬ p) : ¬ (p ↔ ¬ p) := by tauto
example (P : ℕ → Prop) (n : ℕ) : P n → n = 7 ∨ n = 0 ∨ ¬ (n = 7 ∨ n = 0) ∧ P n :=
by tauto
section modulo_symmetry
variables {p q r : Prop} {α : Type} {x y : α}
variables (h : x = y)
variables (h'' : (p ∧ q ↔ q ∨ r) ↔ (r ∧ p ↔ r ∨ q))
include h
include h''
example (h' : ¬ y = x) : p ∧ q := by tauto
example (h' : p ∧ ¬ y = x) : p ∧ q := by tauto
example : y = x := by tauto
example (h' : ¬ x = y) : p ∧ q := by tauto
example : x = y := by tauto
end modulo_symmetry
end tauto₃
|
7bbb53c722d1b48b11690acf43ac94e722d7de5a | 54d7e71c3616d331b2ec3845d31deb08f3ff1dea | /library/init/wf.lean | 5a6aae1e4b2fee5d13243c0cf3b3e06c0cf85aea | [
"Apache-2.0"
] | permissive | pachugupta/lean | 6f3305c4292288311cc4ab4550060b17d49ffb1d | 0d02136a09ac4cf27b5c88361750e38e1f485a1a | refs/heads/master | 1,611,110,653,606 | 1,493,130,117,000 | 1,493,167,649,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,440 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.nat.basic init.data.prod
universes u v
inductive acc {α : Type u} (r : α → α → Prop) : α → Prop
| intro : ∀ x, (∀ y, r y x → acc y) → acc x
namespace acc
variables {α : Type u} {r : α → α → Prop}
def inv {x y : α} (h₁ : acc r x) (h₂ : r y x) : acc r y :=
acc.rec_on h₁ (λ x₁ ac₁ ih h₂, ac₁ y h₂) h₂
end acc
inductive well_founded {α : Type u} (r : α → α → Prop) : Prop
| intro : (∀ a, acc r a) → well_founded
namespace well_founded
def apply {α : Type u} {r : α → α → Prop} (wf : well_founded r) : ∀ a, acc r a :=
take a, well_founded.rec_on wf (λ p, p) a
section
parameters {α : Type u} {r : α → α → Prop}
local infix `≺`:50 := r
parameter hwf : well_founded r
lemma recursion {C : α → Sort v} (a : α) (h : Π x, (Π y, y ≺ x → C y) → C x) : C a :=
acc.rec_on (apply hwf a) (λ x₁ ac₁ ih, h x₁ ih)
lemma induction {C : α → Prop} (a : α) (h : ∀ x, (∀ y, y ≺ x → C y) → C x) : C a :=
recursion a h
variable {C : α → Sort v}
variable F : Π x, (Π y, y ≺ x → C y) → C x
def fix_F (x : α) (a : acc r x) : C x :=
acc.rec_on a (λ x₁ ac₁ ih, F x₁ ih)
lemma fix_F_eq (x : α) (acx : acc r x) :
fix_F F x acx = F x (λ (y : α) (p : y ≺ x), fix_F F y (acc.inv acx p)) :=
acc.drec (λ x r ih, rfl) acx
end
variables {α : Type u} {C : α → Sort v} {r : α → α → Prop}
-- Well-founded fixpoint
def fix (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) : C x :=
fix_F F x (apply hwf x)
-- Well-founded fixpoint satisfies fixpoint equation
lemma fix_eq (hwf : well_founded r) (F : Π x, (Π y, r y x → C y) → C x) (x : α) :
fix hwf F x = F x (λ y h, fix hwf F y) :=
fix_F_eq F x (apply hwf x)
end well_founded
open well_founded
-- Empty relation is well-founded
def empty_wf {α : Type u} : well_founded empty_relation :=
well_founded.intro (λ (a : α),
acc.intro a (λ (b : α) (lt : false), false.rec _ lt))
-- Subrelation of a well-founded relation is well-founded
namespace subrelation
section
parameters {α : Type u} {r Q : α → α → Prop}
parameters (h₁ : subrelation Q r)
parameters (h₂ : well_founded r)
def accessible {a : α} (ac : acc r a) : acc Q a :=
acc.rec_on ac (λ x ax ih,
acc.intro x (λ (y : α) (lt : Q y x), ih y (h₁ lt)))
def wf : well_founded Q :=
⟨λ a, accessible (apply h₂ a)⟩
end
end subrelation
-- The inverse image of a well-founded relation is well-founded
namespace inv_image
section
parameters {α : Type u} {β : Type v} {r : β → β → Prop}
parameters (f : α → β)
parameters (h : well_founded r)
private def acc_aux {b : β} (ac : acc r b) : ∀ (x : α), f x = b → acc (inv_image r f) x :=
acc.rec_on ac (λ x acx ih z e,
acc.intro z (λ y lt, eq.rec_on e (λ acx ih, ih (f y) lt y rfl) acx ih))
def accessible {a : α} (ac : acc r (f a)) : acc (inv_image r f) a :=
acc_aux ac a rfl
def wf : well_founded (inv_image r f) :=
⟨λ a, accessible (apply h (f a))⟩
end
end inv_image
-- The transitive closure of a well-founded relation is well-founded
namespace tc
section
parameters {α : Type u} {r : α → α → Prop}
local notation `r⁺` := tc r
def accessible {z : α} (ac : acc r z) : acc (tc r) z :=
acc.rec_on ac (λ x acx ih,
acc.intro x (λ y rel,
tc.rec_on rel
(λ a b rab acx ih, ih a rab)
(λ a b c rab rbc ih₁ ih₂ acx ih, acc.inv (ih₂ acx ih) rab)
acx ih))
def wf (h : well_founded r) : well_founded r⁺ :=
⟨λ a, accessible (apply h a)⟩
end
end tc
-- less-than is well-founded
def nat.lt_wf : well_founded nat.lt :=
⟨nat.rec
(acc.intro 0 (λ n h, absurd h (nat.not_lt_zero n)))
(λ n ih, acc.intro (nat.succ n) (λ m h,
or.elim (nat.eq_or_lt_of_le (nat.le_of_succ_le_succ h))
(λ e, eq.substr e ih) (acc.inv ih)))⟩
def measure {α : Type u} : (α → ℕ) → α → α → Prop :=
inv_image lt
def measure_wf {α : Type u} (f : α → ℕ) : well_founded (measure f) :=
inv_image.wf f nat.lt_wf
namespace prod
open well_founded
section
variables {α : Type u} {β : Type v}
variable (ra : α → α → Prop)
variable (rb : β → β → Prop)
-- Lexicographical order based on ra and rb
inductive lex : α × β → α × β → Prop
| left : ∀ {a₁} b₁ {a₂} b₂, ra a₁ a₂ → lex (a₁, b₁) (a₂, b₂)
| right : ∀ a {b₁ b₂}, rb b₁ b₂ → lex (a, b₁) (a, b₂)
-- relational product based on ra and rb
inductive rprod : α × β → α × β → Prop
| intro : ∀ {a₁ b₁ a₂ b₂}, ra a₁ a₂ → rb b₁ b₂ → rprod (a₁, b₁) (a₂, b₂)
end
section
parameters {α : Type u} {β : Type v}
parameters {ra : α → α → Prop} {rb : β → β → Prop}
local infix `≺`:50 := lex ra rb
def lex_accessible {a} (aca : acc ra a) (acb : ∀ b, acc rb b): ∀ b, acc (lex ra rb) (a, b) :=
acc.rec_on aca (λ xa aca iha b,
acc.rec_on (acb b) (λ xb acb ihb,
acc.intro (xa, xb) (λ p lt,
have aux : xa = xa → xb = xb → acc (lex ra rb) p, from
@prod.lex.rec_on α β ra rb (λ p₁ p₂, fst p₂ = xa → snd p₂ = xb → acc (lex ra rb) p₁)
p (xa, xb) lt
(λ a₁ b₁ a₂ b₂ h (eq₂ : a₂ = xa) (eq₃ : b₂ = xb), iha a₁ (eq.rec_on eq₂ h) b₁)
(λ a b₁ b₂ h (eq₂ : a = xa) (eq₃ : b₂ = xb), eq.rec_on eq₂.symm (ihb b₁ (eq.rec_on eq₃ h))),
aux rfl rfl)))
-- The lexicographical order of well founded relations is well-founded
def lex_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (lex ra rb) :=
⟨λ p, cases_on p (λ a b, lex_accessible (apply ha a) (well_founded.apply hb) b)⟩
-- relational product is a subrelation of the lex
def rprod_sub_lex : ∀ a b, rprod ra rb a b → lex ra rb a b :=
λ a b h, prod.rprod.rec_on h (λ a₁ b₁ a₂ b₂ h₁ h₂, lex.left rb b₁ b₂ h₁)
-- The relational product of well founded relations is well-founded
def rprod_wf (ha : well_founded ra) (hb : well_founded rb) : well_founded (rprod ra rb) :=
subrelation.wf (rprod_sub_lex) (lex_wf ha hb)
end
end prod
|
9e0802578e0267798bbcee379372d10a8808fe75 | 43390109ab88557e6090f3245c47479c123ee500 | /src/finite_dimensional_vector_spaces/tmp.lean | e7be17664291badd7dcc9db537cdab9671bede6c | [
"Apache-2.0"
] | permissive | Ja1941/xena-UROP-2018 | 41f0956519f94d56b8bf6834a8d39473f4923200 | b111fb87f343cf79eca3b886f99ee15c1dd9884b | refs/heads/master | 1,662,355,955,139 | 1,590,577,325,000 | 1,590,577,325,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,052 | lean | import finite_dimensional_vector_spaces.ring_n_is_module
universes u
namespace fin_vector_space
variables (R : Type u) [h : field R] (n : ℕ)
-- structure fin_dim_ring extends module R (vector R n)
include h
def elemental_vector (i : fin n) : vector R n :=
match n, i with
| 0, _ := vector.nil
| (n+1), ⟨0, _⟩ := vector.cons 1 (vector.repeat 0 n)
| (n+1), ⟨i+1, l⟩ := vector.cons 0
$ by exact _match _ ⟨_, (nat.lt_of_succ_lt_succ l)⟩
end
def basis : vector (vector R n) n :=
vector.of_fn (elemental_vector R n)
def basis_as_finset : finset (vector R n) :=
{
val := (basis R n).to_list,
nodup := by
{ rw [basis, vector.to_list_of_fn,
multiset.coe_nodup, list.nodup_iff_nth_le_inj],
intros i j h1 h2,
rw [list.length_of_fn] at h1 h2,
rw [list.nth_le_of_fn _ ⟨i, h1⟩, list.nth_le_of_fn _ ⟨j, h2⟩],
intro a,
induction n with n ih generalizing i j,
exact (nat.le_lt_antisymm (i.zero_le) h1).elim,
cases i; cases j; unfold elemental_vector at a,
{ replace a := @congr _ _ (vector.head) _ _ _ rfl a,
rw [vector.head_cons, vector.head_cons] at a,
exact (not_not_intro a h.zero_ne_one.symm).elim },
{ replace a := @congr _ _ (vector.head) _ _ _ rfl a,
rw [vector.head_cons, vector.head_cons] at a,
exact (not_not_intro a h.zero_ne_one).elim },
{ rw [list.length_of_fn] at ih,
have hi := nat.lt_of_succ_lt_succ h1_1,
have hj := nat.lt_of_succ_lt_succ h2_1,
apply congr rfl,
apply ih _ _ hi hj hj hi,
replace a := @congr _ _ (vector.tail) _ _ _ rfl a,
rw [vector.tail_cons, vector.tail_cons] at a,
exact a } }
}
#check @finsupp.on_finset _ _ _ _ (basis_as_finset R n)
#check @set.finite
def fin_lc (v : vector R n) (i : fin n) : R := v.nth i
def lc_basis [d : decidable_eq R] : lc R (vector R n) :=
by { apply @finsupp.on_finset _ R _ _ (basis_as_finset R n),
swap 2, intro a,
have := ,
-- intros a ha,
-- unfold basis_as_finset basis,
-- simp [vector.to_list_of_fn],
}
-- lemma basis_is_spanning_set : ∀ (x : vector R n),
-- x ∈ span {v : vector R n | v ∈ basis_as_finset R n} :=
-- by { intro a,
-- rw [span, basis_as_finset],
-- split, }
-- instance : is_basis { v | v ∈ basis_as_finset R n } :=
-- by { split,
-- { --simp [linear_independent],
-- unfold linear_independent basis_as_finset,
-- intros l h1 h2, simp at h1,
-- simp [vector.eq_nil 0, finsupp.sum] at h2,
-- -- induction n with _ ih generalizing l,
-- cases l with ls lf lh,
-- simp [list.of_fn, list.of_fn_aux] at h1,
-- simp [coe_fn, has_coe_to_fun.coe] at h1 h2,
-- simp [has_zero.zero],
-- simp [has_zero.zero, add_monoid.zero, add_group.zero,
-- add_comm_group.zero, vector.repeat] at h2,
-- cases ls with lsv lss,
-- split,
-- induction n with _ ih,
-- }, }
end fin_vector_space |
86bcd7a69c442895e7d5bb35cb498e94081104fc | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/order/complete_lattice.lean | 8fb2af63cb409412fada5ba1b0a2ea0f9897acb3 | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 33,547 | 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
Theory of complete lattices.
-/
import order.bounded_lattice order.bounds data.set.basic tactic.pi_instances tactic.alias
set_option old_structure_cmd true
open set
universes u v w w₂
variables {α : Type u} {β : Type v} {ι : Sort w} {ι₂ : Sort w₂}
/-- class for the `Sup` operator -/
class has_Sup (α : Type u) := (Sup : set α → α)
/-- class for the `Inf` operator -/
class has_Inf (α : Type u) := (Inf : set α → α)
/-- Supremum of a set -/
def Sup [has_Sup α] : set α → α := has_Sup.Sup
/-- Infimum of a set -/
def Inf [has_Inf α] : set α → α := has_Inf.Inf
/-- Indexed supremum -/
def supr [has_Sup α] (s : ι → α) : α := Sup (range s)
/-- Indexed infimum -/
def infi [has_Inf α] (s : ι → α) : α := Inf (range s)
lemma has_Inf_to_nonempty (α) [has_Inf α] : nonempty α := ⟨Inf ∅⟩
lemma has_Sup_to_nonempty (α) [has_Sup α] : nonempty α := ⟨Sup ∅⟩
notation `⨆` binders `, ` r:(scoped f, supr f) := r
notation `⨅` binders `, ` r:(scoped f, infi f) := r
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A complete lattice is a bounded lattice which
has suprema and infima for every subset. -/
class complete_lattice (α : Type u) extends bounded_lattice α, has_Sup α, has_Inf α :=
(le_Sup : ∀s, ∀a∈s, a ≤ Sup s)
(Sup_le : ∀s a, (∀b∈s, b ≤ a) → Sup s ≤ a)
(Inf_le : ∀s, ∀a∈s, Inf s ≤ a)
(le_Inf : ∀s a, (∀b∈s, a ≤ b) → a ≤ Inf s)
/-- A complete linear order is a linear order whose lattice structure is complete. -/
class complete_linear_order (α : Type u) extends complete_lattice α, decidable_linear_order α
end prio
section
variables [complete_lattice α] {s t : set α} {a b : α}
@[ematch] theorem le_Sup : a ∈ s → a ≤ Sup s := complete_lattice.le_Sup s a
theorem Sup_le : (∀b∈s, b ≤ a) → Sup s ≤ a := complete_lattice.Sup_le s a
@[ematch] theorem Inf_le : a ∈ s → Inf s ≤ a := complete_lattice.Inf_le s a
theorem le_Inf : (∀b∈s, a ≤ b) → a ≤ Inf s := complete_lattice.le_Inf s a
lemma is_lub_Sup (s : set α) : is_lub s (Sup s) := ⟨assume x, le_Sup, assume x, Sup_le⟩
lemma is_lub.Sup_eq (h : is_lub s a) : Sup s = a := (is_lub_Sup s).unique h
lemma is_glb_Inf (s : set α) : is_glb s (Inf s) := ⟨assume a, Inf_le, assume a, le_Inf⟩
lemma is_glb.Inf_eq (h : is_glb s a) : Inf s = a := (is_glb_Inf s).unique h
theorem le_Sup_of_le (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_Sup hb)
theorem Inf_le_of_le (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (Inf_le hb) h
theorem Sup_le_Sup (h : s ⊆ t) : Sup s ≤ Sup t :=
Sup_le (assume a, assume ha : a ∈ s, le_Sup $ h ha)
theorem Inf_le_Inf (h : s ⊆ t) : Inf t ≤ Inf s :=
le_Inf (assume a, assume ha : a ∈ s, Inf_le $ h ha)
@[simp] theorem Sup_le_iff : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
is_lub_le_iff (is_lub_Sup s)
@[simp] theorem le_Inf_iff : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
le_is_glb_iff (is_glb_Inf s)
theorem Inf_le_Sup (hs : s.nonempty) : Inf s ≤ Sup s :=
is_glb_le_is_lub (is_glb_Inf s) (is_lub_Sup s) hs
-- TODO: it is weird that we have to add union_def
theorem Sup_union {s t : set α} : Sup (s ∪ t) = Sup s ⊔ Sup t :=
((is_lub_Sup s).union (is_lub_Sup t)).Sup_eq
theorem Sup_inter_le {s t : set α} : Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
by finish
/-
Sup_le (assume a ⟨a_s, a_t⟩, le_inf (le_Sup a_s) (le_Sup a_t))
-/
theorem Inf_union {s t : set α} : Inf (s ∪ t) = Inf s ⊓ Inf t :=
((is_glb_Inf s).union (is_glb_Inf t)).Inf_eq
theorem le_Inf_inter {s t : set α} : Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
by finish
/-
le_Inf (assume a ⟨a_s, a_t⟩, sup_le (Inf_le a_s) (Inf_le a_t))
-/
@[simp] theorem Sup_empty : Sup ∅ = (⊥ : α) :=
is_lub_empty.Sup_eq
@[simp] theorem Inf_empty : Inf ∅ = (⊤ : α) :=
(@is_glb_empty α _).Inf_eq
@[simp] theorem Sup_univ : Sup univ = (⊤ : α) :=
(@is_lub_univ α _).Sup_eq
@[simp] theorem Inf_univ : Inf univ = (⊥ : α) :=
is_glb_univ.Inf_eq
-- TODO(Jeremy): get this automatically
@[simp] theorem Sup_insert {a : α} {s : set α} : Sup (insert a s) = a ⊔ Sup s :=
((is_lub_Sup s).insert a).Sup_eq
@[simp] theorem Inf_insert {a : α} {s : set α} : Inf (insert a s) = a ⊓ Inf s :=
((is_glb_Inf s).insert a).Inf_eq
-- We will generalize this to conditionally complete lattices in `cSup_singleton`.
theorem Sup_singleton {a : α} : Sup {a} = a :=
is_lub_singleton.Sup_eq
-- We will generalize this to conditionally complete lattices in `cInf_singleton`.
theorem Inf_singleton {a : α} : Inf {a} = a :=
is_glb_singleton.Inf_eq
theorem Sup_pair {a b : α} : Sup {a, b} = a ⊔ b :=
(@is_lub_pair α _ a b).Sup_eq
theorem Inf_pair {a b : α} : Inf {a, b} = a ⊓ b :=
(@is_glb_pair α _ a b).Inf_eq
@[simp] theorem Inf_eq_top : Inf s = ⊤ ↔ (∀a∈s, a = ⊤) :=
iff.intro
(assume h a ha, top_unique $ h ▸ Inf_le ha)
(assume h, top_unique $ le_Inf $ assume a ha, top_le_iff.2 $ h a ha)
@[simp] theorem Sup_eq_bot : Sup s = ⊥ ↔ (∀a∈s, a = ⊥) :=
iff.intro
(assume h a ha, bot_unique $ h ▸ le_Sup ha)
(assume h, bot_unique $ Sup_le $ assume a ha, le_bot_iff.2 $ h a ha)
end
section complete_linear_order
variables [complete_linear_order α] {s t : set α} {a b : α}
lemma Inf_lt_iff : Inf s < b ↔ (∃a∈s, a < b) :=
is_glb_lt_iff (is_glb_Inf s)
lemma lt_Sup_iff : b < Sup s ↔ (∃a∈s, b < a) :=
lt_is_lub_iff (is_lub_Sup s)
lemma Sup_eq_top : Sup s = ⊤ ↔ (∀b<⊤, ∃a∈s, b < a) :=
iff.intro
(assume (h : Sup s = ⊤) b hb, by rwa [←h, lt_Sup_iff] at hb)
(assume h, top_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_le_of_lt (le_Sup ha) h)
lemma Inf_eq_bot : Inf s = ⊥ ↔ (∀b>⊥, ∃a∈s, a < b) :=
iff.intro
(assume (h : Inf s = ⊥) b (hb : ⊥ < b), by rwa [←h, Inf_lt_iff] at hb)
(assume h, bot_unique $ le_of_not_gt $ assume h',
let ⟨a, ha, h⟩ := h _ h' in
lt_irrefl a $ lt_of_lt_of_le h (Inf_le ha))
lemma lt_supr_iff {ι : Sort*} {f : ι → α} : a < supr f ↔ (∃i, a < f i) :=
lt_Sup_iff.trans exists_range_iff
lemma infi_lt_iff {ι : Sort*} {f : ι → α} : infi f < a ↔ (∃i, f i < a) :=
Inf_lt_iff.trans exists_range_iff
end complete_linear_order
/- supr & infi -/
section
variables [complete_lattice α] {s t : ι → α} {a b : α}
-- TODO: this declaration gives error when starting smt state
--@[ematch]
theorem le_supr (s : ι → α) (i : ι) : s i ≤ supr s :=
le_Sup ⟨i, rfl⟩
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i ≤ supr s :) :=
le_Sup ⟨i, rfl⟩
/- TODO: this version would be more powerful, but, alas, the pattern matcher
doesn't accept it.
@[ematch] theorem le_supr' (s : ι → α) (i : ι) : (: s i :) ≤ (: supr s :) :=
le_Sup ⟨i, rfl⟩
-/
lemma is_lub_supr : is_lub (range s) (⨆j, s j) := is_lub_Sup _
lemma is_lub.supr_eq (h : is_lub (range s) a) : (⨆j, s j) = a := h.Sup_eq
lemma is_glb_infi : is_glb (range s) (⨅j, s j) := is_glb_Inf _
lemma is_glb.infi_eq (h : is_glb (range s) a) : (⨅j, s j) = a := h.Inf_eq
theorem le_supr_of_le (i : ι) (h : a ≤ s i) : a ≤ supr s :=
le_trans h (le_supr _ i)
theorem supr_le (h : ∀i, s i ≤ a) : supr s ≤ a :=
Sup_le $ assume b ⟨i, eq⟩, eq ▸ h i
theorem supr_le_supr (h : ∀i, s i ≤ t i) : supr s ≤ supr t :=
supr_le $ assume i, le_supr_of_le i (h i)
theorem supr_le_supr2 {t : ι₂ → α} (h : ∀i, ∃j, s i ≤ t j) : supr s ≤ supr t :=
supr_le $ assume j, exists.elim (h j) le_supr_of_le
theorem supr_le_supr_const (h : ι → ι₂) : (⨆ i:ι, a) ≤ (⨆ j:ι₂, a) :=
supr_le $ le_supr _ ∘ h
@[simp] theorem supr_le_iff : supr s ≤ a ↔ (∀i, s i ≤ a) :=
(is_lub_le_iff is_lub_supr).trans forall_range_iff
lemma le_supr_iff : (a ≤ supr s) ↔ (∀ b, (∀ i, s i ≤ b) → a ≤ b) :=
⟨λ h b hb, le_trans h (supr_le hb), λ h, h _ $ λ i, le_supr s i⟩
lemma monotone.map_supr_ge [complete_lattice β] {f : α → β} (hf : monotone f) :
(⨆ i, f (s i)) ≤ f (supr s) :=
supr_le $ λ i, hf $ le_supr _ _
lemma monotone.map_supr2_ge [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
(⨆ i (h : ι' i), f (s i h)) ≤ f (⨆ i (h : ι' i), s i h) :=
calc (⨆ i h, f (s i h)) ≤ (⨆ i, f (⨆ h, s i h)) :
supr_le_supr $ λ i, hf.map_supr_ge
... ≤ f (⨆ i (h : ι' i), s i h) : hf.map_supr_ge
-- TODO: finish doesn't do well here.
@[congr] theorem supr_congr_Prop {α : Type u} [has_Sup α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : supr f₁ = supr f₂ :=
begin
unfold supr,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
theorem infi_le (s : ι → α) (i : ι) : infi s ≤ s i :=
Inf_le ⟨i, rfl⟩
@[ematch] theorem infi_le' (s : ι → α) (i : ι) : (: infi s ≤ s i :) :=
Inf_le ⟨i, rfl⟩
/- I wanted to see if this would help for infi_comm; it doesn't.
@[ematch] theorem infi_le₂' (s : ι → ι₂ → α) (i : ι) (j : ι₂) : (: ⨅ i j, s i j :) ≤ (: s i j :) :=
begin
transitivity,
apply (infi_le (λ i, ⨅ j, s i j) i),
apply infi_le
end
-/
theorem infi_le_of_le (i : ι) (h : s i ≤ a) : infi s ≤ a :=
le_trans (infi_le _ i) h
theorem le_infi (h : ∀i, a ≤ s i) : a ≤ infi s :=
le_Inf $ assume b ⟨i, eq⟩, eq ▸ h i
theorem infi_le_infi (h : ∀i, s i ≤ t i) : infi s ≤ infi t :=
le_infi $ assume i, infi_le_of_le i (h i)
theorem infi_le_infi2 {t : ι₂ → α} (h : ∀j, ∃i, s i ≤ t j) : infi s ≤ infi t :=
le_infi $ assume j, exists.elim (h j) infi_le_of_le
theorem infi_le_infi_const (h : ι₂ → ι) : (⨅ i:ι, a) ≤ (⨅ j:ι₂, a) :=
le_infi $ infi_le _ ∘ h
@[simp] theorem le_infi_iff : a ≤ infi s ↔ (∀i, a ≤ s i) :=
⟨assume : a ≤ infi s, assume i, le_trans this (infi_le _ _), le_infi⟩
lemma monotone.map_infi_le [complete_lattice β] {f : α → β} (hf : monotone f) :
f (infi s) ≤ (⨅ i, f (s i)) :=
le_infi $ λ i, hf $ infi_le _ _
lemma monotone.map_infi2_le [complete_lattice β] {f : α → β} (hf : monotone f)
{ι' : ι → Sort*} (s : Π i, ι' i → α) :
f (⨅ i (h : ι' i), s i h) ≤ (⨅ i (h : ι' i), f (s i h)) :=
calc f (⨅ i (h : ι' i), s i h) ≤ (⨅ i, f (⨅ h, s i h)) : hf.map_infi_le
... ≤ (⨅ i h, f (s i h)) : infi_le_infi $ λ i, hf.map_infi_le
@[congr] theorem infi_congr_Prop {α : Type u} [has_Inf α] {p q : Prop} {f₁ : p → α} {f₂ : q → α}
(pq : p ↔ q) (f : ∀x, f₁ (pq.mpr x) = f₂ x) : infi f₁ = infi f₂ :=
begin
unfold infi,
apply congr_arg,
ext,
simp,
split,
exact λ⟨h, W⟩, ⟨pq.1 h, eq.trans (f (pq.1 h)).symm W⟩,
exact λ⟨h, W⟩, ⟨pq.2 h, eq.trans (f h) W⟩
end
-- We will generalize this to conditionally complete lattices in `cinfi_const`.
theorem infi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
by rw [infi, range_const, Inf_singleton]
-- We will generalize this to conditionally complete lattices in `csupr_const`.
theorem supr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
by rw [supr, range_const, Sup_singleton]
@[simp] lemma infi_top : (⨅i:ι, ⊤ : α) = ⊤ :=
top_unique $ le_infi $ assume i, le_refl _
@[simp] lemma supr_bot : (⨆i:ι, ⊥ : α) = ⊥ :=
bot_unique $ supr_le $ assume i, le_refl _
@[simp] lemma infi_eq_top : infi s = ⊤ ↔ (∀i, s i = ⊤) :=
iff.intro
(assume eq i, top_unique $ eq ▸ infi_le _ _)
(assume h, top_unique $ le_infi $ assume i, top_le_iff.2 $ h i)
@[simp] lemma supr_eq_bot : supr s = ⊥ ↔ (∀i, s i = ⊥) :=
iff.intro
(assume eq i, bot_unique $ eq ▸ le_supr _ _)
(assume h, bot_unique $ supr_le $ assume i, le_bot_iff.2 $ h i)
@[simp] lemma infi_pos {p : Prop} {f : p → α} (hp : p) : (⨅ h : p, f h) = f hp :=
le_antisymm (infi_le _ _) (le_infi $ assume h, le_refl _)
@[simp] lemma infi_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨅ h : p, f h) = ⊤ :=
le_antisymm le_top $ le_infi $ assume h, (hp h).elim
@[simp] lemma supr_pos {p : Prop} {f : p → α} (hp : p) : (⨆ h : p, f h) = f hp :=
le_antisymm (supr_le $ assume h, le_refl _) (le_supr _ _)
@[simp] lemma supr_neg {p : Prop} {f : p → α} (hp : ¬ p) : (⨆ h : p, f h) = ⊥ :=
le_antisymm (supr_le $ assume h, (hp h).elim) bot_le
lemma supr_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨆h:p, a h) = (if h : p then a h else ⊥) :=
by by_cases p; simp [h]
lemma supr_eq_if {p : Prop} [decidable p] (a : α) :
(⨆h:p, a) = (if p then a else ⊥) :=
by rw [supr_eq_dif, dif_eq_if]
lemma infi_eq_dif {p : Prop} [decidable p] (a : p → α) :
(⨅h:p, a h) = (if h : p then a h else ⊤) :=
by by_cases p; simp [h]
lemma infi_eq_if {p : Prop} [decidable p] (a : α) :
(⨅h:p, a) = (if p then a else ⊤) :=
by rw [infi_eq_dif, dif_eq_if]
-- TODO: should this be @[simp]?
theorem infi_comm {f : ι → ι₂ → α} : (⨅i, ⨅j, f i j) = (⨅j, ⨅i, f i j) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le_of_le j $ infi_le _ i)
(le_infi $ assume j, le_infi $ assume i, infi_le_of_le i $ infi_le _ j)
/- TODO: this is strange. In the proof below, we get exactly the desired
among the equalities, but close does not get it.
begin
apply @le_antisymm,
simp, intros,
begin [smt]
ematch, ematch, ematch, trace_state, have := le_refl (f i_1 i),
trace_state, close
end
end
-/
-- TODO: should this be @[simp]?
theorem supr_comm {f : ι → ι₂ → α} : (⨆i, ⨆j, f i j) = (⨆j, ⨆i, f i j) :=
le_antisymm
(supr_le $ assume i, supr_le $ assume j, le_supr_of_le j $ le_supr _ i)
(supr_le $ assume j, supr_le $ assume i, le_supr_of_le i $ le_supr _ j)
@[simp] theorem infi_infi_eq_left {b : β} {f : Πx:β, x = b → α} : (⨅x, ⨅h:x = b, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem infi_infi_eq_right {b : β} {f : Πx:β, b = x → α} : (⨅x, ⨅h:b = x, f x h) = f b rfl :=
le_antisymm
(infi_le_of_le b $ infi_le _ rfl)
(le_infi $ assume b', le_infi $ assume eq, match b', eq with ._, rfl := le_refl _ end)
@[simp] theorem supr_supr_eq_left {b : β} {f : Πx:β, x = b → α} : (⨆x, ⨆h : x = b, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
@[simp] theorem supr_supr_eq_right {b : β} {f : Πx:β, b = x → α} : (⨆x, ⨆h : b = x, f x h) = f b rfl :=
le_antisymm
(supr_le $ assume b', supr_le $ assume eq, match b', eq with ._, rfl := le_refl _ end)
(le_supr_of_le b $ le_supr _ rfl)
attribute [ematch] le_refl
theorem infi_inf_eq {f g : ι → α} : (⨅ x, f x ⊓ g x) = (⨅ x, f x) ⊓ (⨅ x, g x) :=
le_antisymm
(le_inf
(le_infi $ assume i, infi_le_of_le i inf_le_left)
(le_infi $ assume i, infi_le_of_le i inf_le_right))
(le_infi $ assume i, le_inf
(inf_le_left_of_le $ infi_le _ _)
(inf_le_right_of_le $ infi_le _ _))
/- TODO: here is another example where more flexible pattern matching
might help.
begin
apply @le_antisymm,
safe, pose h := f a ⊓ g a, begin [smt] ematch, ematch end
end
-/
lemma infi_inf {f : ι → α} {a : α} (i : ι) : (⨅x, f x) ⊓ a = (⨅ x, f x ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_inf (inf_le_left_of_le $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, inf_le_left) (infi_le_of_le i inf_le_right))
lemma inf_infi {f : ι → α} {a : α} (i : ι) : a ⊓ (⨅x, f x) = (⨅ x, a ⊓ f x) :=
by rw [inf_comm, infi_inf i]; simp [inf_comm]
lemma binfi_inf {ι : Sort*} {p : ι → Prop}
{f : Πi, p i → α} {a : α} {i : ι} (hi : p i) :
(⨅i (h : p i), f i h) ⊓ a = (⨅ i (h : p i), f i h ⊓ a) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume hi,
le_inf (inf_le_left_of_le $ infi_le_of_le i $ infi_le _ _) inf_le_right)
(le_inf (infi_le_infi $ assume i, infi_le_infi $ assume hi, inf_le_left)
(infi_le_of_le i $ infi_le_of_le hi $ inf_le_right))
theorem supr_sup_eq {f g : β → α} : (⨆ x, f x ⊔ g x) = (⨆ x, f x) ⊔ (⨆ x, g x) :=
le_antisymm
(supr_le $ assume i, sup_le
(le_sup_left_of_le $ le_supr _ _)
(le_sup_right_of_le $ le_supr _ _))
(sup_le
(supr_le $ assume i, le_supr_of_le i le_sup_left)
(supr_le $ assume i, le_supr_of_le i le_sup_right))
/- supr and infi under Prop -/
@[simp] theorem infi_false {s : false → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, false.elim i)
@[simp] theorem supr_false {s : false → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, false.elim i) bot_le
@[simp] theorem infi_true {s : true → α} : infi s = s trivial :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_true {s : true → α} : supr s = s trivial :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
@[simp] theorem infi_exists {p : ι → Prop} {f : Exists p → α} : (⨅ x, f x) = (⨅ i, ⨅ h:p i, f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
@[simp] theorem supr_exists {p : ι → Prop} {f : Exists p → α} : (⨆ x, f x) = (⨆ i, ⨆ h:p i, f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_and {p q : Prop} {s : p ∧ q → α} : infi s = (⨅ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_and {p q : Prop} {s : p ∧ q → α} : supr s = (⨆ h₁ h₂, s ⟨h₁, h₂⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, s ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_or {p q : Prop} {s : p ∨ q → α} :
infi s = (⨅ h : p, s (or.inl h)) ⊓ (⨅ h : q, s (or.inr h)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume i, match i with
| or.inl i := inf_le_left_of_le $ infi_le _ _
| or.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_or {p q : Prop} {s : p ∨ q → α} :
(⨆ x, s x) = (⨆ i, s (or.inl i)) ⊔ (⨆ j, s (or.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| or.inl i := le_sup_left_of_le $ le_supr _ i
| or.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨or.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨or.inr j, le_refl _⟩))
theorem Inf_eq_infi {s : set α} : Inf s = (⨅a ∈ s, a) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume h, Inf_le h)
(le_Inf $ assume b h, infi_le_of_le b $ infi_le _ h)
theorem Sup_eq_supr {s : set α} : Sup s = (⨆a ∈ s, a) :=
le_antisymm
(Sup_le $ assume b h, le_supr_of_le b $ le_supr _ h)
(supr_le $ assume b, supr_le $ assume h, le_Sup h)
lemma Sup_range {α : Type u} [has_Sup α] {f : ι → α} : Sup (range f) = supr f := rfl
lemma Inf_range {α : Type u} [has_Inf α] {f : ι → α} : Inf (range f) = infi f := rfl
lemma supr_range {g : β → α} {f : ι → β} : (⨆b∈range f, g b) = (⨆i, g (f i)) :=
le_antisymm
(supr_le $ assume b, supr_le $ assume ⟨i, (h : f i = b)⟩, h ▸ le_supr _ i)
(supr_le $ assume i, le_supr_of_le (f i) $ le_supr (λp, g (f i)) (mem_range_self _))
lemma infi_range {g : β → α} {f : ι → β} : (⨅b∈range f, g b) = (⨅i, g (f i)) :=
le_antisymm
(le_infi $ assume i, infi_le_of_le (f i) $ infi_le (λp, g (f i)) (mem_range_self _))
(le_infi $ assume b, le_infi $ assume ⟨i, (h : f i = b)⟩, h ▸ infi_le _ i)
theorem Inf_image {s : set β} {f : β → α} : Inf (f '' s) = (⨅ a ∈ s, f a) :=
calc Inf (set.image f s) = (⨅a, ⨅h : ∃b, b ∈ s ∧ f b = a, a) : Inf_eq_infi
... = (⨅a, ⨅b, ⨅h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨅a, ⨅b, ⨅h : a = f b, ⨅h : b ∈ s, a) : by simp [infi_and, eq_comm]
... = (⨅b, ⨅a, ⨅h : a = f b, ⨅h : b ∈ s, a) : by rw [infi_comm]
... = (⨅a∈s, f a) : congr_arg infi $ by funext x; rw [infi_infi_eq_left]
theorem Sup_image {s : set β} {f : β → α} : Sup (f '' s) = (⨆ a ∈ s, f a) :=
calc Sup (set.image f s) = (⨆a, ⨆h : ∃b, b ∈ s ∧ f b = a, a) : Sup_eq_supr
... = (⨆a, ⨆b, ⨆h : f b = a ∧ b ∈ s, a) : by simp [and_comm]
... = (⨆a, ⨆b, ⨆h : a = f b, ⨆h : b ∈ s, a) : by simp [supr_and, eq_comm]
... = (⨆b, ⨆a, ⨆h : a = f b, ⨆h : b ∈ s, a) : by rw [supr_comm]
... = (⨆a∈s, f a) : congr_arg supr $ by funext x; rw [supr_supr_eq_left]
/- supr and infi under set constructions -/
theorem infi_emptyset {f : β → α} : (⨅ x ∈ (∅ : set β), f x) = ⊤ :=
by simp
theorem supr_emptyset {f : β → α} : (⨆ x ∈ (∅ : set β), f x) = ⊥ :=
by simp
theorem infi_univ {f : β → α} : (⨅ x ∈ (univ : set β), f x) = (⨅ x, f x) :=
by simp
theorem supr_univ {f : β → α} : (⨆ x ∈ (univ : set β), f x) = (⨆ x, f x) :=
by simp
theorem infi_union {f : β → α} {s t : set β} : (⨅ x ∈ s ∪ t, f x) = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) :=
calc (⨅ x ∈ s ∪ t, f x) = (⨅ x, (⨅h : x∈s, f x) ⊓ (⨅h : x∈t, f x)) : congr_arg infi $ funext $ assume x, infi_or
... = (⨅x∈s, f x) ⊓ (⨅x∈t, f x) : infi_inf_eq
theorem infi_le_infi_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨅ x ∈ t, f x) ≤ (⨅ x ∈ s, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, infi_union]; exact inf_le_left
theorem supr_union {f : β → α} {s t : set β} : (⨆ x ∈ s ∪ t, f x) = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) :=
calc (⨆ x ∈ s ∪ t, f x) = (⨆ x, (⨆h : x∈s, f x) ⊔ (⨆h : x∈t, f x)) : congr_arg supr $ funext $ assume x, supr_or
... = (⨆x∈s, f x) ⊔ (⨆x∈t, f x) : supr_sup_eq
theorem supr_le_supr_of_subset {f : β → α} {s t : set β} (h : s ⊆ t) :
(⨆ x ∈ s, f x) ≤ (⨆ x ∈ t, f x) :=
by rw [(union_eq_self_of_subset_left h).symm, supr_union]; exact le_sup_left
theorem infi_insert {f : β → α} {s : set β} {b : β} : (⨅ x ∈ insert b s, f x) = f b ⊓ (⨅x∈s, f x) :=
eq.trans infi_union $ congr_arg (λx:α, x ⊓ (⨅x∈s, f x)) infi_infi_eq_left
theorem supr_insert {f : β → α} {s : set β} {b : β} : (⨆ x ∈ insert b s, f x) = f b ⊔ (⨆x∈s, f x) :=
eq.trans supr_union $ congr_arg (λx:α, x ⊔ (⨆x∈s, f x)) supr_supr_eq_left
theorem infi_singleton {f : β → α} {b : β} : (⨅ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem infi_pair {f : β → α} {a b : β} : (⨅ x ∈ ({a, b} : set β), f x) = f a ⊓ f b :=
by { rw [show {a, b} = (insert b {a} : set β), from rfl, infi_insert, inf_comm], simp }
theorem supr_singleton {f : β → α} {b : β} : (⨆ x ∈ (singleton b : set β), f x) = f b :=
by simp
theorem supr_pair {f : β → α} {a b : β} : (⨆ x ∈ ({a, b} : set β), f x) = f a ⊔ f b :=
by { rw [show {a, b} = (insert b {a} : set β), from rfl, supr_insert, sup_comm], simp }
lemma infi_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨅ c ∈ f '' t, g c) = (⨅ b ∈ t, g (f b)) :=
le_antisymm
(le_infi $ assume b, le_infi $ assume hbt,
infi_le_of_le (f b) $ infi_le (λ_, g (f b)) (mem_image_of_mem f hbt))
(le_infi $ assume c, le_infi $ assume ⟨b, hbt, eq⟩,
eq ▸ infi_le_of_le b $ infi_le (λ_, g (f b)) hbt)
lemma supr_image {γ} {f : β → γ} {g : γ → α} {t : set β} :
(⨆ c ∈ f '' t, g c) = (⨆ b ∈ t, g (f b)) :=
le_antisymm
(supr_le $ assume c, supr_le $ assume ⟨b, hbt, eq⟩,
eq ▸ le_supr_of_le b $ le_supr (λ_, g (f b)) hbt)
(supr_le $ assume b, supr_le $ assume hbt,
le_supr_of_le (f b) $ le_supr (λ_, g (f b)) (mem_image_of_mem f hbt))
/- supr and infi under Type -/
@[simp] theorem infi_empty {s : empty → α} : infi s = ⊤ :=
le_antisymm le_top (le_infi $ assume i, empty.rec_on _ i)
@[simp] theorem supr_empty {s : empty → α} : supr s = ⊥ :=
le_antisymm (supr_le $ assume i, empty.rec_on _ i) bot_le
@[simp] theorem infi_unit {f : unit → α} : (⨅ x, f x) = f () :=
le_antisymm (infi_le _ _) (le_infi $ assume ⟨⟩, le_refl _)
@[simp] theorem supr_unit {f : unit → α} : (⨆ x, f x) = f () :=
le_antisymm (supr_le $ assume ⟨⟩, le_refl _) (le_supr _ _)
lemma supr_bool_eq {f : bool → α} : (⨆b:bool, f b) = f tt ⊔ f ff :=
le_antisymm
(supr_le $ assume b, match b with tt := le_sup_left | ff := le_sup_right end)
(sup_le (le_supr _ _) (le_supr _ _))
lemma infi_bool_eq {f : bool → α} : (⨅b:bool, f b) = f tt ⊓ f ff :=
le_antisymm
(le_inf (infi_le _ _) (infi_le _ _))
(le_infi $ assume b, match b with tt := inf_le_left | ff := inf_le_right end)
theorem infi_subtype {p : ι → Prop} {f : subtype p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
lemma infi_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨅ i (h : p i), f i h) = (⨅ x : subtype p, f x.val x.property) :=
(@infi_subtype _ _ _ p (λ x, f x.val x.property)).symm
theorem supr_subtype {p : ι → Prop} {f : subtype p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
lemma supr_subtype' {p : ι → Prop} {f : ∀ i, p i → α} :
(⨆ i (h : p i), f i h) = (⨆ x : subtype p, f x.val x.property) :=
(@supr_subtype _ _ _ p (λ x, f x.val x.property)).symm
theorem infi_sigma {p : β → Type w} {f : sigma p → α} : (⨅ x, f x) = (⨅ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume : p i, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_sigma {p : β → Type w} {f : sigma p → α} : (⨆ x, f x) = (⨆ i (h:p i), f ⟨i, h⟩) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λh:p i, f ⟨i, h⟩) _)
(supr_le $ assume i, supr_le $ assume : p i, le_supr _ _)
theorem infi_prod {γ : Type w} {f : β × γ → α} : (⨅ x, f x) = (⨅ i j, f (i, j)) :=
le_antisymm
(le_infi $ assume i, le_infi $ assume j, infi_le _ _)
(le_infi $ assume ⟨i, h⟩, infi_le_of_le i $ infi_le _ _)
theorem supr_prod {γ : Type w} {f : β × γ → α} : (⨆ x, f x) = (⨆ i j, f (i, j)) :=
le_antisymm
(supr_le $ assume ⟨i, h⟩, le_supr_of_le i $ le_supr (λj, f ⟨i, j⟩) _)
(supr_le $ assume i, supr_le $ assume j, le_supr _ _)
theorem infi_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨅ x, f x) = (⨅ i, f (sum.inl i)) ⊓ (⨅ j, f (sum.inr j)) :=
le_antisymm
(le_inf
(infi_le_infi2 $ assume i, ⟨_, le_refl _⟩)
(infi_le_infi2 $ assume j, ⟨_, le_refl _⟩))
(le_infi $ assume s, match s with
| sum.inl i := inf_le_left_of_le $ infi_le _ _
| sum.inr j := inf_le_right_of_le $ infi_le _ _
end)
theorem supr_sum {γ : Type w} {f : β ⊕ γ → α} :
(⨆ x, f x) = (⨆ i, f (sum.inl i)) ⊔ (⨆ j, f (sum.inr j)) :=
le_antisymm
(supr_le $ assume s, match s with
| sum.inl i := le_sup_left_of_le $ le_supr _ i
| sum.inr j := le_sup_right_of_le $ le_supr _ j
end)
(sup_le
(supr_le_supr2 $ assume i, ⟨sum.inl i, le_refl _⟩)
(supr_le_supr2 $ assume j, ⟨sum.inr j, le_refl _⟩))
end
section complete_linear_order
variables [complete_linear_order α]
lemma supr_eq_top (f : ι → α) : supr f = ⊤ ↔ (∀b<⊤, ∃i, b < f i) :=
by rw [← Sup_range, Sup_eq_top];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
lemma infi_eq_bot (f : ι → α) : infi f = ⊥ ↔ (∀b>⊥, ∃i, b > f i) :=
by rw [← Inf_range, Inf_eq_bot];
from forall_congr (assume b, forall_congr (assume hb, set.exists_range_iff))
end complete_linear_order
/- Instances -/
instance complete_lattice_Prop : complete_lattice Prop :=
{ Sup := λs, ∃a∈s, a,
le_Sup := assume s a h p, ⟨a, h, p⟩,
Sup_le := assume s a h ⟨b, h', p⟩, h b h' p,
Inf := λs, ∀a:Prop, a∈s → a,
Inf_le := assume s a h p, p a h,
le_Inf := assume s a h p b hb, h b hb p,
..bounded_lattice_Prop }
lemma Inf_Prop_eq {s : set Prop} : Inf s = (∀p ∈ s, p) := rfl
lemma Sup_Prop_eq {s : set Prop} : Sup s = (∃p ∈ s, p) := rfl
lemma infi_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨅i, p i) = (∀i, p i) :=
le_antisymm (assume h i, h _ ⟨i, rfl⟩ ) (assume h p ⟨i, eq⟩, eq ▸ h i)
lemma supr_Prop_eq {ι : Sort*} {p : ι → Prop} : (⨆i, p i) = (∃i, p i) :=
le_antisymm (assume ⟨q, ⟨i, (eq : p i = q)⟩, hq⟩, ⟨i, eq.symm ▸ hq⟩) (assume ⟨i, hi⟩, ⟨p i, ⟨i, rfl⟩, hi⟩)
instance pi.complete_lattice {α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] :
complete_lattice (Π i, β i) :=
by { pi_instance;
{ intros, intro,
apply_field, intros,
simp at H, rcases H with ⟨ x, H₀, H₁ ⟩,
subst b, apply a_1 _ H₀ i, } }
lemma Inf_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Inf s) a = (⨅f∈s, (f : Πa, β a) a) :=
by rw [← Inf_image]; refl
lemma infi_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨅i, f i) a = (⨅i, f i a) :=
by erw [← Inf_range, Inf_apply, infi_range]
lemma Sup_apply
{α : Type u} {β : α → Type v} [∀ i, complete_lattice (β i)] {s : set (Πa, β a)} {a : α} :
(Sup s) a = (⨆f∈s, (f : Πa, β a) a) :=
by rw [← Sup_image]; refl
lemma supr_apply {α : Type u} {β : α → Type v} {ι : Sort*} [∀ i, complete_lattice (β i)]
{f : ι → Πa, β a} {a : α} : (⨆i, f i) a = (⨆i, f i a) :=
by erw [← Sup_range, Sup_apply, supr_range]
section complete_lattice
variables [preorder α] [complete_lattice β]
theorem monotone_Sup_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Sup s) :=
assume x y h, Sup_le $ assume x' ⟨f, f_in, fx_eq⟩, le_Sup_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
theorem monotone_Inf_of_monotone {s : set (α → β)} (m_s : ∀f∈s, monotone f) : monotone (Inf s) :=
assume x y h, le_Inf $ assume x' ⟨f, f_in, fx_eq⟩, Inf_le_of_le ⟨f, f_in, rfl⟩ $ fx_eq ▸ m_s _ f_in h
end complete_lattice
section ord_continuous
variables [complete_lattice α] [complete_lattice β]
/-- A function `f` between complete lattices is order-continuous
if it preserves all suprema. -/
def ord_continuous (f : α → β) := ∀s : set α, f (Sup s) = (⨆i∈s, f i)
lemma ord_continuous_sup {f : α → β} {a₁ a₂ : α} (hf : ord_continuous f) : f (a₁ ⊔ a₂) = f a₁ ⊔ f a₂ :=
by rw [← Sup_pair, ← Sup_pair, hf {a₁, a₂}, ← Sup_image, image_pair]
lemma ord_continuous_mono {f : α → β} (hf : ord_continuous f) : monotone f :=
assume a₁ a₂ h,
calc f a₁ ≤ f a₁ ⊔ f a₂ : le_sup_left
... = f (a₁ ⊔ a₂) : (ord_continuous_sup hf).symm
... = _ : by rw [sup_of_le_right h]
end ord_continuous
namespace order_dual
variable (α)
instance [has_Inf α] : has_Sup (order_dual α) := ⟨(Inf : set α → α)⟩
instance [has_Sup α] : has_Inf (order_dual α) := ⟨(Sup : set α → α)⟩
instance [complete_lattice α] : complete_lattice (order_dual α) :=
{ le_Sup := @complete_lattice.Inf_le α _,
Sup_le := @complete_lattice.le_Inf α _,
Inf_le := @complete_lattice.le_Sup α _,
le_Inf := @complete_lattice.Sup_le α _,
.. order_dual.bounded_lattice α, ..order_dual.has_Sup α, ..order_dual.has_Inf α }
instance [complete_linear_order α] : complete_linear_order (order_dual α) :=
{ .. order_dual.complete_lattice α, .. order_dual.decidable_linear_order α }
end order_dual
namespace prod
variables (α β)
instance [has_Inf α] [has_Inf β] : has_Inf (α × β) :=
⟨λs, (Inf (prod.fst '' s), Inf (prod.snd '' s))⟩
instance [has_Sup α] [has_Sup β] : has_Sup (α × β) :=
⟨λs, (Sup (prod.fst '' s), Sup (prod.snd '' s))⟩
instance [complete_lattice α] [complete_lattice β] : complete_lattice (α × β) :=
{ le_Sup := assume s p hab, ⟨le_Sup $ mem_image_of_mem _ hab, le_Sup $ mem_image_of_mem _ hab⟩,
Sup_le := assume s p h,
⟨ Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).1,
Sup_le $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
Inf_le := assume s p hab, ⟨Inf_le $ mem_image_of_mem _ hab, Inf_le $ mem_image_of_mem _ hab⟩,
le_Inf := assume s p h,
⟨ le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).1,
le_Inf $ ball_image_of_ball $ assume p hp, (h p hp).2⟩,
.. prod.bounded_lattice α β,
.. prod.has_Sup α β,
.. prod.has_Inf α β }
end prod
|
d9086e04630709201ef877032ffdf565939d07f2 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/ElabRules.lean | 4eb04b48708831f6760d504c8de4ec7bd78a8c96 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 4,921 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.MacroArgUtil
import Lean.Elab.AuxDef
namespace Lean.Elab.Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do
Term.tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType?
| throwError "expected type must be known"
x expectedType
def elabElabRulesAux (doc? : Option Syntax) (attrKind : Syntax) (k : SyntaxNodeKind) (cat? expty? : Option Syntax) (alts : Array Syntax) : CommandElabM Syntax := do
let alts ← alts.mapM fun alt => match alt with
| `(matchAltExpr| | $pats,* => $rhs) => do
let pat := pats.elemsAndSeps[0]
if !pat.isQuot then
throwUnsupportedSyntax
let quoted := getQuotContent pat
let k' := quoted.getKind
if checkRuleKind k' k then
pure alt
else if k' == choiceKind then
match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with
| none => throwErrorAt alt "invalid elab_rules alternative, expected syntax node kind '{k}'"
| some quoted =>
let pat := pat.setArg 1 quoted
let pats := pats.elemsAndSeps.set! 0 pat
`(matchAltExpr| | $pats,* => $rhs)
else
throwErrorAt alt "invalid elab_rules alternative, unexpected syntax node kind '{k'}'"
| _ => throwUnsupportedSyntax
let catName ← match cat?, expty? with
| some cat, _ => cat.getId
| _, some _ => `term
-- TODO: infer category from quotation kind, possibly even kind of quoted syntax?
| _, _ => throwError "invalid elab_rules command, specify category using `elab_rules : <cat> ...`"
if let some expId := expty? then
if catName == `term then
`($[$doc?:docComment]? @[termElab $(← mkIdentFromRef k):ident]
aux_def elabRules $(mkIdent k) : Lean.Elab.Term.TermElab :=
fun stx expectedType? => Lean.Elab.Command.withExpectedType expectedType? fun $expId => match stx with
$alts:matchAlt* | _ => throwUnsupportedSyntax)
else
throwErrorAt expId "syntax category '{catName}' does not support expected type specification"
else if catName == `term then
`($[$doc?:docComment]? @[termElab $(← mkIdentFromRef k):ident]
aux_def elabRules $(mkIdent k) : Lean.Elab.Term.TermElab :=
fun stx _ => match stx with
$alts:matchAlt* | _ => throwUnsupportedSyntax)
else if catName == `command then
`($[$doc?:docComment]? @[commandElab $(← mkIdentFromRef k):ident]
aux_def elabRules $(mkIdent k) : Lean.Elab.Command.CommandElab :=
fun $alts:matchAlt* | _ => throwUnsupportedSyntax)
else if catName == `tactic then
`($[$doc?:docComment]? @[tactic $(← mkIdentFromRef k):ident]
aux_def elabRules $(mkIdent k) : Lean.Elab.Tactic.Tactic :=
fun $alts:matchAlt* | _ => throwUnsupportedSyntax)
else
-- We considered making the command extensible and support new user-defined categories. We think it is unnecessary.
-- If users want this feature, they add their own `elab_rules` macro that uses this one as a fallback.
throwError "unsupported syntax category '{catName}'"
@[builtinCommandElab «elab_rules»] def elabElabRules : CommandElab :=
adaptExpander fun stx => match stx with
| `($[$doc?:docComment]? $attrKind:attrKind elab_rules $[: $cat?]? $[<= $expty?]? $alts:matchAlt*) =>
expandNoKindMacroRulesAux alts "elab_rules" fun kind? alts =>
`($[$doc?:docComment]? $attrKind:attrKind elab_rules $[(kind := $(mkIdent <$> kind?))]? $[: $cat?]? $[<= $expty?]? $alts:matchAlt*)
| `($[$doc?:docComment]? $attrKind:attrKind elab_rules (kind := $kind) $[: $cat?]? $[<= $expty?]? $alts:matchAlt*) =>
do elabElabRulesAux doc? attrKind (← resolveSyntaxKind kind.getId) cat? expty? alts
| _ => throwUnsupportedSyntax
@[builtinMacro Lean.Parser.Command.elab]
def expandElab : Macro
| `($[$doc?:docComment]? $attrKind:attrKind
elab$[:$prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $args:macroArg* :
$cat $[<= $expectedType?]? => $rhs) => do
let prio ← evalOptPrio prio?
let catName := cat.getId
let (stxParts, patArgs) := (← args.mapM expandMacroArg).unzip
-- name
let name ← match name? with
| some name => pure name.getId
| none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts)
let pat := mkNode ((← Macro.getCurrNamespace) ++ name) patArgs
`($[$doc?:docComment]? $attrKind:attrKind syntax$[:$prec?]? (name := $(← mkIdentFromRef name)) (priority := $(quote prio)) $[$stxParts]* : $cat
$[$doc?:docComment]? elab_rules : $cat $[<= $expectedType?]? | `($pat) => $rhs)
| _ => Macro.throwUnsupported
end Lean.Elab.Command
|
d08eca77ae75a6de39a72ed95e1f8ed2ba5256e9 | fe25de614feb5587799621c41487aaee0d083b08 | /src/Lean/Elab/Declaration.lean | dbf4060d291372ded4c27fad4c9066ac8bd081e4 | [
"Apache-2.0"
] | permissive | pollend/lean4 | e8469c2f5fb8779b773618c3267883cf21fb9fac | c913886938c4b3b83238a3f99673c6c5a9cec270 | refs/heads/master | 1,687,973,251,481 | 1,628,039,739,000 | 1,628,039,739,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,980 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Util.CollectLevelParams
import Lean.Elab.DeclUtil
import Lean.Elab.DefView
import Lean.Elab.Inductive
import Lean.Elab.Structure
import Lean.Elab.MutualDef
import Lean.Elab.DeclarationRange
namespace Lean.Elab.Command
open Meta
/- Auxiliary function for `expandDeclNamespace?` -/
def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) :=
let (id, optUnivDeclStx) := expandDeclIdCore declId
let scpView := extractMacroScopes id
match scpView.name with
| Name.str Name.anonymous s _ => none
| Name.str pre s _ =>
let nameNew := { scpView with name := Name.mkSimple s }.review
if declId.isIdent then
some (pre, mkIdentFrom declId nameNew)
else
some (pre, declId.setArg 0 (mkIdentFrom declId nameNew))
| _ => none
/- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/
def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) :=
if !stx.isOfKind `Lean.Parser.Command.declaration then none
else
let decl := stx[1]
let k := decl.getKind
if k == `Lean.Parser.Command.abbrev ||
k == `Lean.Parser.Command.def ||
k == `Lean.Parser.Command.theorem ||
k == `Lean.Parser.Command.constant ||
k == `Lean.Parser.Command.axiom ||
k == `Lean.Parser.Command.inductive ||
k == `Lean.Parser.Command.classInductive ||
k == `Lean.Parser.Command.structure then
match expandDeclIdNamespace? decl[1] with
| some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId))
| none => none
else if k == `Lean.Parser.Command.instance then
let optDeclId := decl[3]
if optDeclId.isNone then none
else match expandDeclIdNamespace? optDeclId[0] with
| some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId)))
| none => none
else
none
def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do
-- leading_parser "axiom " >> declId >> declSig
let declId := stx[1]
let (binders, typeStx) := expandDeclSig stx[2]
let scopeLevelNames ← getLevelNames
let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers
addDeclarationRanges declName stx
runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do
Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration
let type ← Term.elabType typeStx
Term.synthesizeSyntheticMVarsNoPostponing
let type ← instantiateMVars type
let type ← mkForallFVars xs type
let type ← mkForallFVars vars type (usedOnly := true)
let (type, _) ← Term.levelMVarToParam type
let usedParams := collectLevelParams {} type |>.params
match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with
| Except.error msg => throwErrorAt stx msg
| Except.ok levelParams =>
let decl := Declaration.axiomDecl {
name := declName,
levelParams := levelParams,
type := type,
isUnsafe := modifiers.isUnsafe
}
Term.ensureNoUnassignedMVars decl
addDecl decl
Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking
if isExtern (← getEnv) declName then
compileDecl decl
Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation
/-
leading_parser "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor
leading_parser atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving
-/
private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do
checkValidInductiveModifier modifiers
let (binders, type?) := expandOptDeclSig decl[2]
let declId := decl[1]
let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers
addDeclarationRanges declName decl
let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do
-- def ctor := leading_parser " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig
let ctorModifiers ← elabModifiers ctor[1]
if ctorModifiers.isPrivate && modifiers.isPrivate then
throwError "invalid 'private' constructor in a 'private' inductive datatype"
if ctorModifiers.isProtected && modifiers.isPrivate then
throwError "invalid 'protected' constructor in a 'private' inductive datatype"
checkValidCtorModifier ctorModifiers
let ctorName := ctor.getIdAt 2
let ctorName := declName ++ ctorName
let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName
let inferMod := !ctor[3].isNone
let (binders, type?) := expandOptDeclSig ctor[4]
addDocString' ctorName ctorModifiers.docString?
addAuxDeclarationRanges ctorName ctor ctor[2]
pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView }
let classes ← getOptDerivingClasses decl[5]
pure {
ref := decl
modifiers := modifiers
shortDeclName := name
declName := declName
levelNames := levelNames
binders := binders
type? := type?
ctors := ctors
derivingClasses := classes
}
private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView :=
inductiveSyntaxToView modifiers decl
def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do
let v ← inductiveSyntaxToView modifiers stx
elabInductiveViews #[v]
def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do
let modifiers := modifiers.addAttribute { name := `class }
let v ← classInductiveSyntaxToView modifiers stx
elabInductiveViews #[v]
@[builtinCommandElab declaration]
def elabDeclaration : CommandElab := fun stx =>
match expandDeclNamespace? stx with
| some (ns, newStx) => do
let ns := mkIdentFrom stx ns
let newStx ← `(namespace $ns:ident $newStx end $ns:ident)
withMacroExpansion stx newStx $ elabCommand newStx
| none => do
let modifiers ← elabModifiers stx[0]
let decl := stx[1]
let declKind := decl.getKind
if declKind == `Lean.Parser.Command.«axiom» then
elabAxiom modifiers decl
else if declKind == `Lean.Parser.Command.«inductive» then
elabInductive modifiers decl
else if declKind == `Lean.Parser.Command.classInductive then
elabClassInductive modifiers decl
else if declKind == `Lean.Parser.Command.«structure» then
elabStructure modifiers decl
else if isDefLike decl then
elabMutualDef #[stx]
else
throwError "unexpected declaration"
/- Return true if all elements of the mutual-block are inductive declarations. -/
private def isMutualInductive (stx : Syntax) : Bool :=
stx[1].getArgs.all fun elem =>
let decl := elem[1]
let declKind := decl.getKind
declKind == `Lean.Parser.Command.inductive
private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do
let views ← elems.mapM fun stx => do
let modifiers ← elabModifiers stx[0]
inductiveSyntaxToView modifiers stx[1]
elabInductiveViews views
/- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/
private def isMutualDef (stx : Syntax) : Bool :=
stx[1].getArgs.all fun elem =>
let decl := elem[1]
isDefLike decl
private def isMutualPreambleCommand (stx : Syntax) : Bool :=
let k := stx.getKind
k == `Lean.Parser.Command.variable ||
k == `Lean.Parser.Command.variables ||
k == `Lean.Parser.Command.universe ||
k == `Lean.Parser.Command.universe ||
k == `Lean.Parser.Command.check ||
k == `Lean.Parser.Command.set_option ||
k == `Lean.Parser.Command.open
private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) :=
let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) :=
if h : i < elems.size then
let elem := elems.get ⟨i, h⟩
if isMutualPreambleCommand elem then
loop (i+1)
else if i == 0 then
none -- `mutual` block does not contain any preamble commands
else
some (elems[0:i], elems[i:elems.size])
else
none -- a `mutual` block containing only preamble commands is not a valid `mutual` block
loop 0
@[builtinMacro Lean.Parser.Command.mutual]
def expandMutualNamespace : Macro := fun stx => do
let mut ns? := none
let mut elemsNew := #[]
for elem in stx[1].getArgs do
match ns?, expandDeclNamespace? elem with
| _, none => elemsNew := elemsNew.push elem
| none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem
| some nsCurr, some (nsNew, elem) =>
if nsCurr == nsNew then
elemsNew := elemsNew.push elem
else
Macro.throwErrorAt elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration"
match ns? with
| some ns =>
let ns := mkIdentFrom stx ns
let stxNew := stx.setArg 1 (mkNullNode elemsNew)
`(namespace $ns:ident $stxNew end $ns:ident)
| none => Macro.throwUnsupported
@[builtinMacro Lean.Parser.Command.mutual]
def expandMutualElement : Macro := fun stx => do
let mut elemsNew := #[]
let mut modified := false
for elem in stx[1].getArgs do
match (← expandMacro? elem) with
| some elemNew => elemsNew := elemsNew.push elemNew; modified := true
| none => elemsNew := elemsNew.push elem
if modified then
pure $ stx.setArg 1 (mkNullNode elemsNew)
else
Macro.throwUnsupported
@[builtinMacro Lean.Parser.Command.mutual]
def expandMutualPreamble : Macro := fun stx =>
match splitMutualPreamble stx[1].getArgs with
| none => Macro.throwUnsupported
| some (preamble, rest) => do
let secCmd ← `(section)
let newMutual := stx.setArg 1 (mkNullNode rest)
let endCmd ← `(end)
pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd])
@[builtinCommandElab «mutual»]
def elabMutual : CommandElab := fun stx => do
if isMutualInductive stx then
elabMutualInductive stx[1].getArgs
else if isMutualDef stx then
elabMutualDef stx[1].getArgs
else
throwError "invalid mutual block"
/- leading_parser "attribute " >> "[" >> sepBy1 (eraseAttr <|> Term.attrInstance) ", " >> "]" >> many1 ident -/
@[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do
let mut attrInsts := #[]
let mut toErase := #[]
for attrKindStx in stx[2].getSepArgs do
if attrKindStx.getKind == ``Lean.Parser.Command.eraseAttr then
let attrName := attrKindStx[1].getId.eraseMacroScopes
unless isAttribute (← getEnv) attrName do
throwError "unknown attribute [{attrName}]"
toErase := toErase.push attrName
else
attrInsts := attrInsts.push attrKindStx
let attrs ← elabAttrs attrInsts
let idents := stx[4].getArgs
for ident in idents do withRef ident <| liftTermElabM none do
let declName ← resolveGlobalConstNoOverloadWithInfo ident
Term.applyAttributes declName attrs
for attrName in toErase do
Attribute.erase declName attrName
def expandInitCmd (builtin : Bool) : Macro := fun stx => do
let optVisibility := stx[0]
let optHeader := stx[2]
let doSeq := stx[3]
let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init
if optHeader.isNone then
unless optVisibility.isNone do
Macro.throwError "invalid initialization command, 'visibility' modifer is not allowed"
`(@[$attrId:ident]def initFn : IO Unit := do $doSeq)
else
let id := optHeader[0]
let type := optHeader[1][1]
if optVisibility.isNone then
`(def initFn : IO $type := do $doSeq
@[$attrId:ident initFn] constant $id : $type)
else if optVisibility[0].getKind == ``Parser.Command.private then
`(def initFn : IO $type := do $doSeq
@[$attrId:ident initFn] private constant $id : $type)
else if optVisibility[0].getKind == ``Parser.Command.protected then
`(def initFn : IO $type := do $doSeq
@[$attrId:ident initFn] protected constant $id : $type)
else
Macro.throwError "unexpected visibility annotation"
@[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro :=
expandInitCmd (builtin := false)
@[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro :=
expandInitCmd (builtin := true)
end Lean.Elab.Command
|
c0006df1669b11187366fbbc843aa42cb4834646 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/category/Module/kernels.lean | 6c48b46f78f0f9da40f9f088693775b310908edf | [
"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 | 4,169 | lean | /-
Copyright (c) 2020 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import algebra.category.Module.epi_mono
/-!
# The concrete (co)kernels in the category of modules are (co)kernels in the categorical sense.
-/
open category_theory
open category_theory.limits
open category_theory.limits.walking_parallel_pair
universes u v
namespace Module
variables {R : Type u} [ring R]
section
variables {M N : Module.{v} R} (f : M ⟶ N)
/-- The kernel cone induced by the concrete kernel. -/
def kernel_cone : kernel_fork f :=
kernel_fork.of_ι (as_hom f.ker.subtype) $ by tidy
/-- The kernel of a linear map is a kernel in the categorical sense. -/
def kernel_is_limit : is_limit (kernel_cone f) :=
fork.is_limit.mk _
(λ s, linear_map.cod_restrict f.ker (fork.ι s) (λ c, linear_map.mem_ker.2 $
by { rw [←@function.comp_apply _ _ _ f (fork.ι s) c, ←coe_comp, fork.condition,
has_zero_morphisms.comp_zero (fork.ι s) N], refl }))
(λ s, linear_map.subtype_comp_cod_restrict _ _ _)
(λ s m h, linear_map.ext $ λ x, subtype.ext_iff_val.2 $
have h₁ : (m ≫ (kernel_cone f).π.app zero).to_fun = (s.π.app zero).to_fun,
by { congr, exact h zero },
by convert @congr_fun _ _ _ _ h₁ x )
/-- The cokernel cocone induced by the projection onto the quotient. -/
def cokernel_cocone : cokernel_cofork f :=
cokernel_cofork.of_π (as_hom f.range.mkq) $ linear_map.range_mkq_comp _
/-- The projection onto the quotient is a cokernel in the categorical sense. -/
def cokernel_is_colimit : is_colimit (cokernel_cocone f) :=
cofork.is_colimit.mk _
(λ s, f.range.liftq (cofork.π s) $ linear_map.range_le_ker_iff.2 $ cokernel_cofork.condition s)
(λ s, f.range.liftq_mkq (cofork.π s) _)
(λ s m h,
begin
haveI : epi (as_hom f.range.mkq) := (epi_iff_range_eq_top _).mpr (submodule.range_mkq _),
apply (cancel_epi (as_hom f.range.mkq)).1,
convert h walking_parallel_pair.one,
exact submodule.liftq_mkq _ _ _
end)
end
/-- The category of R-modules has kernels, given by the inclusion of the kernel submodule. -/
lemma has_kernels_Module : has_kernels (Module R) :=
⟨λ X Y f, has_limit.mk ⟨_, kernel_is_limit f⟩⟩
/-- The category or R-modules has cokernels, given by the projection onto the quotient. -/
lemma has_cokernels_Module : has_cokernels (Module R) :=
⟨λ X Y f, has_colimit.mk ⟨_, cokernel_is_colimit f⟩⟩
open_locale Module
local attribute [instance] has_kernels_Module
local attribute [instance] has_cokernels_Module
variables {G H : Module.{v} R} (f : G ⟶ H)
/--
The categorical kernel of a morphism in `Module`
agrees with the usual module-theoretical kernel.
-/
noncomputable def kernel_iso_ker {G H : Module.{v} R} (f : G ⟶ H) :
kernel f ≅ Module.of R (f.ker) :=
limit.iso_limit_cone ⟨_, kernel_is_limit f⟩
-- We now show this isomorphism commutes with the inclusion of the kernel into the source.
@[simp, elementwise] lemma kernel_iso_ker_inv_kernel_ι :
(kernel_iso_ker f).inv ≫ kernel.ι f = f.ker.subtype :=
limit.iso_limit_cone_inv_π _ _
@[simp, elementwise] lemma kernel_iso_ker_hom_ker_subtype :
(kernel_iso_ker f).hom ≫ f.ker.subtype = kernel.ι f :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ (limit.is_limit _) zero
/--
The categorical cokernel of a morphism in `Module`
agrees with the usual module-theoretical quotient.
-/
noncomputable def cokernel_iso_range_quotient {G H : Module.{v} R} (f : G ⟶ H) :
cokernel f ≅ Module.of R (H ⧸ f.range) :=
colimit.iso_colimit_cocone ⟨_, cokernel_is_colimit f⟩
-- We now show this isomorphism commutes with the projection of target to the cokernel.
@[simp, elementwise] lemma cokernel_π_cokernel_iso_range_quotient_hom :
cokernel.π f ≫ (cokernel_iso_range_quotient f).hom = f.range.mkq :=
by { convert colimit.iso_colimit_cocone_ι_hom _ _; refl, }
@[simp, elementwise] lemma range_mkq_cokernel_iso_range_quotient_inv :
↿f.range.mkq ≫ (cokernel_iso_range_quotient f).inv = cokernel.π f :=
by { convert colimit.iso_colimit_cocone_ι_inv ⟨_, cokernel_is_colimit f⟩ _; refl, }
end Module
|
2e94ec611d5c7e5af1ee8ce2251cad467d4d1efb | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/currying.lean | 3df0f37ed015586343284d49ae33bb462ce2d859 | [
"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 | 3,918 | 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.products.bifunctor
/-!
# Curry and uncurry, as functors.
We define `curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E))` and `uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E)`,
and verify that they provide an equivalence of categories
`currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E)`.
-/
namespace category_theory
universes v₁ v₂ v₃ u₁ u₂ u₃
variables {C : Type u₁} [category.{v₁} C]
{D : Type u₂} [category.{v₂} D]
{E : Type u₃} [category.{v₃} E]
/--
The uncurrying functor, taking a functor `C ⥤ (D ⥤ E)` and producing a functor `(C × D) ⥤ E`.
-/
def uncurry : (C ⥤ (D ⥤ E)) ⥤ ((C × D) ⥤ E) :=
{ obj := λ F,
{ obj := λ X, (F.obj X.1).obj X.2,
map := λ X Y f, (F.map f.1).app X.2 ≫ (F.obj Y.1).map f.2,
map_comp' := λ X Y Z f g,
begin
simp only [prod_comp_fst, prod_comp_snd, functor.map_comp,
nat_trans.comp_app, category.assoc],
slice_lhs 2 3 { rw ← nat_trans.naturality },
rw category.assoc,
end },
map := λ F G T,
{ app := λ X, (T.app X.1).app X.2,
naturality' := λ X Y f,
begin
simp only [prod_comp_fst, prod_comp_snd, category.comp_id, category.assoc,
functor.map_id, functor.map_comp, nat_trans.id_app, nat_trans.comp_app],
slice_lhs 2 3 { rw nat_trans.naturality },
slice_lhs 1 2 { rw [←nat_trans.comp_app, nat_trans.naturality, nat_trans.comp_app] },
rw category.assoc,
end } }.
/--
The object level part of the currying functor. (See `curry` for the functorial version.)
-/
def curry_obj (F : (C × D) ⥤ E) : C ⥤ (D ⥤ E) :=
{ obj := λ X,
{ obj := λ Y, F.obj (X, Y),
map := λ Y Y' g, F.map (𝟙 X, g) },
map := λ X X' f, { app := λ Y, F.map (f, 𝟙 Y) } }
/--
The currying functor, taking a functor `(C × D) ⥤ E` and producing a functor `C ⥤ (D ⥤ E)`.
-/
def curry : ((C × D) ⥤ E) ⥤ (C ⥤ (D ⥤ E)) :=
{ obj := λ F, curry_obj F,
map := λ F G T,
{ app := λ X,
{ app := λ Y, T.app (X, Y),
naturality' := λ Y Y' g,
begin
dsimp [curry_obj],
rw nat_trans.naturality,
end },
naturality' := λ X X' f,
begin
ext, dsimp [curry_obj],
rw nat_trans.naturality,
end } }.
@[simp] lemma uncurry.obj_obj {F : C ⥤ (D ⥤ E)} {X : C × D} :
(uncurry.obj F).obj X = (F.obj X.1).obj X.2 := rfl
@[simp] lemma uncurry.obj_map {F : C ⥤ (D ⥤ E)} {X Y : C × D} {f : X ⟶ Y} :
(uncurry.obj F).map f = ((F.map f.1).app X.2) ≫ ((F.obj Y.1).map f.2) := rfl
@[simp] lemma uncurry.map_app {F G : C ⥤ (D ⥤ E)} {α : F ⟶ G} {X : C × D} :
(uncurry.map α).app X = (α.app X.1).app X.2 := rfl
@[simp] lemma curry.obj_obj_obj
{F : (C × D) ⥤ E} {X : C} {Y : D} :
((curry.obj F).obj X).obj Y = F.obj (X, Y) := rfl
@[simp] lemma curry.obj_obj_map
{F : (C × D) ⥤ E} {X : C} {Y Y' : D} {g : Y ⟶ Y'} :
((curry.obj F).obj X).map g = F.map (𝟙 X, g) := rfl
@[simp] lemma curry.obj_map_app {F : (C × D) ⥤ E} {X X' : C} {f : X ⟶ X'} {Y} :
((curry.obj F).map f).app Y = F.map (f, 𝟙 Y) := rfl
@[simp] lemma curry.map_app_app {F G : (C × D) ⥤ E} {α : F ⟶ G} {X} {Y} :
((curry.map α).app X).app Y = α.app (X, Y) := rfl
/--
The equivalence of functor categories given by currying/uncurrying.
-/
@[simps] -- create projection simp lemmas even though this isn't a `{ .. }`.
def currying : (C ⥤ (D ⥤ E)) ≌ ((C × D) ⥤ E) :=
equivalence.mk uncurry curry
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, nat_iso.of_components (λ Y, iso.refl _) (by tidy)) (by tidy)) (by tidy))
(nat_iso.of_components (λ F, nat_iso.of_components
(λ X, eq_to_iso (by simp)) (by tidy)) (by tidy))
end category_theory
|
c6ec84f728af3e6b98a6096e39b1496ac0c709fc | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /archive/100-theorems-list/9_area_of_a_circle.lean | 23d77b6715d7ad4569d8e5f4ab4ce8b864c30f7e | [
"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 | 6,420 | lean | /-
Copyright (c) 2021 James Arthur, Benjamin Davidson, Andrew Souther. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: James Arthur, Benjamin Davidson, Andrew Souther
-/
import measure_theory.interval_integral
import analysis.special_functions.sqrt
/-!
# Freek № 9: The Area of a Circle
In this file we show that the area of a disc with nonnegative radius `r` is `π * r^2`. The main
tools our proof uses are `volume_region_between_eq_integral`, which allows us to represent the area
of the disc as an integral, and `interval_integral.integral_eq_sub_of_has_deriv_at'_of_le`, the
second fundamental theorem of calculus.
We begin by defining `disc` in `ℝ × ℝ`, then show that `disc` can be represented as the
`region_between` two functions.
Though not necessary for the main proof, we nonetheless choose to include a proof of the
measurability of the disc in order to convince the reader that the set whose volume we will be
calculating is indeed measurable and our result is therefore meaningful.
In the main proof, `area_disc`, we use `volume_region_between_eq_integral` followed by
`interval_integral.integral_of_le` to reduce our goal to a single `interval_integral`:
`∫ (x : ℝ) in -r..r, 2 * sqrt (r ^ 2 - x ^ 2) = π * r ^ 2`.
After disposing of the trivial case `r = 0`, we show that `λ x, 2 * sqrt (r ^ 2 - x ^ 2)` is equal
to the derivative of `λ x, r ^ 2 * arcsin (x / r) + x * sqrt (r ^ 2 - x ^ 2)` everywhere on
`Ioo (-r) r` and that those two functions are continuous, then apply the second fundamental theorem
of calculus with those facts. Some simple algebra then completes the proof.
Note that we choose to define `disc` as a set of points in `ℝ ⨯ ℝ`. This is admittedly not ideal; it
would be more natural to define `disc` as a `metric.ball` in `euclidean_space ℝ (fin 2)` (as well as
to provide a more general proof in higher dimensions). However, our proof indirectly relies on a
number of theorems (particularly `measure_theory.measure.prod_apply`) which do not yet exist for
Euclidean space, thus forcing us to use this less-preferable definition. As `measure_theory.pi`
continues to develop, it should eventually become possible to redefine `disc` and extend our proof
to the n-ball.
-/
open set real measure_theory interval_integral
open_locale real nnreal
/-- A disc of radius `r` is defined as the collection of points `(p.1, p.2)` in `ℝ × ℝ` such that
`p.1 ^ 2 + p.2 ^ 2 < r ^ 2`.
Note that this definition is not equivalent to `metric.ball (0 : ℝ × ℝ) r`. This was done
intentionally because `dist` in `ℝ × ℝ` is defined as the uniform norm, making the `metric.ball`
in `ℝ × ℝ` a square, not a disc.
See the module docstring for an explanation of why we don't define the disc in Euclidean space. -/
def disc (r : ℝ) := {p : ℝ × ℝ | p.1 ^ 2 + p.2 ^ 2 < r ^ 2}
variable (r : ℝ≥0)
/-- A disc of radius `r` can be represented as the region between the two curves
`λ x, - sqrt (r ^ 2 - x ^ 2)` and `λ x, sqrt (r ^ 2 - x ^ 2)`. -/
lemma disc_eq_region_between :
disc r = region_between (λ x, -sqrt (r^2 - x^2)) (λ x, sqrt (r^2 - x^2)) (Ioc (-r) r) :=
begin
ext p,
simp only [disc, region_between, mem_set_of_eq, mem_Ioo, mem_Ioc, pi.neg_apply],
split;
intro h,
{ cases abs_lt_of_sq_lt_sq' (lt_of_add_lt_of_nonneg_left h (sq_nonneg p.2)) r.2,
rw [add_comm, ← lt_sub_iff_add_lt] at h,
exact ⟨⟨left, right.le⟩, sq_lt.mp h⟩ },
{ rw [add_comm, ← lt_sub_iff_add_lt],
exact sq_lt.mpr h.2 },
end
/-- The disc is a `measurable_set`. -/
theorem measurable_set_disc : measurable_set (disc r) :=
by apply measurable_set_lt; apply continuous.measurable; continuity
/-- The area of a disc with radius `r` is `π * r ^ 2`. -/
theorem area_disc : volume (disc r) = nnreal.pi * r ^ 2 :=
begin
let f := λ x, sqrt (r ^ 2 - x ^ 2),
let F := λ x, (r:ℝ) ^ 2 * arcsin (r⁻¹ * x) + x * sqrt (r ^ 2 - x ^ 2),
have hf : continuous f := by continuity,
suffices : ∫ x in -r..r, 2 * f x = nnreal.pi * r ^ 2,
{ have h : integrable_on f (Ioc (-r) r) :=
(hf.integrable_on_compact is_compact_Icc).mono_set Ioc_subset_Icc_self,
calc volume (disc r)
= volume (region_between (λ x, -f x) f (Ioc (-r) r)) : by rw disc_eq_region_between
... = ennreal.of_real (∫ x in Ioc (-r:ℝ) r, (f - has_neg.neg ∘ f) x) :
volume_region_between_eq_integral
h.neg h measurable_set_Ioc (λ x hx, neg_le_self (sqrt_nonneg _))
... = ennreal.of_real (∫ x in (-r:ℝ)..r, 2 * f x) : by simp [two_mul, integral_of_le]
... = nnreal.pi * r ^ 2 : by rw_mod_cast [this, ← ennreal.coe_nnreal_eq], },
obtain ⟨hle, (heq | hlt)⟩ := ⟨nnreal.coe_nonneg r, hle.eq_or_lt⟩, { simp [← heq] },
have hderiv : ∀ x ∈ Ioo (-r:ℝ) r, has_deriv_at F (2 * f x) x,
{ rintros x ⟨hx1, hx2⟩,
convert ((has_deriv_at_const x ((r:ℝ)^2)).mul ((has_deriv_at_arcsin _ _).comp x
((has_deriv_at_const x (r:ℝ)⁻¹).mul (has_deriv_at_id' x)))).add
((has_deriv_at_id' x).mul (((has_deriv_at_id' x).pow.const_sub ((r:ℝ)^2)).sqrt _)),
{ have h : sqrt (1 - x ^ 2 / r ^ 2) * r = sqrt (r ^ 2 - x ^ 2),
{ rw [← sqrt_sq hle, ← sqrt_mul, sub_mul, sqrt_sq hle, div_mul_eq_mul_div_comm,
div_self (pow_ne_zero 2 hlt.ne'), one_mul, mul_one],
simpa [sqrt_sq hle, div_le_one (pow_pos hlt 2)] using sq_le_sq' hx1.le hx2.le },
field_simp,
rw [h, mul_left_comm, ← sq, neg_mul_eq_mul_neg, mul_div_mul_left (-x^2) _ two_ne_zero,
add_left_comm, div_add_div_same, tactic.ring.add_neg_eq_sub, div_sqrt, two_mul] },
{ suffices : -(1:ℝ) < r⁻¹ * x, by exact this.ne',
calc -(1:ℝ) = r⁻¹ * -r : by simp [hlt.ne']
... < r⁻¹ * x : by nlinarith [inv_pos.mpr hlt] },
{ suffices : (r:ℝ)⁻¹ * x < 1, by exact this.ne,
calc (r:ℝ)⁻¹ * x < r⁻¹ * r : by nlinarith [inv_pos.mpr hlt]
... = 1 : inv_mul_cancel hlt.ne' },
{ nlinarith } },
have hcont := (by continuity : continuous F).continuous_on,
have hcont' := (continuous_const.mul hf).continuous_on,
calc ∫ x in -r..r, 2 * f x
= F r - F (-r) : integral_eq_sub_of_has_deriv_at'_of_le (neg_le_self r.2) hcont hderiv hcont'
... = nnreal.pi * r ^ 2 : by norm_num [F, inv_mul_cancel hlt.ne', ← mul_div_assoc, mul_comm π],
end
|
8fa62c0d4f545cfc67d89f58013445d643924402 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/category_theory/category/Quiv.lean | 69a43a4ec20f0c55e2744aaae0333257a830c22a | [
"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 | 3,138 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.path_category
import category_theory.category.Cat
/-!
# The category of quivers
The category of (bundled) quivers, and the free/forgetful adjunction between `Cat` and `Quiv`.
-/
universes v u
namespace category_theory
/-- Category of quivers. -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
def Quiv := bundled quiver.{(v+1) u}
namespace Quiv
instance : has_coe_to_sort Quiv (Type u) :=
{ coe := bundled.α }
instance str (C : Quiv.{v u}) : quiver.{(v+1) u} C := C.str
/-- Construct a bundled `Quiv` from the underlying type and the typeclass. -/
def of (C : Type u) [quiver.{v+1} C] : Quiv.{v u} := bundled.of C
instance : inhabited Quiv := ⟨Quiv.of (quiver.empty pempty)⟩
/-- Category structure on `Quiv` -/
instance category : large_category.{max v u} Quiv.{v u} :=
{ hom := λ C D, prefunctor C D,
id := λ C, prefunctor.id C,
comp := λ C D E F G, prefunctor.comp F G,
id_comp' := λ C D F, by cases F; refl,
comp_id' := λ C D F, by cases F; refl,
assoc' := by intros; refl }
/-- The forgetful functor from categories to quivers. -/
@[simps]
def forget : Cat.{v u} ⥤ Quiv.{v u} :=
{ obj := λ C, Quiv.of C,
map := λ C D F, F.to_prefunctor, }
end Quiv
namespace Cat
/-- The functor sending each quiver to its path category. -/
@[simps]
def free : Quiv.{v u} ⥤ Cat.{(max u v) u} :=
{ obj := λ V, Cat.of (paths V),
map := λ V W F,
{ obj := λ X, F.obj X,
map := λ X Y f, F.map_path f,
map_comp' := λ X Y Z f g, F.map_path_comp f g, },
map_id' := λ V, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl },
map_comp' := λ U V W F G,
by { change (show paths U ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } }
end Cat
namespace Quiv
/-- Any prefunctor into a category lifts to a functor from the path category. -/
@[simps]
def lift {V : Type u} [quiver.{v+1} V] {C : Type u} [category.{v} C]
(F : prefunctor V C) : paths V ⥤ C :=
{ obj := λ X, F.obj X,
map := λ X Y f, compose_path (F.map_path f), }
-- We might construct `of_lift_iso_self : paths.of ⋙ lift F ≅ F`
-- (and then show that `lift F` is initial amongst such functors)
-- but it would require lifting quite a bit of machinery to quivers!
/--
The adjunction between forming the free category on a quiver, and forgetting a category to a quiver.
-/
def adj : Cat.free ⊣ Quiv.forget :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ V C,
{ to_fun := λ F, paths.of.comp F.to_prefunctor,
inv_fun := λ F, lift F,
left_inv := λ F, by { ext, { erw (eq_conj_eq_to_hom _).symm, apply category.id_comp }, refl },
right_inv := begin
rintro ⟨obj,map⟩,
dsimp only [prefunctor.comp],
congr,
ext X Y f,
exact category.id_comp _,
end, },
hom_equiv_naturality_left_symm' := λ V W C f g,
by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } }
end Quiv
end category_theory
|
ab6ecb521a0345568f73a3ddcc0cdcb6933f4adf | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Meta/Tactic/Util.lean | 278cbf4381d691e333d290390cfacc27c7fa978a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 6,321 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.ForEachExpr
import Lean.Meta.Basic
import Lean.Meta.AppBuilder
import Lean.Meta.PPGoal
namespace Lean.Meta
/-- Get the user name of the given metavariable. -/
def _root_.Lean.MVarId.getTag (mvarId : MVarId) : MetaM Name :=
return (← mvarId.getDecl).userName
@[deprecated MVarId.getTag]
def getMVarTag (mvarId : MVarId) : MetaM Name :=
mvarId.getTag
def _root_.Lean.MVarId.setTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do
modify fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag }
@[deprecated MVarId.setTag]
def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do
mvarId.setTag tag
def appendTag (tag : Name) (suffix : Name) : Name :=
tag.modifyBase (· ++ suffix.eraseMacroScopes)
def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do
let tag ← mvarId.getTag
mvarId.setTag (appendTag tag suffix)
def mkFreshExprSyntheticOpaqueMVar (type : Expr) (tag : Name := Name.anonymous) : MetaM Expr :=
mkFreshExprMVar type MetavarKind.syntheticOpaque tag
def throwTacticEx (tacticName : Name) (mvarId : MVarId) (msg : MessageData) : MetaM α :=
if msg.isEmpty then
throwError "tactic '{tacticName}' failed\n{mvarId}"
else
throwError "tactic '{tacticName}' failed, {msg}\n{mvarId}"
def throwNestedTacticEx {α} (tacticName : Name) (ex : Exception) : MetaM α := do
throwError "tactic '{tacticName}' failed, nested error:\n{ex.toMessageData}"
/-- Throw a tactic exception with given tactic name if the given metavariable is assigned. -/
def _root_.Lean.MVarId.checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do
if (← mvarId.isAssigned) then
throwTacticEx tacticName mvarId "metavariable has already been assigned"
@[deprecated MVarId.checkNotAssigned]
def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit := do
mvarId.checkNotAssigned tacticName
/-- Get the type the given metavariable. -/
def _root_.Lean.MVarId.getType (mvarId : MVarId) : MetaM Expr :=
return (← mvarId.getDecl).type
@[deprecated MVarId.getType]
def getMVarType (mvarId : MVarId) : MetaM Expr :=
mvarId.getType
/-- Get the type the given metavariable after instantiating metavariables and reducing to
weak head normal form. -/
def _root_.Lean.MVarId.getType' (mvarId : MVarId) : MetaM Expr := do
whnf (← instantiateMVars (← mvarId.getType))
@[deprecated MVarId.getType']
def getMVarType' (mvarId : MVarId) : MetaM Expr := do
mvarId.getType'
builtin_initialize registerTraceClass `Meta.Tactic
/-- Assign `mvarId` to `sorryAx` -/
def _root_.Lean.MVarId.admit (mvarId : MVarId) (synthetic := true) : MetaM Unit :=
mvarId.withContext do
mvarId.checkNotAssigned `admit
let mvarType ← mvarId.getType
let val ← mkSorry mvarType synthetic
mvarId.assign val
@[deprecated MVarId.admit]
def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit :=
mvarId.admit synthetic
/-- Beta reduce the metavariable type head -/
def _root_.Lean.MVarId.headBetaType (mvarId : MVarId) : MetaM Unit := do
mvarId.setType (← mvarId.getType).headBeta
@[deprecated MVarId.headBetaType]
def headBetaMVarType (mvarId : MVarId) : MetaM Unit := do
mvarId.headBetaType
/-- Collect nondependent hypotheses that are propositions. -/
def _root_.Lean.MVarId.getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) :=
let removeDeps (e : Expr) (candidates : FVarIdHashSet) : MetaM FVarIdHashSet := do
let e ← instantiateMVars e
let visit : StateRefT FVarIdHashSet MetaM FVarIdHashSet := do
e.forEach fun
| Expr.fvar fvarId => modify fun s => s.erase fvarId
| _ => pure ()
get
visit |>.run' candidates
mvarId.withContext do
let mut candidates : FVarIdHashSet := {}
for localDecl in (← getLCtx) do
unless localDecl.isImplementationDetail do
candidates ← removeDeps localDecl.type candidates
match localDecl.value? with
| none => pure ()
| some value => candidates ← removeDeps value candidates
if (← isProp localDecl.type) && !localDecl.hasValue then
candidates := candidates.insert localDecl.fvarId
candidates ← removeDeps (← mvarId.getType) candidates
if candidates.isEmpty then
return #[]
else
let mut result := #[]
for localDecl in (← getLCtx) do
if candidates.contains localDecl.fvarId then
result := result.push localDecl.fvarId
return result
@[deprecated MVarId.getNondepPropHyps]
def getNondepPropHyps (mvarId : MVarId) : MetaM (Array FVarId) :=
mvarId.getNondepPropHyps
partial def saturate (mvarId : MVarId) (x : MVarId → MetaM (Option (List MVarId))) : MetaM (List MVarId) := do
let (_, r) ← go mvarId |>.run #[]
return r.toList
where
go (mvarId : MVarId) : StateRefT (Array MVarId) MetaM Unit :=
withIncRecDepth do
match (← x mvarId) with
| none => modify fun s => s.push mvarId
| some mvarIds => mvarIds.forM go
def exactlyOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM MVarId :=
match mvarIds with
| [mvarId] => return mvarId
| _ => throwError msg
def ensureAtMostOne (mvarIds : List MVarId) (msg : MessageData := "unexpected number of goals") : MetaM (Option MVarId) :=
match mvarIds with
| [] => return none
| [mvarId] => return some mvarId
| _ => throwError msg
/-- Return all propositions in the local context. -/
def getPropHyps : MetaM (Array FVarId) := do
let mut result := #[]
for localDecl in (← getLCtx) do
unless localDecl.isImplementationDetail do
if (← isProp localDecl.type) then
result := result.push localDecl.fvarId
return result
def _root_.Lean.MVarId.inferInstance (mvarId : MVarId) : MetaM Unit := mvarId.withContext do
mvarId.checkNotAssigned `infer_instance
let synthVal ← synthInstance (← mvarId.getType)
unless (← isDefEq (mkMVar mvarId) synthVal) do
throwTacticEx `infer_instance mvarId "`infer_instance` tactic failed to assign instance"
inductive TacticResultCNM where
| closed
| noChange
| modified (mvarId : MVarId)
end Lean.Meta
|
5ddeb887cac09a70a5bb2770b9606951f4e06c86 | bb31430994044506fa42fd667e2d556327e18dfe | /src/topology/metric_space/emetric_space.lean | 1146f5df46403e9117c7c3651b3d0ac81b6c4dc5 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 51,221 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.nat.interval
import data.real.ennreal
import topology.uniform_space.pi
import topology.uniform_space.uniform_convergence
import topology.uniform_space.uniform_embedding
/-!
# Extended metric spaces
This file is devoted to the definition and study of `emetric_spaces`, i.e., metric
spaces in which the distance is allowed to take the value ∞. This extended distance is
called `edist`, and takes values in `ℝ≥0∞`.
Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces
and topological spaces. For example: open and closed sets, compactness, completeness, continuity and
uniform continuity.
The class `emetric_space` therefore extends `uniform_space` (and `topological_space`).
Since a lot of elementary properties don't require `eq_of_edist_eq_zero` we start setting up the
theory of `pseudo_emetric_space`, where we don't require `edist x y = 0 → x = y` and we specialize
to `emetric_space` at the end.
-/
open set filter classical
open_locale uniformity topological_space big_operators filter nnreal ennreal
universes u v w
variables {α : Type u} {β : Type v} {X : Type*}
/-- Characterizing uniformities associated to a (generalized) distance function `D`
in terms of the elements of the uniformity. -/
theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β)
(D : α → α → β) (H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) :
U = ⨅ ε>z, 𝓟 {p:α×α | D p.1 p.2 < ε} :=
le_antisymm
(le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩)
(λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in
mem_infi_of_mem ε $ mem_infi_of_mem ε0 $ mem_principal.2 $ λ ⟨a, b⟩, h)
/-- `has_edist α` means that `α` is equipped with an extended distance. -/
class has_edist (α : Type*) := (edist : α → α → ℝ≥0∞)
export has_edist (edist)
/-- Creating a uniform space from an extended distance. -/
def uniform_space_of_edist
(edist : α → α → ℝ≥0∞)
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α :=
uniform_space.of_core
{ uniformity := (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt},
comp :=
le_infi $ assume ε, le_infi $ assume h,
have (2 : ℝ≥0∞) = (2 : ℕ) := by simp,
have A : 0 < ε / 2 := ennreal.div_pos_iff.2
⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩,
lift'_le
(mem_infi_of_mem (ε / 2) $ mem_infi_of_mem A (subset.refl _)) $
have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε,
from assume a b c hac hcb,
calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _
... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb
... = ε : by rw [ennreal.add_halves],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] }
-- the uniform structure is embedded in the emetric space structure
-- to avoid instance diamond issues. See Note [forgetful inheritance].
/-- Extended (pseudo) metric spaces, with an extended distance `edist` possibly taking the
value ∞
Each pseudo_emetric space induces a canonical `uniform_space` and hence a canonical
`topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `pseudo_emetric_space` structure, the uniformity fields are not necessary, they
will be filled in by default. There is a default value for the uniformity, that can be substituted
in cases of interest, for instance when instantiating a `pseudo_emetric_space` structure
on a product.
Continuity of `edist` is proved in `topology.instances.ennreal`
-/
class pseudo_emetric_space (α : Type u) extends has_edist α : Type u :=
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z)
(to_uniform_space : uniform_space α :=
uniform_space_of_edist edist edist_self edist_comm edist_triangle)
(uniformity_edist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} . control_laws_tac)
attribute [priority 100, instance] pseudo_emetric_space.to_uniform_space
/- Pseudoemetric spaces are less common than metric spaces. Therefore, we work in a dedicated
namespace, while notions associated to metric spaces are mostly in the root namespace. -/
variables [pseudo_emetric_space α]
export pseudo_emetric_space (edist_self edist_comm edist_triangle)
attribute [simp] edist_self
/-- Triangle inequality for the extended distance -/
theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y :=
by rw edist_comm z; apply edist_triangle
theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z :=
by rw edist_comm y; apply edist_triangle
lemma edist_congr_right {x y z : α} (h : edist x y = 0) : edist x z = edist y z :=
begin
apply le_antisymm,
{ rw [←zero_add (edist y z), ←h],
apply edist_triangle, },
{ rw edist_comm at h,
rw [←zero_add (edist x z), ←h],
apply edist_triangle, },
end
lemma edist_congr_left {x y z : α} (h : edist x y = 0) : edist z x = edist z y :=
by { rw [edist_comm z x, edist_comm z y], apply edist_congr_right h, }
lemma edist_triangle4 (x y z t : α) :
edist x t ≤ edist x y + edist y z + edist z t :=
calc
edist x t ≤ edist x z + edist z t : edist_triangle x z t
... ≤ (edist x y + edist y z) + edist z t : add_le_add_right (edist_triangle x y z) _
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) :
edist (f m) (f n) ≤ ∑ i in finset.Ico m n, edist (f i) (f (i + 1)) :=
begin
revert n,
refine nat.le_induction _ _,
{ simp only [finset.sum_empty, finset.Ico_self, edist_self],
-- TODO: Why doesn't Lean close this goal automatically? `exact le_rfl` fails too.
exact le_refl (0:ℝ≥0∞) },
{ assume n hn hrec,
calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _
... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec le_rfl
... = ∑ i in finset.Ico m (n+1), _ :
by rw [nat.Ico_succ_right_eq_insert_Ico hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) :
edist (f 0) (f n) ≤ ∑ i in finset.range n, edist (f i) (f (i + 1)) :=
nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_edist f (nat.zero_le n)
/-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ℝ≥0∞} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i :=
le_trans (edist_le_Ico_sum_edist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.mem_Ico.1 hk).1 (finset.mem_Ico.1 hk).2
/-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ℝ≥0∞} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f 0) (f n) ≤ ∑ i in finset.range n, d i :=
nat.Ico_zero_eq_range ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd)
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_pseudoedist :
𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε} :=
pseudo_emetric_space.uniformity_edist
theorem uniformity_basis_edist :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
(@uniformity_pseudoedist α _).symm ▸ has_basis_binfi_principal
(λ r hr p hp, ⟨min r p, lt_min hr hp,
λ x hx, lt_of_lt_of_le hx (min_le_left _ _),
λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩)
⟨1, ennreal.zero_lt_one⟩
/-- Characterization of the elements of the uniformity in terms of the extended distance -/
theorem mem_uniformity_edist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
uniformity_basis_edist.mem_uniformity_iff
/-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`,
`uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/
protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases hf ε ε₀ with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
/-- Given `f : β → ℝ≥0∞`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/
protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ≥0∞}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases exists_between ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ }
end
theorem uniformity_basis_edist_le :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_edist' (ε' : ℝ≥0∞) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_le' (ε' : ℝ≥0∞) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ℝ≥0∞, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := exists_between hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_nnreal :
(𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2)
(λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in
⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩)
theorem uniformity_basis_edist_nnreal_le :
(𝓤 α).has_basis (λ ε : ℝ≥0, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, ennreal.coe_pos.2)
(λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in
⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩)
theorem uniformity_basis_edist_inv_nat :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) :=
emetric.mk_uniformity_basis
(λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n)
(λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩)
theorem uniformity_basis_edist_inv_two_pow :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < 2⁻¹ ^ n}) :=
emetric.mk_uniformity_basis
(λ n _, ennreal.pow_pos (ennreal.inv_pos.2 ennreal.two_ne_top) _)
(λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_two_pow_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩)
/-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/
theorem edist_mem_uniformity {ε:ℝ≥0∞} (ε0 : 0 < ε) :
{p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩
namespace emetric
@[priority 900]
instance : is_countably_generated (𝓤 α) :=
is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩
/-- ε-δ characterization of uniform continuity on a set for pseudoemetric spaces -/
theorem uniform_continuous_on_iff [pseudo_emetric_space β] {f : α → β} {s : set α} :
uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0,
∀ {a b ∈ s}, edist a b < δ → edist (f a) (f b) < ε :=
uniformity_basis_edist.uniform_continuous_on_iff uniformity_basis_edist
/-- ε-δ characterization of uniform continuity on pseudoemetric spaces -/
theorem uniform_continuous_iff [pseudo_emetric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε :=
uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist
/-- ε-δ characterization of uniform embeddings on pseudoemetric spaces -/
theorem uniform_embedding_iff [pseudo_emetric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- If a map between pseudoemetric spaces is a uniform embedding then the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y`. -/
theorem controlled_of_uniform_embedding [pseudo_emetric_space β] {f : α → β} :
uniform_embedding f →
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩,
end
/-- ε-δ characterization of Cauchy sequences on pseudoemetric spaces -/
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε :=
by rw ← ne_bot_iff; exact uniformity_basis_edist.cauchy_iff
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem complete_of_convergent_controlled_sequences (B : ℕ → ℝ≥0∞) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) →
∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
(λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H
/-- A sequentially complete pseudoemetric space is complete. -/
theorem complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
uniform_space.complete_of_cauchy_seq_tendsto
/-- Expressing locally uniform convergence on a set using `edist`. -/
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `edist`. -/
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `edist`. -/
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff,
mem_univ, forall_const, exists_prop, nhds_within_univ]
/-- Expressing uniform convergence using `edist`. -/
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε :=
by simp only [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff, mem_univ, forall_const]
end emetric
open emetric
/-- Auxiliary function to replace the uniformity on a pseudoemetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct a pseudoemetric space with a
specified uniformity. See Note [forgetful inheritance] explaining why having definitionally
the right uniformity is often important.
-/
def pseudo_emetric_space.replace_uniformity {α} [U : uniform_space α] (m : pseudo_emetric_space α)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
pseudo_emetric_space α :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist α _) }
/-- The extended pseudometric induced by a function taking values in a pseudoemetric space. -/
def pseudo_emetric_space.induced {α β} (f : α → β)
(m : pseudo_emetric_space β) : pseudo_emetric_space α :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Pseudoemetric space instance on subsets of pseudoemetric spaces -/
instance {α : Type*} {p : α → Prop} [pseudo_emetric_space α] : pseudo_emetric_space (subtype p) :=
pseudo_emetric_space.induced coe ‹_›
/-- The extended psuedodistance on a subset of a pseudoemetric space is the restriction of
the original pseudodistance, by definition -/
theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl
namespace mul_opposite
/-- Pseudoemetric space instance on the multiplicative opposite of a pseudoemetric space. -/
@[to_additive "Pseudoemetric space instance on the additive opposite of a pseudoemetric space."]
instance {α : Type*} [pseudo_emetric_space α] : pseudo_emetric_space αᵐᵒᵖ :=
pseudo_emetric_space.induced unop ‹_›
@[to_additive] theorem edist_unop (x y : αᵐᵒᵖ) : edist (unop x) (unop y) = edist x y := rfl
@[to_additive] theorem edist_op (x y : α) : edist (op x) (op y) = edist x y := rfl
end mul_opposite
section ulift
instance : pseudo_emetric_space (ulift α) :=
pseudo_emetric_space.induced ulift.down ‹_›
lemma ulift.edist_eq (x y : ulift α) : edist x y = edist x.down y.down := rfl
@[simp] lemma ulift.edist_up_up (x y : α) : edist (ulift.up x) (ulift.up y) = edist x y := rfl
end ulift
/-- The product of two pseudoemetric spaces, with the max distance, is an extended
pseudometric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.pseudo_emetric_space_max [pseudo_emetric_space β] : pseudo_emetric_space (α × β) :=
{ edist := λ x y, edist x.1 y.1 ⊔ edist x.2 y.2,
edist_self := λ x, by simp,
edist_comm := λ x y, by simp [edist_comm],
edist_triangle := λ x y z, max_le
(le_trans (edist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (edist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
uniformity_edist := begin
refine uniformity_prod.trans _,
simp only [pseudo_emetric_space.uniformity_edist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.edist_eq [pseudo_emetric_space β] (x y : α × β) :
edist x y = max (edist x.1 y.1) (edist x.2 y.2) :=
rfl
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of pseudoemetric spaces, with the max distance, is still
a pseudoemetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance pseudo_emetric_space_pi [∀b, pseudo_emetric_space (π b)] :
pseudo_emetric_space (Πb, π b) :=
{ edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_self := assume f, bot_unique $ finset.sup_le $ by simp,
edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _,
edist_triangle := assume f g h,
begin
simp only [finset.sup_le_iff],
assume b hb,
exact le_trans (edist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb))
end,
to_uniform_space := Pi.uniform_space _,
uniformity_edist := begin
simp only [Pi.uniformity, pseudo_emetric_space.uniformity_edist, comap_infi, gt_iff_lt,
preimage_set_of_eq, comap_principal],
rw infi_comm, congr, funext ε,
rw infi_comm, congr, funext εpos,
change 0 < ε at εpos,
simp [set.ext_iff, εpos]
end }
lemma edist_pi_def [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) :
edist f g = finset.sup univ (λb, edist (f b) (g b)) := rfl
lemma edist_le_pi_edist [Π b, pseudo_emetric_space (π b)] (f g : Π b, π b) (b : β) :
edist (f b) (g b) ≤ edist f g :=
finset.le_sup (finset.mem_univ b)
lemma edist_pi_le_iff [Π b, pseudo_emetric_space (π b)] {f g : Π b, π b} {d : ℝ≥0∞} :
edist f g ≤ d ↔ ∀ b, edist (f b) (g b) ≤ d :=
finset.sup_le_iff.trans $ by simp only [finset.mem_univ, forall_const]
lemma edist_pi_const_le (a b : α) : edist (λ _ : β, a) (λ _, b) ≤ edist a b :=
edist_pi_le_iff.2 $ λ _, le_rfl
@[simp] lemma edist_pi_const [nonempty β] (a b : α) : edist (λ x : β, a) (λ _, b) = edist a b :=
finset.sup_const univ_nonempty (edist a b)
end pi
namespace emetric
variables {x y z : α} {ε ε₁ ε₂ : ℝ≥0∞} {s t : set α}
/-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/
def ball (x : α) (ε : ℝ≥0∞) : set α := {y | edist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε :=
by rw [edist_comm, mem_ball]
/-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ≥0∞) := {y | edist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl
theorem mem_closed_ball' : y ∈ closed_ball x ε ↔ edist x y ≤ ε :=
by rw [edist_comm, mem_closed_ball]
@[simp] theorem closed_ball_top (x : α) : closed_ball x ∞ = univ :=
eq_univ_of_forall $ λ y, le_top
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y hy, le_of_lt hy
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt (zero_le _) hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show edist x x < ε, by rw edist_self; assumption
theorem mem_closed_ball_self : x ∈ closed_ball x ε :=
show edist x x ≤ ε, by rw edist_self; exact bot_le
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by rw [mem_ball', mem_ball]
theorem mem_closed_ball_comm : x ∈ closed_ball y ε ↔ y ∈ closed_ball x ε :=
by rw [mem_closed_ball', mem_closed_ball]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : disjoint (ball x ε₁) (ball y ε₂) :=
set.disjoint_left.mpr $ λ z h₁ h₂,
(edist_triangle_left x y z).not_lt $ (ennreal.add_lt_add h₁ h₂).trans_le h
theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y ≠ ∞) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, calc
edist z y ≤ edist z x + edist x y : edist_triangle _ _ _
... = edist x y + edist z x : add_comm _ _
... < edist x y + ε₁ : ennreal.add_lt_add_left h' zx
... ≤ ε₂ : h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
begin
have : 0 < ε - edist y x := by simpa using h,
refine ⟨ε - edist y x, this, ball_subset _ (ne_top_of_lt h)⟩,
exact (add_tsub_cancel_of_le (mem_ball.mp h).le).le
end
theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))),
λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩
lemma ord_connected_set_of_closed_ball_subset (x : α) (s : set α) :
ord_connected {r | closed_ball x r ⊆ s} :=
⟨λ r₁ hr₁ r₂ hr₂ r hr, (closed_ball_subset_closed_ball hr.2).trans hr₂⟩
lemma ord_connected_set_of_ball_subset (x : α) (s : set α) :
ord_connected {r | ball x r ⊆ s} :=
⟨λ r₁ hr₁ r₂ hr₂ r hr, (ball_subset_ball hr.2).trans hr₂⟩
/-- Relation “two points are at a finite edistance” is an equivalence relation. -/
def edist_lt_top_setoid : setoid α :=
{ r := λ x y, edist x y < ⊤,
iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top },
λ x y h, by rwa edist_comm,
λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ }
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [emetric.ball_eq_empty_iff]
theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_edist
lemma nhds_within_basis_eball : (𝓝[s] x).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_eball s
theorem nhds_basis_closed_eball : (𝓝 x).has_basis (λ ε:ℝ≥0∞, 0 < ε) (closed_ball x) :=
nhds_basis_uniformity uniformity_basis_edist_le
lemma nhds_within_basis_closed_eball :
(𝓝[s] x).has_basis (λ ε : ℝ≥0∞, 0 < ε) (λ ε, closed_ball x ε ∩ s) :=
nhds_within_has_basis nhds_basis_closed_eball s
theorem nhds_eq : 𝓝 x = (⨅ε>0, 𝓟 (ball x ε)) :=
nhds_basis_eball.eq_binfi
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff
lemma mem_nhds_within_iff : s ∈ 𝓝[t] x ↔ ∃ ε > 0, ball x ε ∩ t ⊆ s :=
nhds_within_basis_eball.mem_iff
section
variables [pseudo_emetric_space β] {f : α → β}
lemma tendsto_nhds_within_nhds_within {t : set β} {a b} :
tendsto f (𝓝[s] a) (𝓝[t] b) ↔
∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, x ∈ s → edist x a < δ → f x ∈ t ∧ edist (f x) b < ε :=
(nhds_within_basis_eball.tendsto_iff nhds_within_basis_eball).trans $
forall₂_congr $ λ ε hε, exists₂_congr $ λ δ hδ,
forall_congr $ λ x, by simp; itauto
lemma tendsto_nhds_within_nhds {a b} :
tendsto f (𝓝[s] a) (𝓝 b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → edist x a < δ → edist (f x) b < ε :=
by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] }
lemma tendsto_nhds_nhds {a b} :
tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀ ⦃x⦄, edist x a < δ → edist (f x) b < ε :=
nhds_basis_eball.tendsto_iff nhds_basis_eball
end
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem is_closed_ball_top : is_closed (ball x ⊤) :=
is_open_compl_iff.1 $ is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top,
(ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }).subset_compl_right⟩
theorem ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
is_open_ball.mem_nhds (mem_ball_self ε0)
theorem closed_ball_mem_nhds (x : α) {ε : ℝ≥0∞} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x :=
mem_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball
theorem ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) :
ball x r ×ˢ ball y r = ball (x, y) r :=
ext $ λ z, max_lt_iff.symm
theorem closed_ball_prod_same [pseudo_emetric_space β] (x : α) (y : β) (r : ℝ≥0∞) :
closed_ball x r ×ˢ closed_ball y r = closed_ball (x, y) r :=
ext $ λ z, max_le_iff.symm
/-- ε-characterization of the closure in pseudoemetric spaces -/
theorem mem_closure_iff :
x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε :=
(mem_closure_iff_nhds_basis nhds_basis_eball).trans $
by simp only [mem_ball, edist_comm x]
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε :=
nhds_basis_eball.tendsto_right_iff
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_eball).trans $
by simp only [exists_prop, true_and, mem_Ici, mem_ball]
theorem inseparable_iff : inseparable x y ↔ edist x y = 0 :=
by simp [inseparable_iff_mem_closure, mem_closure_iff, edist_comm, forall_lt_iff_le']
/-- In a pseudoemetric space, Cauchy sequences are characterized by the fact that, eventually,
the pseudoedistance between its elements is arbitrarily small -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε :=
uniformity_basis_edist.cauchy_seq_iff
/-- A variation around the emetric characterization of Cauchy sequences -/
theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>(0 : ℝ≥0∞), ∃N, ∀n≥N, edist (u n) (u N) < ε :=
uniformity_basis_edist.cauchy_seq_iff'
/-- A variation of the emetric characterization of Cauchy sequences that deals with
`ℝ≥0` upper bounds. -/
theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ ε : ℝ≥0, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε :=
uniformity_basis_edist_nnreal.cauchy_seq_iff'
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, t.finite ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩
theorem totally_bounded_iff' {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, set.finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, _, ft, h⟩ := H ε ε0 in
⟨t, ft, h.trans $ Union₂_mono $ λ y yt z, hε⟩⟩
section compact
/-- For a set `s` in a pseudo emetric space, if for every `ε > 0` there exists a countable
set that is `ε`-dense in `s`, then there exists a countable subset `t ⊆ s` that is dense in `s`. -/
lemma subset_countable_closure_of_almost_dense_set (s : set α)
(hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ s ⊆ ⋃ x ∈ t, closed_ball x ε) :
∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) :=
begin
rcases s.eq_empty_or_nonempty with rfl|⟨x₀, hx₀⟩,
{ exact ⟨∅, empty_subset _, countable_empty, empty_subset _⟩ },
choose! T hTc hsT using (λ n : ℕ, hs n⁻¹ (by simp)),
have : ∀ r x, ∃ y ∈ s, closed_ball x r ∩ s ⊆ closed_ball y (r * 2),
{ intros r x,
rcases (closed_ball x r ∩ s).eq_empty_or_nonempty with he|⟨y, hxy, hys⟩,
{ refine ⟨x₀, hx₀, _⟩, rw he, exact empty_subset _ },
{ refine ⟨y, hys, λ z hz, _⟩,
calc edist z y ≤ edist z x + edist y x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add hz.1 hxy
... = r * 2 : (mul_two r).symm } },
choose f hfs hf,
refine ⟨⋃ n : ℕ, (f n⁻¹) '' (T n), Union_subset $ λ n, image_subset_iff.2 (λ z hz, hfs _ _),
countable_Union $ λ n, (hTc n).image _, _⟩,
refine λ x hx, mem_closure_iff.2 (λ ε ε0, _),
rcases ennreal.exists_inv_nat_lt (ennreal.half_pos ε0.lt.ne').ne' with ⟨n, hn⟩,
rcases mem_Union₂.1 (hsT n hx) with ⟨y, hyn, hyx⟩,
refine ⟨f n⁻¹ y, mem_Union.2 ⟨n, mem_image_of_mem _ hyn⟩, _⟩,
calc edist x (f n⁻¹ y) ≤ n⁻¹ * 2 : hf _ _ ⟨hyx, hx⟩
... < ε : ennreal.mul_lt_of_lt_div hn
end
/-- A compact set in a pseudo emetric space is separable, i.e., it is a subset of the closure of a
countable set. -/
lemma subset_countable_closure_of_compact {s : set α} (hs : is_compact s) :
∃ t ⊆ s, (t.countable ∧ s ⊆ closure t) :=
begin
refine subset_countable_closure_of_almost_dense_set s (λ ε hε, _),
rcases totally_bounded_iff'.1 hs.totally_bounded ε hε with ⟨t, hts, htf, hst⟩,
exact ⟨t, htf.countable,
subset.trans hst $ Union₂_mono $ λ _ _, ball_subset_closed_ball⟩
end
end compact
section second_countable
open _root_.topological_space
variables (α)
/-- A sigma compact pseudo emetric space has second countable topology. This is not an instance
to avoid a loop with `sigma_compact_space_of_locally_compact_second_countable`. -/
lemma second_countable_of_sigma_compact [sigma_compact_space α] :
second_countable_topology α :=
begin
suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α,
choose T hTsub hTc hsubT
using λ n, subset_countable_closure_of_compact (is_compact_compact_covering α n),
refine ⟨⟨⋃ n, T n, countable_Union hTc, λ x, _⟩⟩,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
exact closure_mono (subset_Union _ n) (hsubT _ hn)
end
variable {α}
lemma second_countable_of_almost_dense_set
(hs : ∀ ε > 0, ∃ t : set α, t.countable ∧ (⋃ x ∈ t, closed_ball x ε) = univ) :
second_countable_topology α :=
begin
suffices : separable_space α, by exactI uniform_space.second_countable_of_separable α,
rcases subset_countable_closure_of_almost_dense_set (univ : set α) (λ ε ε0, _)
with ⟨t, -, htc, ht⟩,
{ exact ⟨⟨t, htc, λ x, ht (mem_univ x)⟩⟩ },
{ rcases hs ε ε0 with ⟨t, htc, ht⟩,
exact ⟨t, htc, univ_subset_iff.2 ht⟩ }
end
end second_countable
section diam
/-- The diameter of a set in a pseudoemetric space, named `emetric.diam` -/
noncomputable def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y
lemma diam_le_iff {d : ℝ≥0∞} :
diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d :=
by simp only [diam, supr_le_iff]
lemma diam_image_le_iff {d : ℝ≥0∞} {f : β → α} {s : set β} :
diam (f '' s) ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist (f x) (f y) ≤ d :=
by simp only [diam_le_iff, ball_image_iff]
lemma edist_le_of_diam_le {d} (hx : x ∈ s) (hy : y ∈ s) (hd : diam s ≤ d) : edist x y ≤ d :=
diam_le_iff.1 hd x hx y hy
/-- If two points belong to some set, their edistance is bounded by the diameter of the set -/
lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s :=
edist_le_of_diam_le hx hy le_rfl
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le {d : ℝ≥0∞} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) : diam s ≤ d := diam_le_iff.2 h
/-- The diameter of a subsingleton vanishes. -/
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
nonpos_iff_eq_zero.1 $ diam_le $
λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_rfl
/-- The diameter of the empty set vanishes -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- The diameter of a singleton vanishes -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
lemma diam_Union_mem_option {ι : Type*} (o : option ι) (s : ι → set α) :
diam (⋃ i ∈ o, s i) = ⨆ i ∈ o, diam (s i) :=
by cases o; simp
lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) :=
eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff, ball_insert_iff,
edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and,
forall_and_distrib, and_self, ← and_assoc]
lemma diam_pair : diam ({x, y} : set α) = edist x y :=
by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right]
lemma diam_triple :
diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) :=
by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton,
ennreal.max_zero_right, ennreal.sup_eq_max]
/-- The diameter is monotonous with respect to inclusion -/
lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t :=
diam_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy)
/-- The diameter of a union is controlled by the diameter of the sets, and the edistance
between two points in the sets. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) :
diam (s ∪ t) ≤ diam s + edist x y + diam t :=
begin
have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc
edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _
... ≤ diam s + edist x y + diam t :
add_le_add (add_le_add (edist_le_diam_of_mem ha xs) le_rfl) (edist_le_diam_of_mem yt hb),
refine diam_le (λa ha b hb, _),
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b
... ≤ diam s + (edist x y + diam t) : le_self_add
... = diam s + edist x y + diam t : (add_assoc _ _ _).symm },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [edist_comm] at Z },
{ calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b
... ≤ (diam s + edist x y) + diam t : le_add_self }
end
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt
lemma diam_closed_ball {r : ℝ≥0∞} : diam (closed_ball x r) ≤ 2 * r :=
diam_le $ λa ha b hb, calc
edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : (two_mul r).symm
lemma diam_ball {r : ℝ≥0∞} : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball
lemma diam_pi_le_of_le {π : β → Type*} [fintype β] [∀ b, pseudo_emetric_space (π b)]
{s : Π (b : β), set (π b)} {c : ℝ≥0∞} (h : ∀ b, diam (s b) ≤ c) :
diam (set.pi univ s) ≤ c :=
begin
apply diam_le (λ x hx y hy, edist_pi_le_iff.mpr _),
rw [mem_univ_pi] at hx hy,
exact λ b, diam_le_iff.1 (h b) (x b) (hx b) (y b) (hy b),
end
end diam
end emetric --namespace
/-- We now define `emetric_space`, extending `pseudo_emetric_space`. -/
class emetric_space (α : Type u) extends pseudo_emetric_space α : Type u :=
(eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y)
variables {γ : Type w} [emetric_space γ]
export emetric_space (eq_of_edist_eq_zero)
/-- Characterize the equality of points by the vanishing of their extended distance -/
@[simp] theorem edist_eq_zero {x y : γ} : edist x y = 0 ↔ x = y :=
iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _)
@[simp] theorem zero_eq_edist {x y : γ} : 0 = edist x y ↔ x = y :=
iff.intro (assume h, eq_of_edist_eq_zero (h.symm))
(assume : x = y, this ▸ (edist_self _).symm)
theorem edist_le_zero {x y : γ} : (edist x y ≤ 0) ↔ x = y :=
nonpos_iff_eq_zero.trans edist_eq_zero
@[simp] theorem edist_pos {x y : γ} : 0 < edist x y ↔ x ≠ y := by simp [← not_le]
/-- Two points coincide if their distance is `< ε` for all positive ε -/
theorem eq_of_forall_edist_le {x y : γ} (h : ∀ε > 0, edist x y ≤ ε) : x = y :=
eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h)
/-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [emetric_space β] {f : γ → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : γ}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : γ}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
split,
{ assume h,
exact ⟨emetric.uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, emetric.uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : edist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : edist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
/-- An emetric space is separated -/
@[priority 100] -- see Note [lower instance priority]
instance to_separated : separated_space γ :=
separated_def.2 $ λ x y h, eq_of_forall_edist_le $
λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0))
/-- If a `pseudo_emetric_space` is a T₀ space, then it is an `emetric_space`. -/
def emetric.of_t0_pseudo_emetric_space (α : Type*) [pseudo_emetric_space α] [t0_space α] :
emetric_space α :=
{ eq_of_edist_eq_zero := λ x y hdist, inseparable.eq $ emetric.inseparable_iff.2 hdist,
..‹pseudo_emetric_space α› }
/-- Auxiliary function to replace the uniformity on an emetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct an emetric space with a
specified uniformity. See Note [forgetful inheritance] explaining why having definitionally
the right uniformity is often important.
-/
def emetric_space.replace_uniformity {γ} [U : uniform_space γ] (m : emetric_space γ)
(H : @uniformity _ U = @uniformity _ pseudo_emetric_space.to_uniform_space) :
emetric_space γ :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@pseudo_emetric_space.uniformity_edist γ _) }
/-- The extended metric induced by an injective function taking values in a emetric space. -/
def emetric_space.induced {γ β} (f : γ → β) (hf : function.injective f)
(m : emetric_space β) : emetric_space γ :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h),
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Emetric space instance on subsets of emetric spaces -/
instance {α : Type*} {p : α → Prop} [emetric_space α] : emetric_space (subtype p) :=
emetric_space.induced coe subtype.coe_injective ‹_›
/-- Emetric space instance on the multiplicative opposite of an emetric space. -/
@[to_additive "Emetric space instance on the additive opposite of an emetric space."]
instance {α : Type*} [emetric_space α] : emetric_space αᵐᵒᵖ :=
emetric_space.induced mul_opposite.unop mul_opposite.unop_injective ‹_›
instance {α : Type*} [emetric_space α] : emetric_space (ulift α) :=
emetric_space.induced ulift.down ulift.down_injective ‹_›
/-- The product of two emetric spaces, with the max distance, is an extended
metric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.emetric_space_max [emetric_space β] : emetric_space (γ × β) :=
{ eq_of_edist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
have A : x.fst = y.fst := edist_le_zero.1 h₁,
have B : x.snd = y.snd := edist_le_zero.1 h₂,
exact prod.ext_iff.2 ⟨A, B⟩
end,
..prod.pseudo_emetric_space_max }
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_edist :
𝓤 γ = ⨅ ε>0, 𝓟 {p:γ×γ | edist p.1 p.2 < ε} :=
pseudo_emetric_space.uniformity_edist
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of emetric spaces, with the max distance, is still
an emetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) :=
{ eq_of_edist_eq_zero := assume f g eq0,
begin
have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0,
simp only [finset.sup_le_iff] at eq1,
exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b),
end,
..pseudo_emetric_space_pi }
end pi
namespace emetric
/-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set. -/
lemma countable_closure_of_compact {s : set γ} (hs : is_compact s) :
∃ t ⊆ s, (t.countable ∧ s = closure t) :=
begin
rcases subset_countable_closure_of_compact hs with ⟨t, hts, htc, hsub⟩,
exact ⟨t, hts, htc, subset.antisymm hsub (closure_minimal hts hs.is_closed)⟩
end
section diam
variables {s : set γ}
lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton :=
⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩
lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y :=
by simp only [pos_iff_ne_zero, ne.def, diam_eq_zero_iff, set.subsingleton, not_forall]
end diam
end emetric
/-!
### `additive`, `multiplicative`
The distance on those type synonyms is inherited without change.
-/
open additive multiplicative
section
variables [has_edist X]
instance : has_edist (additive X) := ‹has_edist X›
instance : has_edist (multiplicative X) := ‹has_edist X›
@[simp] lemma edist_of_mul (a b : X) : edist (of_mul a) (of_mul b) = edist a b := rfl
@[simp] lemma edist_of_add (a b : X) : edist (of_add a) (of_add b) = edist a b := rfl
@[simp] lemma edist_to_mul (a b : additive X) : edist (to_mul a) (to_mul b) = edist a b := rfl
@[simp] lemma edist_to_add (a b : multiplicative X) : edist (to_add a) (to_add b) = edist a b := rfl
end
instance [pseudo_emetric_space X] : pseudo_emetric_space (additive X) := ‹pseudo_emetric_space X›
instance [pseudo_emetric_space X] : pseudo_emetric_space (multiplicative X) :=
‹pseudo_emetric_space X›
instance [emetric_space X] : emetric_space (additive X) := ‹emetric_space X›
instance [emetric_space X] : emetric_space (multiplicative X) := ‹emetric_space X›
/-!
### Order dual
The distance on this type synonym is inherited without change.
-/
open order_dual
section
variables [has_edist X]
instance : has_edist Xᵒᵈ := ‹has_edist X›
@[simp] lemma edist_to_dual (a b : X) : edist (to_dual a) (to_dual b) = edist a b := rfl
@[simp] lemma edist_of_dual (a b : Xᵒᵈ) : edist (of_dual a) (of_dual b) = edist a b := rfl
end
instance [pseudo_emetric_space X] : pseudo_emetric_space Xᵒᵈ := ‹pseudo_emetric_space X›
instance [emetric_space X] : emetric_space Xᵒᵈ := ‹emetric_space X›
|
cd0de3b636e1805bfbeb54105958b6535b6be248 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/category_theory/monoidal/opposite.lean | 39b647f35172684ff2a92808c98aba5e5734a4d7 | [
"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,625 | 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
/-!
# Monoidal opposites
We write `Cᵐᵒᵖ` for the monoidal opposite of a monoidal category `C`.
-/
universes v₁ v₂ u₁ u₂
variables {C : Type u₁}
namespace category_theory
open category_theory.monoidal_category
/-- A type synonym for the monoidal opposite. Use the notation `Cᴹᵒᵖ`. -/
@[nolint has_inhabited_instance]
def monoidal_opposite (C : Type u₁) := C
namespace monoidal_opposite
notation C `ᴹᵒᵖ`:std.prec.max_plus := monoidal_opposite C
/-- Think of an object of `C` as an object of `Cᴹᵒᵖ`. -/
@[pp_nodot]
def mop (X : C) : Cᴹᵒᵖ := X
/-- Think of an object of `Cᴹᵒᵖ` as an object of `C`. -/
@[pp_nodot]
def unmop (X : Cᴹᵒᵖ) : C := X
lemma op_injective : function.injective (mop : C → Cᴹᵒᵖ) := λ _ _, id
lemma unop_injective : function.injective (unmop : Cᴹᵒᵖ → C) := λ _ _, id
@[simp] lemma op_inj_iff (x y : C) : mop x = mop y ↔ x = y := iff.rfl
@[simp] lemma unop_inj_iff (x y : Cᴹᵒᵖ) : unmop x = unmop y ↔ x = y := iff.rfl
attribute [irreducible] monoidal_opposite
@[simp] lemma mop_unmop (X : Cᴹᵒᵖ) : mop (unmop X) = X := rfl
@[simp] lemma unmop_mop (X : C) : unmop (mop X) = X := rfl
instance monoidal_opposite_category [I : category.{v₁} C] : category Cᴹᵒᵖ :=
{ hom := λ X Y, unmop X ⟶ unmop Y,
id := λ X, 𝟙 (unmop X),
comp := λ X Y Z f g, f ≫ g, }
end monoidal_opposite
end category_theory
open category_theory
open category_theory.monoidal_opposite
variables [category.{v₁} C]
/-- The monoidal opposite of a morphism `f : X ⟶ Y` is just `f`, thought of as `mop X ⟶ mop Y`. -/
def quiver.hom.mop {X Y : C} (f : X ⟶ Y) : @quiver.hom Cᴹᵒᵖ _ (mop X) (mop Y) := f
/-- We can think of a morphism `f : mop X ⟶ mop Y` as a morphism `X ⟶ Y`. -/
def quiver.hom.unmop {X Y : Cᴹᵒᵖ} (f : X ⟶ Y) : unmop X ⟶ unmop Y := f
namespace category_theory
lemma mop_inj {X Y : C} :
function.injective (quiver.hom.mop : (X ⟶ Y) → (mop X ⟶ mop Y)) :=
λ _ _ H, congr_arg quiver.hom.unmop H
lemma unmop_inj {X Y : Cᴹᵒᵖ} :
function.injective (quiver.hom.unmop : (X ⟶ Y) → (unmop X ⟶ unmop Y)) :=
λ _ _ H, congr_arg quiver.hom.mop H
@[simp] lemma unmop_mop {X Y : C} {f : X ⟶ Y} : f.mop.unmop = f := rfl
@[simp] lemma mop_unmop {X Y : Cᴹᵒᵖ} {f : X ⟶ Y} : f.unmop.mop = f := rfl
@[simp] lemma mop_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).mop = f.mop ≫ g.mop := rfl
@[simp] lemma mop_id {X : C} : (𝟙 X).mop = 𝟙 (mop X) := rfl
@[simp] lemma unmop_comp {X Y Z : Cᴹᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} :
(f ≫ g).unmop = f.unmop ≫ g.unmop := rfl
@[simp] lemma unmop_id {X : Cᴹᵒᵖ} : (𝟙 X).unmop = 𝟙 (unmop X) := rfl
@[simp] lemma unmop_id_mop {X : C} : (𝟙 (mop X)).unmop = 𝟙 X := rfl
@[simp] lemma mop_id_unmop {X : Cᴹᵒᵖ} : (𝟙 (unmop X)).mop = 𝟙 X := rfl
namespace iso
variables {X Y : C}
/-- An isomorphism in `C` gives an isomorphism in `Cᴹᵒᵖ`. -/
@[simps]
def mop (f : X ≅ Y) : mop X ≅ mop Y :=
{ hom := f.hom.mop,
inv := f.inv.mop,
hom_inv_id' := unmop_inj f.hom_inv_id,
inv_hom_id' := unmop_inj f.inv_hom_id }
end iso
variables [monoidal_category.{v₁} C]
open opposite monoidal_category
instance monoidal_category_op : monoidal_category Cᵒᵖ :=
{ tensor_obj := λ X Y, op (unop X ⊗ unop Y),
tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (f.unop ⊗ g.unop).op,
tensor_unit := op (𝟙_ C),
associator := λ X Y Z, (α_ (unop X) (unop Y) (unop Z)).symm.op,
left_unitor := λ X, (λ_ (unop X)).symm.op,
right_unitor := λ X, (ρ_ (unop X)).symm.op,
associator_naturality' :=
begin
intros,
apply quiver.hom.unop_inj,
simp [associator_inv_naturality],
end,
left_unitor_naturality' :=
begin
intros,
apply quiver.hom.unop_inj,
simp [left_unitor_inv_naturality],
end,
right_unitor_naturality' :=
begin
intros,
apply quiver.hom.unop_inj,
simp [right_unitor_inv_naturality],
end,
triangle' :=
begin
intros,
apply quiver.hom.unop_inj,
dsimp,
simp,
end,
pentagon' :=
begin
intros,
apply quiver.hom.unop_inj,
dsimp,
simp [pentagon_inv],
end }
lemma op_tensor_obj (X Y : Cᵒᵖ) : X ⊗ Y = op (unop X ⊗ unop Y) := rfl
lemma op_tensor_unit : (𝟙_ Cᵒᵖ) = op (𝟙_ C) := rfl
instance monoidal_category_mop : monoidal_category Cᴹᵒᵖ :=
{ tensor_obj := λ X Y, mop (unmop Y ⊗ unmop X),
tensor_hom := λ X₁ Y₁ X₂ Y₂ f g, (g.unmop ⊗ f.unmop).mop,
tensor_unit := mop (𝟙_ C),
associator := λ X Y Z, (α_ (unmop Z) (unmop Y) (unmop X)).symm.mop,
left_unitor := λ X, (ρ_ (unmop X)).mop,
right_unitor := λ X, (λ_ (unmop X)).mop,
associator_naturality' :=
begin
intros,
apply unmop_inj,
simp [associator_inv_naturality],
end,
left_unitor_naturality' :=
begin
intros,
apply unmop_inj,
simp [right_unitor_naturality],
end,
right_unitor_naturality' :=
begin
intros,
apply unmop_inj,
simp [left_unitor_naturality],
end,
triangle' :=
begin
intros,
apply unmop_inj,
dsimp,
simp,
end,
pentagon' :=
begin
intros,
apply unmop_inj,
dsimp,
simp [pentagon_inv],
end }
lemma mop_tensor_obj (X Y : Cᴹᵒᵖ) : X ⊗ Y = mop (unmop Y ⊗ unmop X) := rfl
lemma mop_tensor_unit : (𝟙_ Cᴹᵒᵖ) = mop (𝟙_ C) := rfl
end category_theory
|
66140f5642ddbd8fe64c029f3f8550eb6de0fd0e | f00cc9c04d77f9621aa57d1406d35c522c3ff82c | /library/init/data/list/lemmas.lean | 54ba0abb9766d2f20d189165fac23adfff775245 | [
"Apache-2.0"
] | permissive | shonfeder/lean | 444c66a74676d74fb3ef682d88cd0f5c1bf928a5 | 24d5a1592d80cefe86552d96410c51bb07e6d411 | refs/heads/master | 1,619,338,440,905 | 1,512,842,340,000 | 1,512,842,340,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 10,457 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn
-/
prelude
import init.data.list.basic init.function init.meta init.data.nat.lemmas
import init.meta.interactive init.meta.smt.rsimp
universes u v w w₁ w₂
variables {α : Type u} {β : Type v} {γ : Type w}
namespace list
open nat
/- append -/
@[simp] lemma nil_append (s : list α) : [] ++ s = s :=
rfl
@[simp] lemma cons_append (x : α) (s t : list α) : (x::s) ++ t = x::(s ++ t) :=
rfl
@[simp] lemma append_nil (t : list α) : t ++ [] = t :=
by induction t; simp [*]
@[simp] lemma append_assoc (s t u : list α) : s ++ t ++ u = s ++ (t ++ u) :=
by induction s; simp [*]
/- length -/
lemma length_cons (a : α) (l : list α) : length (a :: l) = length l + 1 :=
rfl
@[simp] lemma length_append (s t : list α) : length (s ++ t) = length s + length t :=
by induction s; simp [*]
@[simp] lemma length_repeat (a : α) (n : ℕ) : length (repeat a n) = n :=
by induction n; simp [*]; refl
@[simp] lemma length_tail (l : list α) : length (tail l) = length l - 1 :=
by cases l; refl
-- TODO(Leo): cleanup proof after arith dec proc
@[simp] lemma length_drop : ∀ (i : ℕ) (l : list α), length (drop i l) = length l - i
| 0 l := rfl
| (succ i) [] := eq.symm (nat.zero_sub (succ i))
| (succ i) (x::l) := calc
length (drop (succ i) (x::l))
= length l - i : length_drop i l
... = succ (length l) - succ i : (nat.succ_sub_succ_eq_sub (length l) i).symm
/- map -/
lemma map_cons (f : α → β) (a l) : map f (a::l) = f a :: map f l :=
rfl
@[simp] lemma map_append (f : α → β) : ∀ l₁ l₂, map f (l₁ ++ l₂) = (map f l₁) ++ (map f l₂) :=
by intro l₁; induction l₁; intros; simp [*]
lemma map_singleton (f : α → β) (a : α) : map f [a] = [f a] :=
rfl
@[simp] lemma map_id (l : list α) : map id l = l :=
by induction l; simp [*]
@[simp] lemma map_map (g : β → γ) (f : α → β) (l : list α) : map g (map f l) = map (g ∘ f) l :=
by induction l; simp [*]
@[simp] lemma length_map (f : α → β) (l : list α) : length (map f l) = length l :=
by induction l; simp [*]
/- bind -/
@[simp] lemma nil_bind (f : α → list β) : bind [] f = [] :=
by simp [join, bind]
@[simp] lemma cons_bind (x xs) (f : α → list β) : bind (x :: xs) f = f x ++ bind xs f :=
by simp [join, bind]
@[simp] lemma append_bind (xs ys) (f : α → list β) : bind (xs ++ ys) f = bind xs f ++ bind ys f :=
by induction xs; [refl, simp [*, cons_bind]]
/- mem -/
@[simp] lemma mem_nil_iff (a : α) : a ∈ ([] : list α) ↔ false :=
iff.rfl
@[simp] lemma not_mem_nil (a : α) : a ∉ ([] : list α) :=
iff.mp $ mem_nil_iff a
@[simp] lemma mem_cons_self (a : α) (l : list α) : a ∈ a :: l :=
or.inl rfl
@[simp] lemma mem_cons_iff (a y : α) (l : list α) : a ∈ y :: l ↔ (a = y ∨ a ∈ l) :=
iff.rfl
@[rsimp] lemma mem_cons_eq (a y : α) (l : list α) : (a ∈ y :: l) = (a = y ∨ a ∈ l) :=
rfl
lemma mem_cons_of_mem (y : α) {a : α} {l : list α} : a ∈ l → a ∈ y :: l :=
assume H, or.inr H
lemma eq_or_mem_of_mem_cons {a y : α} {l : list α} : a ∈ y::l → a = y ∨ a ∈ l :=
assume h, h
@[simp] lemma mem_append {a : α} {s t : list α} : a ∈ s ++ t ↔ a ∈ s ∨ a ∈ t :=
by induction s; simp [*, or_assoc]
@[rsimp] lemma mem_append_eq (a : α) (s t : list α) : (a ∈ s ++ t) = (a ∈ s ∨ a ∈ t) :=
propext mem_append
lemma mem_append_left {a : α} {l₁ : list α} (l₂ : list α) (h : a ∈ l₁) : a ∈ l₁ ++ l₂ :=
mem_append.2 (or.inl h)
lemma mem_append_right {a : α} (l₁ : list α) {l₂ : list α} (h : a ∈ l₂) : a ∈ l₁ ++ l₂ :=
mem_append.2 (or.inr h)
@[simp] lemma not_bex_nil (p : α → Prop) : ¬ (∃ x ∈ @nil α, p x) :=
λ⟨x, hx, px⟩, hx
@[simp] lemma ball_nil (p : α → Prop) : ∀ x ∈ @nil α, p x :=
λx, false.elim
@[simp] lemma bex_cons (p : α → Prop) (a : α) (l : list α) : (∃ x ∈ (a :: l), p x) ↔ (p a ∨ ∃ x ∈ l, p x) :=
⟨λ⟨x, h, px⟩, by {
simp at h, cases h with h h, {cases h, exact or.inl px}, {exact or.inr ⟨x, h, px⟩}},
λo, o.elim (λpa, ⟨a, mem_cons_self _ _, pa⟩)
(λ⟨x, h, px⟩, ⟨x, mem_cons_of_mem _ h, px⟩)⟩
@[simp] lemma ball_cons (p : α → Prop) (a : α) (l : list α) : (∀ x ∈ (a :: l), p x) ↔ (p a ∧ ∀ x ∈ l, p x) :=
⟨λal, ⟨al a (mem_cons_self _ _), λx h, al x (mem_cons_of_mem _ h)⟩,
λ⟨pa, al⟩ x o, o.elim (λe, e.symm ▸ pa) (al x)⟩
/- list subset -/
protected def subset (l₁ l₂ : list α) := ∀ ⦃a : α⦄, a ∈ l₁ → a ∈ l₂
instance : has_subset (list α) := ⟨list.subset⟩
@[simp] lemma nil_subset (l : list α) : [] ⊆ l :=
λ b i, false.elim (iff.mp (mem_nil_iff b) i)
@[refl, simp] lemma subset.refl (l : list α) : l ⊆ l :=
λ b i, i
@[trans] lemma subset.trans {l₁ l₂ l₃ : list α} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ :=
λ b i, h₂ (h₁ i)
@[simp] lemma subset_cons (a : α) (l : list α) : l ⊆ a::l :=
λ b i, or.inr i
lemma subset_of_cons_subset {a : α} {l₁ l₂ : list α} : a::l₁ ⊆ l₂ → l₁ ⊆ l₂ :=
λ s b i, s (mem_cons_of_mem _ i)
lemma cons_subset_cons {l₁ l₂ : list α} (a : α) (s : l₁ ⊆ l₂) : (a::l₁) ⊆ (a::l₂) :=
λ b hin, or.elim (eq_or_mem_of_mem_cons hin)
(λ e : b = a, or.inl e)
(λ i : b ∈ l₁, or.inr (s i))
@[simp] lemma subset_append_left (l₁ l₂ : list α) : l₁ ⊆ l₁++l₂ :=
λ b, mem_append_left _
@[simp] lemma subset_append_right (l₁ l₂ : list α) : l₂ ⊆ l₁++l₂ :=
λ b, mem_append_right _
lemma subset_cons_of_subset (a : α) {l₁ l₂ : list α} : l₁ ⊆ l₂ → l₁ ⊆ (a::l₂) :=
λ (s : l₁ ⊆ l₂) (a : α) (i : a ∈ l₁), or.inr (s i)
theorem eq_nil_of_length_eq_zero {l : list α} : length l = 0 → l = [] :=
by {induction l; intros, refl, contradiction}
theorem ne_nil_of_length_eq_succ {l : list α} : ∀ {n : nat}, length l = succ n → l ≠ [] :=
by induction l; intros; contradiction
@[simp] theorem length_map₂ (f : α → β → γ) (l₁) : ∀ l₂, length (map₂ f l₁ l₂) = min (length l₁) (length l₂) :=
by {induction l₁; intro l₂; cases l₂; simp [*, add_one, min_succ_succ]}
@[simp] theorem length_take : ∀ (i : ℕ) (l : list α), length (take i l) = min i (length l)
| 0 l := by simp
| (succ n) [] := by simp
| (succ n) (a::l) := by simp [*, nat.min_succ_succ, add_one]
theorem length_take_le (n) (l : list α) : length (take n l) ≤ n :=
by simp [min_le_left]
theorem length_remove_nth : ∀ (l : list α) (i : ℕ), i < length l → length (remove_nth l i) = length l - 1
| [] _ h := rfl
| (x::xs) 0 h := by simp [remove_nth, -add_comm]
| (x::xs) (i+1) h := have i < length xs, from lt_of_succ_lt_succ h,
by dsimp [remove_nth]; rw [length_remove_nth xs i this, nat.sub_add_cancel (lt_of_le_of_lt (nat.zero_le _) this)]; refl
@[simp] lemma partition_eq_filter_filter (p : α → Prop) [decidable_pred p] : ∀ (l : list α), partition p l = (filter p l, filter (not ∘ p) l)
| [] := rfl
| (a::l) := by { by_cases p a with pa; simp [partition, filter, pa, partition_eq_filter_filter l],
rw [if_neg (not_not_intro pa)], rw [if_pos pa] }
/- sublists -/
inductive sublist : list α → list α → Prop
| slnil : sublist [] []
| cons (l₁ l₂ a) : sublist l₁ l₂ → sublist l₁ (a::l₂)
| cons2 (l₁ l₂ a) : sublist l₁ l₂ → sublist (a::l₁) (a::l₂)
infix ` <+ `:50 := sublist
lemma length_le_of_sublist : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → length l₁ ≤ length l₂
| _ _ sublist.slnil := le_refl 0
| _ _ (sublist.cons l₁ l₂ a s) := le_succ_of_le (length_le_of_sublist s)
| _ _ (sublist.cons2 l₁ l₂ a s) := succ_le_succ (length_le_of_sublist s)
/- filter -/
@[simp] theorem filter_nil (p : α → Prop) [h : decidable_pred p] : filter p [] = [] := rfl
@[simp] theorem filter_cons_of_pos {p : α → Prop} [h : decidable_pred p] {a : α} :
∀ l, p a → filter p (a::l) = a :: filter p l :=
λ l pa, if_pos pa
@[simp] theorem filter_cons_of_neg {p : α → Prop} [h : decidable_pred p] {a : α} :
∀ l, ¬ p a → filter p (a::l) = filter p l :=
λ l pa, if_neg pa
@[simp] theorem filter_append {p : α → Prop} [h : decidable_pred p] :
∀ (l₁ l₂ : list α), filter p (l₁++l₂) = filter p l₁ ++ filter p l₂
| [] l₂ := rfl
| (a::l₁) l₂ := by by_cases p a with pa; simp [pa, filter_append]
@[simp] theorem filter_sublist {p : α → Prop} [h : decidable_pred p] : Π (l : list α), filter p l <+ l
| [] := sublist.slnil
| (a::l) := if pa : p a
then by simp [pa]; apply sublist.cons2; apply filter_sublist l
else by simp [pa]; apply sublist.cons; apply filter_sublist l
/- map_accumr -/
section map_accumr
variables {φ : Type w₁} {σ : Type w₂}
-- This runs a function over a list returning the intermediate results and a
-- a final result.
def map_accumr (f : α → σ → σ × β) : list α → σ → (σ × list β)
| [] c := (c, [])
| (y::yr) c :=
let r := map_accumr yr c in
let z := f y r.1 in
(z.1, z.2 :: r.2)
@[simp] theorem length_map_accumr
: ∀ (f : α → σ → σ × β) (x : list α) (s : σ),
length (map_accumr f x s).2 = length x
| f (a::x) s := congr_arg succ (length_map_accumr f x s)
| f [] s := rfl
end map_accumr
section map_accumr₂
variables {φ : Type w₁} {σ : Type w₂}
-- This runs a function over two lists returning the intermediate results and a
-- a final result.
def map_accumr₂ (f : α → β → σ → σ × φ)
: list α → list β → σ → σ × list φ
| [] _ c := (c,[])
| _ [] c := (c,[])
| (x::xr) (y::yr) c :=
let r := map_accumr₂ xr yr c in
let q := f x y r.1 in
(q.1, q.2 :: r.2)
@[simp] theorem length_map_accumr₂ : ∀ (f : α → β → σ → σ × φ) x y c,
length (map_accumr₂ f x y c).2 = min (length x) (length y)
| f (a::x) (b::y) c := calc
succ (length (map_accumr₂ f x y c).2)
= succ (min (length x) (length y))
: congr_arg succ (length_map_accumr₂ f x y c)
... = min (succ (length x)) (succ (length y))
: eq.symm (min_succ_succ (length x) (length y))
| f (a::x) [] c := rfl
| f [] (b::y) c := rfl
| f [] [] c := rfl
end map_accumr₂
end list
|
101fee627bc96f88e6e4a58ddd662af02a4fbbe6 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/414.lean | c9269557b90e609e9fcb715031e1adcc21bc3c3e | [
"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 | 169 | lean | macro_rules (kind := num)
| `($n:num) => `("world")
#check 2
macro_rules
| `($n:num) => `("hello")
#check 2
macro_rules (kind := num)
| n => `("boo")
#check 2
|
bc67869723f21967e82432a228517bcc9dc1c29a | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/euclidean/sphere/power.lean | ad14d1991684f15dfcf392e68b52e45283dd238c | [
"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 | 5,761 | lean | /-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales, Benjamin Davidson
-/
import geometry.euclidean.angle.unoriented.affine
import geometry.euclidean.sphere.basic
/-!
# Power of a point (intersecting chords and secants)
This file proves basic geometrical results about power of a point (intersecting chords and
secants) in spheres in real inner product spaces and Euclidean affine spaces.
## Main theorems
* `mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi`: Intersecting Chords Theorem (Freek No. 55).
* `mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_zero`: Intersecting Secants Theorem.
-/
open real
open_locale euclidean_geometry real_inner_product_space real
variables {V : Type*} [normed_add_comm_group V] [inner_product_space ℝ V]
namespace inner_product_geometry
/-!
### Geometrical results on spheres in real inner product spaces
This section develops some results on spheres in real inner product spaces,
which are used to deduce corresponding results for Euclidean affine spaces.
-/
lemma mul_norm_eq_abs_sub_sq_norm {x y z : V}
(h₁ : ∃ k : ℝ, k ≠ 1 ∧ x + y = k • (x - y)) (h₂ : ‖z - y‖ = ‖z + y‖) :
‖x - y‖ * ‖x + y‖ = |‖z + y‖ ^ 2 - ‖z - x‖ ^ 2| :=
begin
obtain ⟨k, hk_ne_one, hk⟩ := h₁,
let r := (k - 1)⁻¹ * (k + 1),
have hxy : x = r • y,
{ rw [← smul_smul, eq_inv_smul_iff₀ (sub_ne_zero.mpr hk_ne_one), ← sub_eq_zero],
calc (k - 1) • x - (k + 1) • y
= (k • x - x) - (k • y + y) : by simp_rw [sub_smul, add_smul, one_smul]
... = (k • x - k • y) - (x + y) : by simp_rw [← sub_sub, sub_right_comm]
... = k • (x - y) - (x + y) : by rw ← smul_sub k x y
... = 0 : sub_eq_zero.mpr hk.symm },
have hzy : ⟪z, y⟫ = 0,
by rwa [inner_eq_zero_iff_angle_eq_pi_div_two, ← norm_add_eq_norm_sub_iff_angle_eq_pi_div_two,
eq_comm],
have hzx : ⟪z, x⟫ = 0 := by rw [hxy, inner_smul_right, hzy, mul_zero],
calc ‖x - y‖ * ‖x + y‖
= ‖(r - 1) • y‖ * ‖(r + 1) • y‖ : by simp [sub_smul, add_smul, hxy]
... = ‖r - 1‖ * ‖y‖ * (‖r + 1‖ * ‖y‖) : by simp_rw [norm_smul]
... = ‖r - 1‖ * ‖r + 1‖ * ‖y‖ ^ 2 : by ring
... = |(r - 1) * (r + 1) * ‖y‖ ^ 2| : by simp [abs_mul]
... = |r ^ 2 * ‖y‖ ^ 2 - ‖y‖ ^ 2| : by ring_nf
... = |‖x‖ ^ 2 - ‖y‖ ^ 2| : by simp [hxy, norm_smul, mul_pow, sq_abs]
... = |‖z + y‖ ^ 2 - ‖z - x‖ ^ 2| : by simp [norm_add_sq_real, norm_sub_sq_real,
hzy, hzx, abs_sub_comm],
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on spheres in Euclidean affine spaces
This section develops some results on spheres in Euclidean affine spaces.
-/
open inner_product_geometry
variables {P : Type*} [metric_space P] [normed_add_torsor V P]
include V
/-- If `P` is a point on the line `AB` and `Q` is equidistant from `A` and `B`, then
`AP * BP = abs (BQ ^ 2 - PQ ^ 2)`. -/
lemma mul_dist_eq_abs_sub_sq_dist {a b p q : P}
(hp : ∃ k : ℝ, k ≠ 1 ∧ b -ᵥ p = k • (a -ᵥ p)) (hq : dist a q = dist b q) :
dist a p * dist b p = |dist b q ^ 2 - dist p q ^ 2| :=
begin
let m : P := midpoint ℝ a b,
obtain ⟨v, h1, h2, h3⟩ := ⟨vsub_sub_vsub_cancel_left, v a p m, v p q m, v a q m⟩,
have h : ∀ r, b -ᵥ r = (m -ᵥ r) + (m -ᵥ a) :=
λ r, by rw [midpoint_vsub_left, ← right_vsub_midpoint, add_comm, vsub_add_vsub_cancel],
iterate 4 { rw dist_eq_norm_vsub V },
rw [← h1, ← h2, h, h],
rw [← h1, h] at hp,
rw [dist_eq_norm_vsub V a q, dist_eq_norm_vsub V b q, ← h3, h] at hq,
exact mul_norm_eq_abs_sub_sq_norm hp hq,
end
/-- If `A`, `B`, `C`, `D` are cospherical and `P` is on both lines `AB` and `CD`, then
`AP * BP = CP * DP`. -/
lemma mul_dist_eq_mul_dist_of_cospherical {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hapb : ∃ k₁ : ℝ, k₁ ≠ 1 ∧ b -ᵥ p = k₁ • (a -ᵥ p))
(hcpd : ∃ k₂ : ℝ, k₂ ≠ 1 ∧ d -ᵥ p = k₂ • (c -ᵥ p)) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨q, r, h'⟩ := (cospherical_def {a, b, c, d}).mp h,
obtain ⟨ha, hb, hc, hd⟩ := ⟨h' a _, h' b _, h' c _, h' d _⟩,
{ rw ← hd at hc,
rw ← hb at ha,
rw [mul_dist_eq_abs_sub_sq_dist hapb ha, hb, mul_dist_eq_abs_sub_sq_dist hcpd hc, hd] },
all_goals { simp },
end
/-- **Intersecting Chords Theorem**. -/
theorem mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_pi {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hapb : ∠ a p b = π) (hcpd : ∠ c p d = π) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨-, k₁, _, hab⟩ := angle_eq_pi_iff.mp hapb,
obtain ⟨-, k₂, _, hcd⟩ := angle_eq_pi_iff.mp hcpd,
exact mul_dist_eq_mul_dist_of_cospherical h ⟨k₁, (by linarith), hab⟩ ⟨k₂, (by linarith), hcd⟩,
end
/-- **Intersecting Secants Theorem**. -/
theorem mul_dist_eq_mul_dist_of_cospherical_of_angle_eq_zero {a b c d p : P}
(h : cospherical ({a, b, c, d} : set P))
(hab : a ≠ b) (hcd : c ≠ d) (hapb : ∠ a p b = 0) (hcpd : ∠ c p d = 0) :
dist a p * dist b p = dist c p * dist d p :=
begin
obtain ⟨-, k₁, -, hab₁⟩ := angle_eq_zero_iff.mp hapb,
obtain ⟨-, k₂, -, hcd₁⟩ := angle_eq_zero_iff.mp hcpd,
refine mul_dist_eq_mul_dist_of_cospherical h ⟨k₁, _, hab₁⟩ ⟨k₂, _, hcd₁⟩;
by_contra hnot;
simp only [not_not, *, one_smul] at *,
exacts [hab (vsub_left_cancel hab₁).symm, hcd (vsub_left_cancel hcd₁).symm],
end
end euclidean_geometry
|
c38271f911685a2192b1aac45034e8927c4b8aab | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/finset/sort.lean | e8e20dd8b84a5adb5cdadaac48398b566ddea833 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 10,659 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.fintype.basic
import data.multiset.sort
import data.list.nodup_equiv_fin
/-!
# Construct a sorted list from a finset.
-/
namespace finset
open multiset nat
variables {α β : Type*}
/-! ### sort -/
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
@[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card :=
multiset.length_sort _
@[simp] theorem sort_empty : sort r ∅ = [] :=
multiset.sort_zero r
@[simp] theorem sort_singleton (a : α) : sort r {a} = [a] :=
multiset.sort_singleton r a
lemma sort_perm_to_list (s : finset α) : sort r s ~ s.to_list :=
by { rw ←multiset.coe_eq_coe, simp only [coe_to_list, sort_eq] }
end sort
section sort_linear_order
variables [linear_order α]
theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) :
(s.sort (≤)).nth_le 0 h = s.min' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) },
{ have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h),
exact s.min'_le _ this }
end
lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} :
(s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) :=
sorted_zero_eq_min'_aux _ _ _
lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} :
s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) :=
(sorted_zero_eq_min'_aux _ _ _).symm
lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length)
(H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H :=
begin
let l := s.sort (≤),
apply le_antisymm,
{ have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s :=
(finset.mem_sort (≤)).1 (list.nth_le_mem l _ h),
exact s.le_max' _ this },
{ have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H),
obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H :=
list.mem_iff_nth_le.1 this,
rw ← hi,
have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt,
exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) },
end
lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} :
(s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h =
s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) :=
sorted_last_eq_max'_aux _ _ _
lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} :
s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1)
(by simpa using nat.sub_lt (card_pos.mpr h) zero_lt_one) :=
(sorted_last_eq_max'_aux _ _ _).symm
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid
casting issues in further uses of this function. -/
def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o s :=
order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $
(s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $
set.ext $ λ x, mem_sort _
/-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is
the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a
proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to
avoid casting issues in further uses of this function. -/
def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α :=
(order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _)
@[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
↑(order_iso_of_fin s h i) = order_emb_of_fin s h i :=
rfl
lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : s) :
↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x :=
rfl
lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) :=
rfl
@[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) :
s.order_emb_of_fin h i ∈ s :=
(s.order_iso_of_fin h i).2
@[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) :
set.range (s.order_emb_of_fin h) = s :=
by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)]
/-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/
lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) :=
by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min']
/-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/
lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) :
order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) :=
by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h]
/-- `order_emb_of_fin {a} h` sends any argument to `a`. -/
@[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) :
order_emb_of_fin {a} (card_singleton a) i = a :=
by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton]
/-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α}
(hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h :=
begin
apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono,
rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj],
refine eq_of_subset_of_card_le (λ x hx, _) _,
{ rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x },
{ rw [h, card_image_of_injective _ hmono.injective, fin_range_card] }
end
/-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with
the increasing bijection `order_emb_of_fin s h`. -/
lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α}
(hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h :=
rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono
/-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if
and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l`
(although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/
@[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff
{k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} :
s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) :=
begin
substs k l,
exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _)
end
/-- Given a finset `s` of size at least `k` in a linear order `α`, the map `order_emb_of_card_le`
is an order embedding from `fin k` to `α` whose image is contained in `s`. Specifically, it maps
`fin k` to an initial segment of `s`. -/
def order_emb_of_card_le (s : finset α) {k : ℕ} (h : k ≤ s.card) : fin k ↪o α :=
(fin.cast_le h).trans (s.order_emb_of_fin rfl)
lemma order_emb_of_card_le_mem (s : finset α) {k : ℕ} (h : k ≤ s.card) (a) :
order_emb_of_card_le s h a ∈ s :=
by simp only [order_emb_of_card_le, rel_embedding.coe_trans, finset.order_emb_of_fin_mem]
lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) :
s.card ≤ t.card + 1 :=
begin
have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length,
{ intro i,
rw [finset.length_sort, ←lt_tsub_iff_right],
exact i.2 },
have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length :=
λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i),
have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i))
((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i)))
((s.sort (≤)).nth_le (i + 1) (h1 i))
((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i)))
(s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)),
let f : fin (s.card - 1) → t :=
λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩,
have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j :=
λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans
(lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij))
(exists_prop.mp (classical.some_spec (p j))).2.1)),
have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm
(not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij))))
(not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))),
rwa [fintype.card_fin, fintype.card_coe, tsub_le_iff_right] at key,
end
end sort_linear_order
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
end finset
|
5dbb6ae6b9375b382c39c6912b25e9f6fa779ccf | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/set_theory/ordinal/arithmetic.lean | daeab4abbea76962afd7175b5b0eb872163196e5 | [
"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 | 84,799 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Floris van Doorn, Violeta Hernández Palacios
-/
import set_theory.ordinal.basic
import tactic.by_contra
/-!
# Ordinal arithmetic
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Ordinals have an addition (corresponding to disjoint union) that turns them into an additive
monoid, and a multiplication (corresponding to the lexicographic order on the product) that turns
them into a monoid. One can also define correspondingly a subtraction, a division, a successor
function, a power function and a logarithm function.
We also define limit ordinals and prove the basic induction principle on ordinals separating
successor ordinals and limit ordinals, in `limit_rec_on`.
## Main definitions and results
* `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that
every element of `o₁` is smaller than every element of `o₂`.
* `o₁ - o₂` is the unique ordinal `o` such that `o₂ + o = o₁`, when `o₂ ≤ o₁`.
* `o₁ * o₂` is the lexicographic order on `o₂ × o₁`.
* `o₁ / o₂` is the ordinal `o` such that `o₁ = o₂ * o + o'` with `o' < o₂`. We also define the
divisibility predicate, and a modulo operation.
* `order.succ o = o + 1` is the successor of `o`.
* `pred o` if the predecessor of `o`. If `o` is not a successor, we set `pred o = o`.
We discuss the properties of casts of natural numbers of and of `ω` with respect to these
operations.
Some properties of the operations are also used to discuss general tools on ordinals:
* `is_limit o`: an ordinal is a limit ordinal if it is neither `0` nor a successor.
* `limit_rec_on` is the main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals.
* `is_normal`: a function `f : ordinal → ordinal` satisfies `is_normal` if it is strictly increasing
and order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`.
* `enum_ord`: enumerates an unbounded set of ordinals by the ordinals themselves.
* `sup`, `lsub`: the supremum / least strict upper bound of an indexed family of ordinals in
`Type u`, as an ordinal in `Type u`.
* `bsup`, `blsub`: the supremum / least strict upper bound of a set of ordinals indexed by ordinals
less than a given ordinal `o`.
Various other basic arithmetic results are given in `principal.lean` instead.
-/
noncomputable theory
open function cardinal set equiv order
open_locale classical cardinal ordinal
universes u v w
namespace ordinal
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
/-! ### Further properties of addition on ordinals -/
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.sum_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by { rw [←add_one_eq_succ, lift_add, lift_one], refl }
instance add_contravariant_class_le : contravariant_class ordinal.{u} ordinal.{u} (+) (≤) :=
⟨λ a b c, induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩,
⟨have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, rel_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_rel_embedding, embedding.coe_fn_mk]
using @rel_embedding.map_rel_iff _ _ _ _ f.to_rel_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩⟩
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
private theorem add_lt_add_iff_left' (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
instance add_covariant_class_lt : covariant_class ordinal.{u} ordinal.{u} (+) (<) :=
⟨λ a b c, (add_lt_add_iff_left' a).2⟩
instance add_contravariant_class_lt : contravariant_class ordinal.{u} ordinal.{u} (+) (<) :=
⟨λ a b c, (add_lt_add_iff_left' a).1⟩
instance add_swap_contravariant_class_lt :
contravariant_class ordinal.{u} ordinal.{u} (swap (+)) (<) :=
⟨λ a b c, lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)⟩
theorem add_le_add_iff_right {a b : ordinal} : ∀ n : ℕ, a + n ≤ b + n ↔ a ≤ b
| 0 := by simp
| (n+1) := by rw [nat_cast_succ, add_succ, add_succ, succ_le_succ_iff, add_le_add_iff_right]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
theorem add_eq_zero_iff {a b : ordinal} : a + b = 0 ↔ (a = 0 ∧ b = 0) :=
induction_on a $ λ α r _, induction_on b $ λ β s _, begin
simp_rw [←type_sum_lex, type_eq_zero_iff_is_empty],
exact is_empty_sum
end
theorem left_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : a = 0 :=
(add_eq_zero_iff.1 h).1
theorem right_eq_zero_of_add_eq_zero {a b : ordinal} (h : a + b = 0) : b = 0 :=
(add_eq_zero_iff.1 h).2
/-! ### The predecessor of an ordinal -/
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal) : ordinal :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_injective $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_succ a
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact (lt_succ a).ne e,
λ h, dif_neg h⟩
theorem pred_eq_iff_not_succ' {o} : pred o = o ↔ ∀ a, o ≠ succ a :=
by simpa using pred_eq_iff_not_succ
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
@[simp] theorem pred_zero : pred 0 = 0 :=
pred_eq_iff_not_succ'.2 $ λ a, (succ_ne_zero a).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o b : ordinal} (h : ¬ ∃ a, o = succ a) : succ b < o ↔ b < o :=
⟨(lt_succ b).trans, λ l, lt_of_le_of_ne (succ_le_of_lt l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ_iff]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ a in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-! ### Limit ordinals -/
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem is_limit.succ_lt {o a : ordinal} (h : is_limit o) : a < o → succ a < o :=
h.2 a
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ o))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o a : ordinal} (h : is_limit o) : succ a < o ↔ a < o :=
⟨(lt_succ a).trans, h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, l.le.trans h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ a)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, begin
obtain ⟨a', rfl⟩ := lift_down h.le,
rw [←lift_succ, lift_lt],
exact H a' (lift_lt.1 h)
end⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (ordinal.zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
/-- Main induction principle of ordinals: if one can prove a property by
induction at successor ordinals and at limit ordinals, then it holds for all ordinals. -/
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
lt_wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, lt_wf.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, lt_wf.fix_eq, dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, lt_wf.fix_eq, dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
instance order_top_out_succ (o : ordinal) : order_top (succ o).out.α :=
⟨_, le_enum_succ⟩
theorem enum_succ_eq_top {o : ordinal} :
enum (<) o (by { rw type_lt, exact lt_succ o }) = (⊤ : (succ o).out.α) :=
rfl
lemma has_succ_of_type_succ_lt {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : ∀ a < type r, succ a < type r) (x : α) : ∃ y, r x y :=
begin
use enum r (succ (typein r x)) (h _ (typein_lt_type r x)),
convert (enum_lt_enum (typein_lt_type r x) _).mpr (lt_succ _), rw [enum_typein]
end
theorem out_no_max_of_succ_lt {o : ordinal} (ho : ∀ a < o, succ a < o) : no_max_order o.out.α :=
⟨has_succ_of_type_succ_lt (by rwa type_lt)⟩
lemma bounded_singleton {r : α → α → Prop} [is_well_order α r] (hr : (type r).is_limit) (x) :
bounded r {x} :=
begin
refine ⟨enum r (succ (typein r x)) (hr.2 _ (typein_lt_type r x)), _⟩,
intros b hb,
rw mem_singleton_iff.1 hb,
nth_rewrite 0 ←enum_typein r x,
rw @enum_lt_enum _ r,
apply lt_succ
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (rel_iso.preimage equiv.ulift r).trans (enum_iso r).symm
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-! ### Normal ordinal functions -/
/-- A normal ordinal function is a strictly increasing function which is
order-continuous, i.e., the image `f o` of a limit ordinal `o` is the sup of `f a` for
`a < o`. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.strict_mono {f} (H : is_normal f) : strict_mono f :=
λ a b, limit_rec_on b (not.elim (not_lt_of_le $ ordinal.zero_le _))
(λ b IH h, (lt_or_eq_of_le (le_of_lt_succ h)).elim
(λ h, (IH h).trans (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 le_rfl _ (l.2 _ h)))
theorem is_normal.monotone {f} (H : is_normal f) : monotone f :=
H.strict_mono.monotone
theorem is_normal_iff_strict_mono_limit (f : ordinal → ordinal) :
is_normal f ↔ (strict_mono f ∧ ∀ o, is_limit o → ∀ a, (∀ b < o, f b ≤ a) → f o ≤ a) :=
⟨λ hf, ⟨hf.strict_mono, λ a ha c, (hf.2 a ha c).2⟩, λ ⟨hs, hl⟩, ⟨λ a, hs (lt_succ a),
λ a ha c, ⟨λ hac b hba, ((hs hba).trans_le hac).le, hl a ha c⟩⟩⟩
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ H.strict_mono
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.self_le {f} (H : is_normal f) (a) : a ≤ f a :=
lt_wf.self_le_of_strict_mono H.strict_mono a
theorem is_normal.le_set {f o} (H : is_normal f) (p : set ordinal) (p0 : p.nonempty) (b)
(H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f a ≤ o :=
⟨λ h a pa, (H.le_iff.2 ((H₂ _).1 le_rfl _ pa)).trans h,
λ h, begin
revert H₂, refine limit_rec_on b (λ H₂, _) (λ S _ H₂, _) (λ S L _ H₂, (H.2 _ L _).2 (λ a h', _)),
{ cases p0 with x px,
have := ordinal.le_zero.1 ((H₂ _).1 (ordinal.zero_le _) _ px),
rw this at px, exact h _ px },
{ rcases not_ball.1 (mt (H₂ S).2 $ (lt_succ S).not_le) with ⟨a, h₁, h₂⟩,
exact (H.le_iff.2 $ succ_le_of_lt $ not_le.1 h₂).trans (h _ h₁) },
{ rcases not_ball.1 (mt (H₂ a).2 h'.not_le) with ⟨b, h₁, h₂⟩,
exact (H.le_iff.2 $ (not_le.1 h₂).le).trans (h _ h₁) }
end⟩
theorem is_normal.le_set' {f o} (H : is_normal f) (p : set α) (p0 : p.nonempty) (g : α → ordinal)
(b) (H₂ : ∀ o, b ≤ o ↔ ∀ a ∈ p, g a ≤ o) : f b ≤ o ↔ ∀ a ∈ p, f (g a) ≤ o :=
by simpa [H₂] using H.le_set (g '' p) (p0.image g) b
theorem is_normal.refl : is_normal id := ⟨lt_succ, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) : is_normal (f ∘ g) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _), λ o l a, H₁.le_set' (< o) ⟨_, l.pos⟩ g _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) : is_limit (f o) :=
⟨ne_of_gt $ (ordinal.zero_le _).trans_lt $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
(succ_le_of_lt h₂).trans_lt (H.lt_iff.2 h₁)⟩
theorem is_normal.le_iff_eq {f} (H : is_normal f) {a} : f a ≤ a ↔ f a = a := (H.self_le a).le_iff_eq
theorem add_le_of_limit {a b c : ordinal} (h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, (add_le_add_left l.le _).trans h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [←typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le_iff] at this,
refine (rel_embedding.of_monotone (λ a, _) (λ a b, _)).ordinal_type_le.trans_lt this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ b),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
alias add_is_limit ← is_limit.add
/-! ### Subtraction on ordinals-/
/-- The set in the definition of subtraction is nonempty. -/
theorem sub_nonempty {a b : ordinal} : {o | a ≤ b + o}.nonempty :=
⟨a, le_add_left _ _⟩
/-- `a - b` is the unique ordinal satisfying `b + (a - b) = a` when `b ≤ a`. -/
instance : has_sub ordinal := ⟨λ a b, Inf {o | a ≤ b + o}⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
Inf_mem sub_nonempty
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, (le_add_sub a b).trans (add_le_add_left h _), λ h, cInf_le' h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_rfl)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
protected theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
(le_add_sub a b).antisymm' begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le_iff, ← lt_sub, e], exact lt_succ c },
{ exact (add_le_of_limit l).2 (λ c l, (lt_sub.1 l).le) }
end
theorem le_sub_of_le {a b c : ordinal} (h : b ≤ a) : c ≤ a - b ↔ b + c ≤ a :=
by rw [←add_le_add_iff_left b, ordinal.add_sub_cancel_of_le h]
theorem sub_lt_of_le {a b c : ordinal} (h : b ≤ a) : a - b < c ↔ a < b + c :=
lt_iff_lt_of_le_iff_le (le_sub_of_le h)
instance : has_exists_add_of_le ordinal :=
⟨λ a b h, ⟨_, (ordinal.add_sub_cancel_of_le h).symm⟩⟩
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← ordinal.le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
protected theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← ordinal.le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
@[simp] theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + ω = ω :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, ← lift_one.{0}, ← lift_add, lift_le, ← type_unit, ← type_sum_lex],
refine ⟨rel_embedding.collapse (rel_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : ω ≤ o) : 1 + o = o :=
by rw [← ordinal.add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
/-! ### Multiplication of ordinals-/
/-- The multiplication of ordinals `o₁` and `o₂` is the (well founded) lexicographic order on
`o₂ × o₁`. -/
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨rel_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_prod_lex {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type (prod.lex s r) = type r * type s := rfl
private theorem mul_eq_zero' {a b : ordinal} : a * b = 0 ↔ a = 0 ∨ b = 0 :=
induction_on a $ λ α _ _, induction_on b $ λ β _ _, begin
simp_rw [←type_prod_lex, type_eq_zero_iff_is_empty],
rw or_comm,
exact is_empty_prod
end
instance : monoid_with_zero ordinal :=
{ zero := 0,
mul_zero := λ a, mul_eq_zero'.2 $ or.inr rfl,
zero_mul := λ a, mul_eq_zero'.2 $ or.inl rfl,
..ordinal.monoid }
instance : no_zero_divisors ordinal :=
⟨λ a b, mul_eq_zero'.1⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans
(rel_iso.prod_lex_congr (rel_iso.preimage equiv.ulift _)
(rel_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
instance : left_distrib_class ordinal.{u} :=
⟨λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩;
simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩⟩
theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one a b
instance mul_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (*) (≤) :=
⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine (rel_embedding.of_monotone (λ a : α × γ, (f a.1, a.2)) (λ a b h, _)).ordinal_type_le,
clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_rel_embedding.map_rel_iff.2 h') },
{ exact prod.lex.right _ h' }
end⟩
instance mul_swap_covariant_class_le : covariant_class ordinal.{u} ordinal.{u} (swap (*)) (≤) :=
⟨λ c a b, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine (rel_embedding.of_monotone (λ a : γ × α, (a.1, f a.2)) (λ a b h, _)).ordinal_type_le,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_rel_embedding.map_rel_iff.2 h') }
end⟩
theorem le_mul_left (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ a * b :=
by { convert mul_le_mul_left' (one_le_iff_pos.2 hb) a, rw mul_one a }
theorem le_mul_right (a : ordinal) {b : ordinal} (hb : 0 < b) : a ≤ b * a :=
by { convert mul_le_mul_right' (one_le_iff_pos.2 hb) a, rw one_mul a }
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [←typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw mul_succ at this,
have := ((add_lt_add_iff_left _).2 (typein_lt_type _ a)).trans_le this,
refine (rel_embedding.of_monotone (λ a, _) (λ a b, _)).ordinal_type_le.trans_lt this,
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂,
simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true,
dif_pos, sum.lex_inr_inr] using h },
{ subst b₁,
simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true,
or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp [e₂, dif_neg e₁, show b₂ ≠ b₁, by cc] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk,
sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal} (h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, (mul_le_mul_left' l.le _).trans h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [ordinal.pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact b0.false.elim },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
theorem smul_eq_mul : ∀ (n : ℕ) (a : ordinal), n • a = a * n
| 0 a := by rw [zero_smul, nat.cast_zero, mul_zero]
| (n + 1) a := by rw [succ_nsmul', nat.cast_add, mul_add, nat.cast_one, mul_one, smul_eq_mul]
/-! ### Division on ordinals -/
/-- The set in the definition of division is nonempty. -/
theorem div_nonempty {a b : ordinal} (h : b ≠ 0) : {o | a < b * succ o}.nonempty :=
⟨a, succ_le_iff.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right' (succ_le_of_lt (ordinal.pos_iff_ne_zero.2 h)) (succ a)⟩
/-- `a / b` is the unique ordinal `o` satisfying `a = b * o + o'` with `o' < b`. -/
instance : has_div ordinal := ⟨λ a b, if h : b = 0 then 0 else Inf {o | a < b * succ o}⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 :=
dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) : a / b = Inf {o | a < b * succ o} :=
dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact Inf_mem (div_nonempty h)
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, (lt_mul_succ_div a b0).trans_le (mul_le_mul_left' (succ_le_succ_iff.2 h) _),
λ h, by rw div_def a b0; exact cInf_le' h⟩
theorem lt_div {a b c : ordinal} (h : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le h, not_lt]
theorem div_pos {b c : ordinal} (h : c ≠ 0) : 0 < b / c ↔ c ≤ b := by simp [lt_div h]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, ordinal.zero_le] },
{ intros, rw [succ_le_iff, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, ordinal.zero_le] else
(div_le b0).2 $ h.trans_lt $ mul_lt_mul_of_pos_left (lt_succ c) (ordinal.pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
ordinal.le_zero.1 $ div_le_of_le_mul $ ordinal.zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, ordinal.zero_le] else (le_div b0).1 le_rfl
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
begin
rw [←ordinal.le_zero, div_le $ ordinal.pos_iff_ne_zero.1 $ (ordinal.zero_le _).trans_lt h],
simpa only [succ_zero, mul_one] using h
end
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a ordinal.one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, ordinal.pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by { rw [e, ← mul_add], apply dvd_mul_right }⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left'
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0)) a
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (eq_zero_of_zero_dvd h₁).symm else
if b0 : b = 0 then by subst b; exact eq_zero_of_zero_dvd h₂ else
(le_of_dvd b0 h₁).antisymm (le_of_dvd a0 h₂)
instance : is_antisymm ordinal (∣) := ⟨@dvd_antisymm⟩
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
theorem mod_le (a b : ordinal) : a % b ≤ a := sub_le_self a _
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
ordinal.add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
theorem dvd_of_mod_eq_zero {a b : ordinal} (H : a % b = 0) : b ∣ a :=
⟨a / b, by simpa [H] using (div_add_mod a b).symm⟩
theorem mod_eq_zero_of_dvd {a b : ordinal} (H : b ∣ a) : a % b = 0 :=
begin
rcases H with ⟨c, rfl⟩,
rcases eq_or_ne b 0 with rfl | hb,
{ simp },
{ simp [mod_def, hb] }
end
theorem dvd_iff_mod_eq_zero {a b : ordinal} : b ∣ a ↔ a % b = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
@[simp] theorem mul_add_mod_self (x y z : ordinal) : (x * y + z) % x = z % x :=
begin
rcases eq_or_ne x 0 with rfl | hx,
{ simp },
{ rwa [mod_def, mul_add_div, mul_add, ←sub_sub, add_sub_cancel, mod_def] }
end
@[simp] theorem mul_mod (x y : ordinal) : x * y % x = 0 := by simpa using mul_add_mod_self x y 0
theorem mod_mod_of_dvd (a : ordinal) {b c : ordinal} (h : c ∣ b) : a % b % c = a % c :=
begin
nth_rewrite_rhs 0 ←div_add_mod a b,
rcases h with ⟨d, rfl⟩,
rw [mul_assoc, mul_add_mod_self]
end
@[simp] theorem mod_mod (a b : ordinal) : a % b % b = a % b := mod_mod_of_dvd a dvd_rfl
/-! ### Families of ordinals
There are two kinds of indexed families that naturally arise when dealing with ordinals: those
indexed by some type in the appropriate universe, and those indexed by ordinals less than another.
The following API allows one to convert from one kind of family to the other.
In many cases, this makes it easy to prove claims about one kind of family via the corresponding
claim on the other. -/
/-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a specified
well-ordering. -/
def bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α) :
Π a < type r, α :=
λ a ha, f (enum r a ha)
/-- Converts a family indexed by a `Type u` to one indexed by an `ordinal.{u}` using a well-ordering
given by the axiom of choice. -/
def bfamily_of_family {ι : Type u} : (ι → α) → Π a < type (@well_ordering_rel ι), α :=
bfamily_of_family' well_ordering_rel
/-- Converts a family indexed by an `ordinal.{u}` to one indexed by an `Type u` using a specified
well-ordering. -/
def family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o)
(f : Π a < o, α) : ι → α :=
λ i, f (typein r i) (by { rw ←ho, exact typein_lt_type r i })
/-- Converts a family indexed by an `ordinal.{u}` to one indexed by a `Type u` using a well-ordering
given by the axiom of choice. -/
def family_of_bfamily (o : ordinal) (f : Π a < o, α) : o.out.α → α :=
family_of_bfamily' (<) (type_lt o) f
@[simp] theorem bfamily_of_family'_typein {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α)
(i) : bfamily_of_family' r f (typein r i) (typein_lt_type r i) = f i :=
by simp only [bfamily_of_family', enum_typein]
@[simp] theorem bfamily_of_family_typein {ι} (f : ι → α) (i) :
bfamily_of_family f (typein _ i) (typein_lt_type _ i) = f i :=
bfamily_of_family'_typein _ f i
@[simp] theorem family_of_bfamily'_enum {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o}
(ho : type r = o) (f : Π a < o, α) (i hi) :
family_of_bfamily' r ho f (enum r i (by rwa ho)) = f i hi :=
by simp only [family_of_bfamily', typein_enum]
@[simp] theorem family_of_bfamily_enum (o : ordinal) (f : Π a < o, α) (i hi) :
family_of_bfamily o f (enum (<) i (by { convert hi, exact type_lt _ })) = f i hi :=
family_of_bfamily'_enum _ (type_lt o) f _ _
/-- The range of a family indexed by ordinals. -/
def brange (o : ordinal) (f : Π a < o, α) : set α :=
{a | ∃ i hi, f i hi = a}
theorem mem_brange {o : ordinal} {f : Π a < o, α} {a} : a ∈ brange o f ↔ ∃ i hi, f i hi = a :=
iff.rfl
theorem mem_brange_self {o} (f : Π a < o, α) (i hi) : f i hi ∈ brange o f :=
⟨i, hi, rfl⟩
@[simp] theorem range_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o}
(ho : type r = o) (f : Π a < o, α) : range (family_of_bfamily' r ho f) = brange o f :=
begin
refine set.ext (λ a, ⟨_, _⟩),
{ rintro ⟨b, rfl⟩,
apply mem_brange_self },
{ rintro ⟨i, hi, rfl⟩,
exact ⟨_, family_of_bfamily'_enum _ _ _ _ _⟩ }
end
@[simp] theorem range_family_of_bfamily {o} (f : Π a < o, α) :
range (family_of_bfamily o f) = brange o f :=
range_family_of_bfamily' _ _ f
@[simp] theorem brange_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r]
(f : ι → α) : brange _ (bfamily_of_family' r f) = range f :=
begin
refine set.ext (λ a, ⟨_, _⟩),
{ rintro ⟨i, hi, rfl⟩,
apply mem_range_self },
{ rintro ⟨b, rfl⟩,
exact ⟨_, _, bfamily_of_family'_typein _ _ _⟩ },
end
@[simp] theorem brange_bfamily_of_family {ι : Type u} (f : ι → α) :
brange _ (bfamily_of_family f) = range f :=
brange_bfamily_of_family' _ _
@[simp] theorem brange_const {o : ordinal} (ho : o ≠ 0) {c : α} : brange o (λ _ _, c) = {c} :=
begin
rw ←range_family_of_bfamily,
exact @set.range_const _ o.out.α (out_nonempty_iff_ne_zero.2 ho) c
end
theorem comp_bfamily_of_family' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → α)
(g : α → β) : (λ i hi, g (bfamily_of_family' r f i hi)) = bfamily_of_family' r (g ∘ f) :=
rfl
theorem comp_bfamily_of_family {ι : Type u} (f : ι → α) (g : α → β) :
(λ i hi, g (bfamily_of_family f i hi)) = bfamily_of_family (g ∘ f) :=
rfl
theorem comp_family_of_bfamily' {ι : Type u} (r : ι → ι → Prop) [is_well_order ι r] {o}
(ho : type r = o) (f : Π a < o, α) (g : α → β) :
g ∘ (family_of_bfamily' r ho f) = family_of_bfamily' r ho (λ i hi, g (f i hi)) :=
rfl
theorem comp_family_of_bfamily {o} (f : Π a < o, α) (g : α → β) :
g ∘ (family_of_bfamily o f) = family_of_bfamily o (λ i hi, g (f i hi)) :=
rfl
/-! ### Supremum of a family of ordinals -/
/-- The supremum of a family of ordinals -/
def sup {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal.{max u v} :=
supr f
@[simp] theorem Sup_eq_sup {ι : Type u} (f : ι → ordinal.{max u v}) : Sup (set.range f) = sup f :=
rfl
/-- The range of an indexed ordinal function, whose outputs live in a higher universe than the
inputs, is always bounded above. See `ordinal.lsub` for an explicit bound. -/
theorem bdd_above_range {ι : Type u} (f : ι → ordinal.{max u v}) : bdd_above (set.range f) :=
⟨(supr (succ ∘ card ∘ f)).ord, begin
rintros a ⟨i, rfl⟩,
exact le_of_lt (cardinal.lt_ord.2 ((lt_succ _).trans_le (le_csupr (bdd_above_range _) _)))
end⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
λ i, le_cSup (bdd_above_range f) (mem_range_self i)
theorem sup_le_iff {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
(cSup_le_iff' (bdd_above_range f)).trans (by simp)
theorem sup_le {ι} {f : ι → ordinal} {a} : (∀ i, f i ≤ a) → sup f ≤ a :=
sup_le_iff.2
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le_iff _ f a)
theorem ne_sup_iff_lt_sup {ι} {f : ι → ordinal} : (∀ i, f i ≠ sup f) ↔ ∀ i, f i < sup f :=
⟨λ hf _, lt_of_le_of_ne (le_sup _ _) (hf _), λ hf _, ne_of_lt (hf _)⟩
theorem sup_not_succ_of_ne_sup {ι} {f : ι → ordinal} (hf : ∀ i, f i ≠ sup f) {a}
(hao : a < sup f) : succ a < sup f :=
begin
by_contra' hoa,
exact hao.not_le (sup_le $ λ i, le_of_lt_succ $
(lt_of_le_of_ne (le_sup _ _) (hf i)).trans_le hoa)
end
@[simp] theorem sup_eq_zero_iff {ι} {f : ι → ordinal} : sup f = 0 ↔ ∀ i, f i = 0 :=
begin
refine ⟨λ h i, _, λ h, le_antisymm
(sup_le (λ i, ordinal.le_zero.2 (h i))) (ordinal.zero_le _)⟩,
rw [←ordinal.le_zero, ←h],
exact le_sup f i
end
theorem is_normal.sup {f} (H : is_normal f) {ι} (g : ι → ordinal) [nonempty ι] :
f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le_iff, comp, H.le_set' set.univ set.univ_nonempty g]; simp [sup_le_iff]
@[simp] theorem sup_empty {ι} [is_empty ι] (f : ι → ordinal) : sup f = 0 :=
csupr_of_empty f
@[simp] theorem sup_const {ι} [hι : nonempty ι] (o : ordinal) : sup (λ _ : ι, o) = o :=
csupr_const
@[simp] theorem sup_unique {ι} [unique ι] (f : ι → ordinal) : sup f = f default :=
supr_unique
theorem sup_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal}
(h : set.range f ⊆ set.range g) : sup.{u (max v w)} f ≤ sup.{v (max u w)} g :=
sup_le $ λ i, match h (mem_range_self i) with ⟨j, hj⟩ := hj ▸ le_sup _ _ end
theorem sup_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal}
(h : set.range f = set.range g) : sup.{u (max v w)} f = sup.{v (max u w)} g :=
(sup_le_of_range_subset h.le).antisymm (sup_le_of_range_subset.{v u w} h.ge)
@[simp] theorem sup_sum {α : Type u} {β : Type v} (f : α ⊕ β → ordinal) : sup.{(max u v) w} f =
max (sup.{u (max v w)} (λ a, f (sum.inl a))) (sup.{v (max u w)} (λ b, f (sum.inr b))) :=
begin
apply (sup_le_iff.2 _).antisymm (max_le_iff.2 ⟨_, _⟩),
{ rintro (i|i),
{ exact le_max_of_le_left (le_sup _ i) },
{ exact le_max_of_le_right (le_sup _ i) } },
all_goals
{ apply sup_le_of_range_subset.{_ (max u v) w},
rintros i ⟨a, rfl⟩,
apply mem_range_self }
end
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : type r ≤ sup.{u u} (typein r ∘ f)) : unbounded r (range f) :=
(not_bounded_iff _).1 $ λ ⟨x, hx⟩, not_lt_of_le h $ lt_of_le_of_lt
(sup_le $ λ y, le_of_lt $ (typein_lt_typein r).2 $ hx _ $ mem_range_self y)
(typein_lt_type r x)
theorem le_sup_shrink_equiv {s : set ordinal.{u}} (hs : small.{u} s) (a) (ha : a ∈ s) :
a ≤ sup.{u u} (λ x, ((@equiv_shrink s hs).symm x).val) :=
by { convert le_sup.{u u} _ ((@equiv_shrink s hs) ⟨a, ha⟩), rw symm_apply_apply }
instance small_Iio (o : ordinal.{u}) : small.{u} (set.Iio o) :=
let f : o.out.α → set.Iio o := λ x, ⟨typein (<) x, typein_lt_self x⟩ in
let hf : surjective f := λ b, ⟨enum (<) b.val (by { rw type_lt, exact b.prop }),
subtype.ext (typein_enum _ _)⟩ in
small_of_surjective hf
instance small_Iic (o : ordinal.{u}) : small.{u} (set.Iic o) :=
by { rw ←Iio_succ, apply_instance }
theorem bdd_above_iff_small {s : set ordinal.{u}} : bdd_above s ↔ small.{u} s :=
⟨λ ⟨a, h⟩, small_subset $ show s ⊆ Iic a, from λ x hx, h hx,
λ h, ⟨sup.{u u} (λ x, ((@equiv_shrink s h).symm x).val), le_sup_shrink_equiv h⟩⟩
theorem bdd_above_of_small (s : set ordinal.{u}) [h : small.{u} s] : bdd_above s :=
bdd_above_iff_small.2 h
theorem sup_eq_Sup {s : set ordinal.{u}} (hs : small.{u} s) :
sup.{u u} (λ x, (@equiv_shrink s hs).symm x) = Sup s :=
let hs' := bdd_above_iff_small.2 hs in
((cSup_le_iff' hs').2 (le_sup_shrink_equiv hs)).antisymm'
(sup_le (λ x, le_cSup hs' (subtype.mem _)))
theorem Sup_ord {s : set cardinal.{u}} (hs : bdd_above s) : (Sup s).ord = Sup (ord '' s) :=
eq_of_forall_ge_iff $ λ a, begin
rw [cSup_le_iff' (bdd_above_iff_small.2 (@small_image _ _ _ s
(cardinal.bdd_above_iff_small.1 hs))), ord_le, cSup_le_iff' hs],
simp [ord_le]
end
theorem supr_ord {ι} {f : ι → cardinal} (hf : bdd_above (range f)) :
(supr f).ord = ⨆ i, (f i).ord :=
by { unfold supr, convert Sup_ord hf, rw range_comp }
private theorem sup_le_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop)
[is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o)
(f : Π a < o, ordinal) : sup (family_of_bfamily' r ho f) ≤ sup (family_of_bfamily' r' ho' f) :=
sup_le $ λ i, begin
cases typein_surj r' (by { rw [ho', ←ho], exact typein_lt_type r i }) with j hj,
simp_rw [family_of_bfamily', ←hj],
apply le_sup
end
theorem sup_eq_sup {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop) [is_well_order ι r]
[is_well_order ι' r'] {o : ordinal.{u}} (ho : type r = o) (ho' : type r' = o)
(f : Π a < o, ordinal.{max u v}) :
sup (family_of_bfamily' r ho f) = sup (family_of_bfamily' r' ho' f) :=
sup_eq_of_range_eq.{u u v} (by simp)
/-- The supremum of a family of ordinals indexed by the set of ordinals less than some
`o : ordinal.{u}`. This is a special case of `sup` over the family provided by
`family_of_bfamily`. -/
def bsup (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} :=
sup (family_of_bfamily o f)
@[simp] theorem sup_eq_bsup {o} (f : Π a < o, ordinal) : sup (family_of_bfamily o f) = bsup o f :=
rfl
@[simp] theorem sup_eq_bsup' {o ι} (r : ι → ι → Prop) [is_well_order ι r] (ho : type r = o) (f) :
sup (family_of_bfamily' r ho f) = bsup o f :=
sup_eq_sup r _ ho _ f
@[simp] theorem Sup_eq_bsup {o} (f : Π a < o, ordinal) : Sup (brange o f) = bsup o f :=
by { congr, rw range_family_of_bfamily }
@[simp] theorem bsup_eq_sup' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) :
bsup _ (bfamily_of_family' r f) = sup f :=
by simp only [←sup_eq_bsup' r, enum_typein, family_of_bfamily', bfamily_of_family']
theorem bsup_eq_bsup {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r']
(f : ι → ordinal) : bsup _ (bfamily_of_family' r f) = bsup _ (bfamily_of_family' r' f) :=
by rw [bsup_eq_sup', bsup_eq_sup']
@[simp] theorem bsup_eq_sup {ι} (f : ι → ordinal) : bsup _ (bfamily_of_family f) = sup f :=
bsup_eq_sup' _ f
@[congr] lemma bsup_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) :
bsup o₁ f = bsup o₂ (λ a h, f a (h.trans_eq ho.symm)) :=
by subst ho
theorem bsup_le_iff {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
sup_le_iff.trans ⟨λ h i hi, by { rw ←family_of_bfamily_enum o f, exact h _ }, λ h i, h _ _⟩
theorem bsup_le {o : ordinal} {f : Π b < o, ordinal} {a} :
(∀ i h, f i h ≤ a) → bsup.{u v} o f ≤ a :=
bsup_le_iff.2
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le_iff.1 le_rfl _ _
theorem lt_bsup {o} (f : Π a < o, ordinal) {a} : a < bsup o f ↔ ∃ i hi, a < f i hi :=
by simpa only [not_forall, not_le] using not_congr (@bsup_le_iff _ f a)
theorem is_normal.bsup {f} (H : is_normal f) {o} :
∀ (g : Π a < o, ordinal) (h : o ≠ 0), f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h, begin
resetI,
haveI := type_ne_zero_iff_nonempty.1 h,
rw [←sup_eq_bsup' r, H.sup, ←sup_eq_bsup' r];
refl
end
theorem lt_bsup_of_ne_bsup {o : ordinal} {f : Π a < o, ordinal} :
(∀ i h, f i h ≠ o.bsup f) ↔ ∀ i h, f i h < o.bsup f :=
⟨λ hf _ _, lt_of_le_of_ne (le_bsup _ _ _) (hf _ _), λ hf _ _, ne_of_lt (hf _ _)⟩
theorem bsup_not_succ_of_ne_bsup {o} {f : Π a < o, ordinal}
(hf : ∀ {i : ordinal} (h : i < o), f i h ≠ o.bsup f) (a) :
a < bsup o f → succ a < bsup o f :=
by { rw ←sup_eq_bsup at *, exact sup_not_succ_of_ne_sup (λ i, hf _) }
@[simp] theorem bsup_eq_zero_iff {o} {f : Π a < o, ordinal} : bsup o f = 0 ↔ ∀ i hi, f i hi = 0 :=
begin
refine ⟨λ h i hi, _, λ h, le_antisymm
(bsup_le (λ i hi, ordinal.le_zero.2 (h i hi))) (ordinal.zero_le _)⟩,
rw [←ordinal.le_zero, ←h],
exact le_bsup f i hi,
end
theorem lt_bsup_of_limit {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀ {a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : ∀ a < o, succ a < o) (i h) : f i h < bsup o f :=
(hf _ _ $ lt_succ i).trans_le (le_bsup f (succ i) $ ho _ h)
theorem bsup_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal}
(hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : bsup _ f = f o (lt_succ o) :=
le_antisymm (bsup_le $ λ i hi, hf _ _ $ le_of_lt_succ hi) (le_bsup _ _ _)
@[simp] theorem bsup_zero (f : Π a < (0 : ordinal), ordinal) : bsup 0 f = 0 :=
bsup_eq_zero_iff.2 (λ i hi, (ordinal.not_lt_zero i hi).elim)
theorem bsup_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : bsup o (λ _ _, a) = a :=
le_antisymm (bsup_le (λ _ _, le_rfl)) (le_bsup _ 0 (ordinal.pos_iff_ne_zero.2 ho))
@[simp] theorem bsup_one (f : Π a < (1 : ordinal), ordinal) : bsup 1 f = f 0 zero_lt_one :=
by simp_rw [←sup_eq_bsup, sup_unique, family_of_bfamily, family_of_bfamily', typein_one_out]
theorem bsup_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal}
(h : brange o f ⊆ brange o' g) : bsup.{u (max v w)} o f ≤ bsup.{v (max u w)} o' g :=
bsup_le $ λ i hi, begin
obtain ⟨j, hj, hj'⟩ := h ⟨i, hi, rfl⟩,
rw ←hj',
apply le_bsup
end
theorem bsup_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal}
(h : brange o f = brange o' g) : bsup.{u (max v w)} o f = bsup.{v (max u w)} o' g :=
(bsup_le_of_brange_subset h.le).antisymm (bsup_le_of_brange_subset.{v u w} h.ge)
/-- The least strict upper bound of a family of ordinals. -/
def lsub {ι} (f : ι → ordinal) : ordinal := sup (succ ∘ f)
@[simp] theorem sup_eq_lsub {ι} (f : ι → ordinal) : sup (succ ∘ f) = lsub f := rfl
theorem lsub_le_iff {ι} {f : ι → ordinal} {a} : lsub f ≤ a ↔ ∀ i, f i < a :=
by { convert sup_le_iff, simp only [succ_le_iff] }
theorem lsub_le {ι} {f : ι → ordinal} {a} : (∀ i, f i < a) → lsub f ≤ a :=
lsub_le_iff.2
theorem lt_lsub {ι} (f : ι → ordinal) (i) : f i < lsub f :=
succ_le_iff.1 (le_sup _ i)
theorem lt_lsub_iff {ι} {f : ι → ordinal} {a} : a < lsub f ↔ ∃ i, a ≤ f i :=
by simpa only [not_forall, not_lt, not_le] using not_congr (@lsub_le_iff _ f a)
theorem sup_le_lsub {ι} (f : ι → ordinal) : sup f ≤ lsub f :=
sup_le $ λ i, (lt_lsub f i).le
theorem lsub_le_sup_succ {ι} (f : ι → ordinal) : lsub f ≤ succ (sup f) :=
lsub_le $ λ i, lt_succ_iff.2 (le_sup f i)
theorem sup_eq_lsub_or_sup_succ_eq_lsub {ι} (f : ι → ordinal) :
sup f = lsub f ∨ succ (sup f) = lsub f :=
begin
cases eq_or_lt_of_le (sup_le_lsub f),
{ exact or.inl h },
{ exact or.inr ((succ_le_of_lt h).antisymm (lsub_le_sup_succ f)) }
end
theorem sup_succ_le_lsub {ι} (f : ι → ordinal) : succ (sup f) ≤ lsub f ↔ ∃ i, f i = sup f :=
begin
refine ⟨λ h, _, _⟩,
{ by_contra' hf,
exact (succ_le_iff.1 h).ne ((sup_le_lsub f).antisymm
(lsub_le (ne_sup_iff_lt_sup.1 hf))) },
rintro ⟨_, hf⟩,
rw [succ_le_iff, ←hf],
exact lt_lsub _ _
end
theorem sup_succ_eq_lsub {ι} (f : ι → ordinal) : succ (sup f) = lsub f ↔ ∃ i, f i = sup f :=
(lsub_le_sup_succ f).le_iff_eq.symm.trans (sup_succ_le_lsub f)
theorem sup_eq_lsub_iff_succ {ι} (f : ι → ordinal) :
sup f = lsub f ↔ ∀ a < lsub f, succ a < lsub f :=
begin
refine ⟨λ h, _, λ hf, le_antisymm (sup_le_lsub f) (lsub_le (λ i, _))⟩,
{ rw ←h,
exact λ a, sup_not_succ_of_ne_sup (λ i, (lsub_le_iff.1 (le_of_eq h.symm) i).ne) },
by_contra' hle,
have heq := (sup_succ_eq_lsub f).2 ⟨i, le_antisymm (le_sup _ _) hle⟩,
have := hf _ (by { rw ←heq, exact lt_succ (sup f) }),
rw heq at this,
exact this.false
end
theorem sup_eq_lsub_iff_lt_sup {ι} (f : ι → ordinal) : sup f = lsub f ↔ ∀ i, f i < sup f :=
⟨λ h i, (by { rw h, apply lt_lsub }), λ h, le_antisymm (sup_le_lsub f) (lsub_le h)⟩
@[simp] lemma lsub_empty {ι} [h : is_empty ι] (f : ι → ordinal) : lsub f = 0 :=
by { rw [←ordinal.le_zero, lsub_le_iff], exact h.elim }
lemma lsub_pos {ι} [h : nonempty ι] (f : ι → ordinal) : 0 < lsub f :=
h.elim $ λ i, (ordinal.zero_le _).trans_lt (lt_lsub f i)
@[simp] theorem lsub_eq_zero_iff {ι} {f : ι → ordinal} : lsub f = 0 ↔ is_empty ι :=
begin
refine ⟨λ h, ⟨λ i, _⟩, λ h, @lsub_empty _ h _⟩,
have := @lsub_pos _ ⟨i⟩ f,
rw h at this,
exact this.false
end
@[simp] theorem lsub_const {ι} [hι : nonempty ι] (o : ordinal) : lsub (λ _ : ι, o) = succ o :=
sup_const (succ o)
@[simp] theorem lsub_unique {ι} [hι : unique ι] (f : ι → ordinal) : lsub f = succ (f default) :=
sup_unique _
theorem lsub_le_of_range_subset {ι ι'} {f : ι → ordinal} {g : ι' → ordinal}
(h : set.range f ⊆ set.range g) : lsub.{u (max v w)} f ≤ lsub.{v (max u w)} g :=
sup_le_of_range_subset (by convert set.image_subset _ h; apply set.range_comp)
theorem lsub_eq_of_range_eq {ι ι'} {f : ι → ordinal} {g : ι' → ordinal}
(h : set.range f = set.range g) : lsub.{u (max v w)} f = lsub.{v (max u w)} g :=
(lsub_le_of_range_subset h.le).antisymm (lsub_le_of_range_subset.{v u w} h.ge)
@[simp] theorem lsub_sum {α : Type u} {β : Type v} (f : α ⊕ β → ordinal) : lsub.{(max u v) w} f =
max (lsub.{u (max v w)} (λ a, f (sum.inl a))) (lsub.{v (max u w)} (λ b, f (sum.inr b))) :=
sup_sum _
theorem lsub_not_mem_range {ι} (f : ι → ordinal) : lsub f ∉ set.range f :=
λ ⟨i, h⟩, h.not_lt (lt_lsub f i)
theorem nonempty_compl_range {ι : Type u} (f : ι → ordinal.{max u v}) : (set.range f)ᶜ.nonempty :=
⟨_, lsub_not_mem_range f⟩
@[simp] theorem lsub_typein (o : ordinal) :
lsub.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o :=
(lsub_le.{u u} typein_lt_self).antisymm begin
by_contra' h,
nth_rewrite 0 ←type_lt o at h,
simpa [typein_enum] using lt_lsub.{u u} (typein (<)) (enum (<) _ h)
end
theorem sup_typein_limit {o : ordinal} (ho : ∀ a, a < o → succ a < o) :
sup.{u u} (typein ((<) : o.out.α → o.out.α → Prop)) = o :=
by rw (sup_eq_lsub_iff_succ.{u u} (typein (<))).2; rwa lsub_typein o
@[simp] theorem sup_typein_succ {o : ordinal} :
sup.{u u} (typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) = o :=
begin
cases sup_eq_lsub_or_sup_succ_eq_lsub.{u u}
(typein ((<) : (succ o).out.α → (succ o).out.α → Prop)) with h h,
{ rw sup_eq_lsub_iff_succ at h,
simp only [lsub_typein] at h,
exact (h o (lt_succ o)).false.elim },
rw [←succ_eq_succ_iff, h],
apply lsub_typein
end
/-- The least strict upper bound of a family of ordinals indexed by the set of ordinals less than
some `o : ordinal.{u}`.
This is to `lsub` as `bsup` is to `sup`. -/
def blsub (o : ordinal.{u}) (f : Π a < o, ordinal.{max u v}) : ordinal.{max u v} :=
o.bsup (λ a ha, succ (f a ha))
@[simp] theorem bsup_eq_blsub (o : ordinal) (f : Π a < o, ordinal) :
bsup o (λ a ha, succ (f a ha)) = blsub o f :=
rfl
theorem lsub_eq_blsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] {o} (ho : type r = o) (f) :
lsub (family_of_bfamily' r ho f) = blsub o f :=
sup_eq_bsup' r ho (λ a ha, succ (f a ha))
theorem lsub_eq_lsub {ι ι' : Type u} (r : ι → ι → Prop) (r' : ι' → ι' → Prop)
[is_well_order ι r] [is_well_order ι' r'] {o} (ho : type r = o) (ho' : type r' = o)
(f : Π a < o, ordinal) : lsub (family_of_bfamily' r ho f) = lsub (family_of_bfamily' r' ho' f) :=
by rw [lsub_eq_blsub', lsub_eq_blsub']
@[simp] theorem lsub_eq_blsub {o} (f : Π a < o, ordinal) :
lsub (family_of_bfamily o f) = blsub o f :=
lsub_eq_blsub' _ _ _
@[simp] theorem blsub_eq_lsub' {ι} (r : ι → ι → Prop) [is_well_order ι r] (f : ι → ordinal) :
blsub _ (bfamily_of_family' r f) = lsub f :=
bsup_eq_sup' r (succ ∘ f)
theorem blsub_eq_blsub {ι : Type u} (r r' : ι → ι → Prop) [is_well_order ι r] [is_well_order ι r']
(f : ι → ordinal) : blsub _ (bfamily_of_family' r f) = blsub _ (bfamily_of_family' r' f) :=
by rw [blsub_eq_lsub', blsub_eq_lsub']
@[simp] theorem blsub_eq_lsub {ι} (f : ι → ordinal) : blsub _ (bfamily_of_family f) = lsub f :=
blsub_eq_lsub' _ _
@[congr] lemma blsub_congr {o₁ o₂ : ordinal} (f : Π a < o₁, ordinal) (ho : o₁ = o₂) :
blsub o₁ f = blsub o₂ (λ a h, f a (h.trans_eq ho.symm)) :=
by subst ho
theorem blsub_le_iff {o f a} : blsub o f ≤ a ↔ ∀ i h, f i h < a :=
by { convert bsup_le_iff, simp [succ_le_iff] }
theorem blsub_le {o : ordinal} {f : Π b < o, ordinal} {a} : (∀ i h, f i h < a) → blsub o f ≤ a :=
blsub_le_iff.2
theorem lt_blsub {o} (f : Π a < o, ordinal) (i h) : f i h < blsub o f :=
blsub_le_iff.1 le_rfl _ _
theorem lt_blsub_iff {o f a} : a < blsub o f ↔ ∃ i hi, a ≤ f i hi :=
by simpa only [not_forall, not_lt, not_le] using not_congr (@blsub_le_iff _ f a)
theorem bsup_le_blsub {o} (f : Π a < o, ordinal) : bsup o f ≤ blsub o f :=
bsup_le (λ i h, (lt_blsub f i h).le)
theorem blsub_le_bsup_succ {o} (f : Π a < o, ordinal) : blsub o f ≤ succ (bsup o f) :=
blsub_le (λ i h, lt_succ_iff.2 (le_bsup f i h))
theorem bsup_eq_blsub_or_succ_bsup_eq_blsub {o} (f : Π a < o, ordinal) :
bsup o f = blsub o f ∨ succ (bsup o f) = blsub o f :=
by { rw [←sup_eq_bsup, ←lsub_eq_blsub], exact sup_eq_lsub_or_sup_succ_eq_lsub _ }
theorem bsup_succ_le_blsub {o} (f : Π a < o, ordinal) :
succ (bsup o f) ≤ blsub o f ↔ ∃ i hi, f i hi = bsup o f :=
begin
refine ⟨λ h, _, _⟩,
{ by_contra' hf,
exact ne_of_lt (succ_le_iff.1 h) (le_antisymm (bsup_le_blsub f)
(blsub_le (lt_bsup_of_ne_bsup.1 hf))) },
rintro ⟨_, _, hf⟩,
rw [succ_le_iff, ←hf],
exact lt_blsub _ _ _
end
theorem bsup_succ_eq_blsub {o} (f : Π a < o, ordinal) :
succ (bsup o f) = blsub o f ↔ ∃ i hi, f i hi = bsup o f :=
(blsub_le_bsup_succ f).le_iff_eq.symm.trans (bsup_succ_le_blsub f)
theorem bsup_eq_blsub_iff_succ {o} (f : Π a < o, ordinal) :
bsup o f = blsub o f ↔ ∀ a < blsub o f, succ a < blsub o f :=
by { rw [←sup_eq_bsup, ←lsub_eq_blsub], apply sup_eq_lsub_iff_succ }
theorem bsup_eq_blsub_iff_lt_bsup {o} (f : Π a < o, ordinal) :
bsup o f = blsub o f ↔ ∀ i hi, f i hi < bsup o f :=
⟨λ h i, (by { rw h, apply lt_blsub }), λ h, le_antisymm (bsup_le_blsub f) (blsub_le h)⟩
theorem bsup_eq_blsub_of_lt_succ_limit {o} (ho : is_limit o) {f : Π a < o, ordinal}
(hf : ∀ a ha, f a ha < f (succ a) (ho.2 a ha)) : bsup o f = blsub o f :=
begin
rw bsup_eq_blsub_iff_lt_bsup,
exact λ i hi, (hf i hi).trans_le (le_bsup f _ _)
end
theorem blsub_succ_of_mono {o : ordinal} {f : Π a < succ o, ordinal}
(hf : ∀ {i j} hi hj, i ≤ j → f i hi ≤ f j hj) : blsub _ f = succ (f o (lt_succ o)) :=
bsup_succ_of_mono $ λ i j hi hj h, succ_le_succ (hf hi hj h)
@[simp] theorem blsub_eq_zero_iff {o} {f : Π a < o, ordinal} : blsub o f = 0 ↔ o = 0 :=
by { rw [←lsub_eq_blsub, lsub_eq_zero_iff], exact out_empty_iff_eq_zero }
@[simp] lemma blsub_zero (f : Π a < (0 : ordinal), ordinal) : blsub 0 f = 0 :=
by rwa blsub_eq_zero_iff
lemma blsub_pos {o : ordinal} (ho : 0 < o) (f : Π a < o, ordinal) : 0 < blsub o f :=
(ordinal.zero_le _).trans_lt (lt_blsub f 0 ho)
theorem blsub_type (r : α → α → Prop) [is_well_order α r] (f) :
blsub (type r) f = lsub (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [blsub_le_iff, lsub_le_iff]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem blsub_const {o : ordinal} (ho : o ≠ 0) (a : ordinal) : blsub.{u v} o (λ _ _, a) = succ a :=
bsup_const.{u v} ho (succ a)
@[simp] theorem blsub_one (f : Π a < (1 : ordinal), ordinal) : blsub 1 f = succ (f 0 zero_lt_one) :=
bsup_one _
@[simp] theorem blsub_id : ∀ o, blsub.{u u} o (λ x _, x) = o :=
lsub_typein
theorem bsup_id_limit {o : ordinal} : (∀ a < o, succ a < o) → bsup.{u u} o (λ x _, x) = o :=
sup_typein_limit
@[simp] theorem bsup_id_succ (o) : bsup.{u u} (succ o) (λ x _, x) = o :=
sup_typein_succ
theorem blsub_le_of_brange_subset {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal}
(h : brange o f ⊆ brange o' g) : blsub.{u (max v w)} o f ≤ blsub.{v (max u w)} o' g :=
bsup_le_of_brange_subset $ λ a ⟨b, hb, hb'⟩, begin
obtain ⟨c, hc, hc'⟩ := h ⟨b, hb, rfl⟩,
simp_rw ←hc' at hb',
exact ⟨c, hc, hb'⟩
end
theorem blsub_eq_of_brange_eq {o o'} {f : Π a < o, ordinal} {g : Π a < o', ordinal}
(h : {o | ∃ i hi, f i hi = o} = {o | ∃ i hi, g i hi = o}) :
blsub.{u (max v w)} o f = blsub.{v (max u w)} o' g :=
(blsub_le_of_brange_subset h.le).antisymm (blsub_le_of_brange_subset.{v u w} h.ge)
theorem bsup_comp {o o' : ordinal} {f : Π a < o, ordinal}
(hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) :
bsup o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = bsup o f :=
begin
apply le_antisymm;
refine bsup_le (λ i hi, _),
{ apply le_bsup },
{ rw [←hg, lt_blsub_iff] at hi,
rcases hi with ⟨j, hj, hj'⟩,
exact (hf _ _ hj').trans (le_bsup _ _ _) }
end
theorem blsub_comp {o o' : ordinal} {f : Π a < o, ordinal}
(hf : ∀ {i j} (hi) (hj), i ≤ j → f i hi ≤ f j hj) {g : Π a < o', ordinal} (hg : blsub o' g = o) :
blsub o' (λ a ha, f (g a ha) (by { rw ←hg, apply lt_blsub })) = blsub o f :=
@bsup_comp o _ (λ a ha, succ (f a ha)) (λ i j _ _ h, succ_le_succ_iff.2 (hf _ _ h)) g hg
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λ x _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id_limit h.2] }
theorem is_normal.blsub_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
blsub.{u} o (λ x _, f x) = f o :=
by { rw [←H.bsup_eq h, bsup_eq_blsub_of_lt_succ_limit h], exact (λ a _, H.1 a) }
theorem is_normal_iff_lt_succ_and_bsup_eq {f} :
is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → bsup o (λ x _, f x) = f o :=
⟨λ h, ⟨h.1, @is_normal.bsup_eq f h⟩, λ ⟨h₁, h₂⟩, ⟨h₁, λ o ho a,
(by {rw ←h₂ o ho, exact bsup_le_iff})⟩⟩
theorem is_normal_iff_lt_succ_and_blsub_eq {f} :
is_normal f ↔ (∀ a, f a < f (succ a)) ∧ ∀ o, is_limit o → blsub o (λ x _, f x) = f o :=
begin
rw [is_normal_iff_lt_succ_and_bsup_eq, and.congr_right_iff],
intro h,
split;
intros H o ho;
have := H o ho;
rwa ←bsup_eq_blsub_of_lt_succ_limit ho (λ a _, h a) at *
end
theorem is_normal.eq_iff_zero_and_succ {f g : ordinal.{u} → ordinal.{u}} (hf : is_normal f)
(hg : is_normal g) : f = g ↔ f 0 = g 0 ∧ ∀ a, f a = g a → f (succ a) = g (succ a) :=
⟨λ h, by simp [h], λ ⟨h₁, h₂⟩, funext (λ a, begin
apply a.limit_rec_on,
assumption',
intros o ho H,
rw [←is_normal.bsup_eq.{u u} hf ho, ←is_normal.bsup_eq.{u u} hg ho],
congr,
ext b hb,
exact H b hb
end)⟩
/-- A two-argument version of `ordinal.blsub`.
We don't develop a full API for this, since it's only used in a handful of existence results. -/
def blsub₂ (o₁ o₂ : ordinal) (op : Π (a < o₁) (b < o₂), ordinal) : ordinal :=
lsub (λ x : o₁.out.α × o₂.out.α,
op (typein (<) x.1) (typein_lt_self _) (typein (<) x.2) (typein_lt_self _))
theorem lt_blsub₂ {o₁ o₂ : ordinal} (op : Π (a < o₁) (b < o₂), ordinal) {a b : ordinal}
(ha : a < o₁) (hb : b < o₂) : op a ha b hb < blsub₂ o₁ o₂ op :=
begin
convert lt_lsub _ (prod.mk (enum (<) a (by rwa type_lt)) (enum (<) b (by rwa type_lt))),
simp only [typein_enum]
end
/-! ### Minimum excluded ordinals -/
/-- The minimum excluded ordinal in a family of ordinals. -/
def mex {ι : Type u} (f : ι → ordinal.{max u v}) : ordinal :=
Inf (set.range f)ᶜ
theorem mex_not_mem_range {ι : Type u} (f : ι → ordinal.{max u v}) : mex f ∉ set.range f :=
Inf_mem (nonempty_compl_range f)
theorem le_mex_of_forall {ι : Type u} {f : ι → ordinal.{max u v}} {a : ordinal}
(H : ∀ b < a, ∃ i, f i = b) : a ≤ mex f :=
by { by_contra' h, exact mex_not_mem_range f (H _ h) }
theorem ne_mex {ι} (f : ι → ordinal) : ∀ i, f i ≠ mex f :=
by simpa using mex_not_mem_range f
theorem mex_le_of_ne {ι} {f : ι → ordinal} {a} (ha : ∀ i, f i ≠ a) : mex f ≤ a :=
cInf_le' (by simp [ha])
theorem exists_of_lt_mex {ι} {f : ι → ordinal} {a} (ha : a < mex f) : ∃ i, f i = a :=
by { by_contra' ha', exact ha.not_le (mex_le_of_ne ha') }
theorem mex_le_lsub {ι} (f : ι → ordinal) : mex f ≤ lsub f :=
cInf_le' (lsub_not_mem_range f)
theorem mex_monotone {α β} {f : α → ordinal} {g : β → ordinal} (h : set.range f ⊆ set.range g) :
mex f ≤ mex g :=
begin
refine mex_le_of_ne (λ i hi, _),
cases h ⟨i, rfl⟩ with j hj,
rw ←hj at hi,
exact ne_mex g j hi
end
theorem mex_lt_ord_succ_mk {ι} (f : ι → ordinal) : mex f < (succ (#ι)).ord :=
begin
by_contra' h,
apply (lt_succ (#ι)).not_le,
have H := λ a, exists_of_lt_mex ((typein_lt_self a).trans_le h),
let g : (succ (#ι)).ord.out.α → ι := λ a, classical.some (H a),
have hg : injective g := λ a b h', begin
have Hf : ∀ x, f (g x) = typein (<) x := λ a, classical.some_spec (H a),
apply_fun f at h',
rwa [Hf, Hf, typein_inj] at h'
end,
convert cardinal.mk_le_of_injective hg,
rw cardinal.mk_ord_out
end
/-- The minimum excluded ordinal of a family of ordinals indexed by the set of ordinals less than
some `o : ordinal.{u}`. This is a special case of `mex` over the family provided by
`family_of_bfamily`.
This is to `mex` as `bsup` is to `sup`. -/
def bmex (o : ordinal) (f : Π a < o, ordinal) : ordinal :=
mex (family_of_bfamily o f)
theorem bmex_not_mem_brange {o : ordinal} (f : Π a < o, ordinal) : bmex o f ∉ brange o f :=
by { rw ←range_family_of_bfamily, apply mex_not_mem_range }
theorem le_bmex_of_forall {o : ordinal} (f : Π a < o, ordinal) {a : ordinal}
(H : ∀ b < a, ∃ i hi, f i hi = b) : a ≤ bmex o f :=
by { by_contra' h, exact bmex_not_mem_brange f (H _ h) }
theorem ne_bmex {o : ordinal} (f : Π a < o, ordinal) {i} (hi) : f i hi ≠ bmex o f :=
begin
convert ne_mex _ (enum (<) i (by rwa type_lt)),
rw family_of_bfamily_enum
end
theorem bmex_le_of_ne {o : ordinal} {f : Π a < o, ordinal} {a} (ha : ∀ i hi, f i hi ≠ a) :
bmex o f ≤ a :=
mex_le_of_ne (λ i, ha _ _)
theorem exists_of_lt_bmex {o : ordinal} {f : Π a < o, ordinal} {a} (ha : a < bmex o f) :
∃ i hi, f i hi = a :=
begin
cases exists_of_lt_mex ha with i hi,
exact ⟨_, typein_lt_self i, hi⟩
end
theorem bmex_le_blsub {o : ordinal} (f : Π a < o, ordinal) : bmex o f ≤ blsub o f :=
mex_le_lsub _
theorem bmex_monotone {o o' : ordinal} {f : Π a < o, ordinal} {g : Π a < o', ordinal}
(h : brange o f ⊆ brange o' g) : bmex o f ≤ bmex o' g :=
mex_monotone (by rwa [range_family_of_bfamily, range_family_of_bfamily])
theorem bmex_lt_ord_succ_card {o : ordinal} (f : Π a < o, ordinal) :
bmex o f < (succ o.card).ord :=
by { rw ←mk_ordinal_out, exact (mex_lt_ord_succ_mk (family_of_bfamily o f)) }
end ordinal
/-! ### Results about injectivity and surjectivity -/
lemma not_surjective_of_ordinal {α : Type u} (f : α → ordinal.{u}) : ¬ surjective f :=
λ h, ordinal.lsub_not_mem_range.{u u} f (h _)
lemma not_injective_of_ordinal {α : Type u} (f : ordinal.{u} → α) : ¬ injective f :=
λ h, not_surjective_of_ordinal _ (inv_fun_surjective h)
lemma not_surjective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : α → ordinal.{u}) :
¬ surjective f :=
λ h, not_surjective_of_ordinal _ (h.comp (equiv_shrink _).symm.surjective)
lemma not_injective_of_ordinal_of_small {α : Type v} [small.{u} α] (f : ordinal.{u} → α) :
¬ injective f :=
λ h, not_injective_of_ordinal _ ((equiv_shrink _).injective.comp h)
/-- The type of ordinals in universe `u` is not `small.{u}`. This is the type-theoretic analog of
the Burali-Forti paradox. -/
theorem not_small_ordinal : ¬ small.{u} ordinal.{max u v} :=
λ h, @not_injective_of_ordinal_of_small _ h _ (λ a b, ordinal.lift_inj.1)
/-! ### Enumerating unbounded sets of ordinals with ordinals -/
namespace ordinal
section
/-- Enumerator function for an unbounded set of ordinals. -/
def enum_ord (S : set ordinal.{u}) : ordinal → ordinal :=
lt_wf.fix (λ o f, Inf (S ∩ set.Ici (blsub.{u u} o f)))
variables {S : set ordinal.{u}}
/-- The equation that characterizes `enum_ord` definitionally. This isn't the nicest expression to
work with, so consider using `enum_ord_def` instead. -/
theorem enum_ord_def' (o) :
enum_ord S o = Inf (S ∩ set.Ici (blsub.{u u} o (λ a _, enum_ord S a))) :=
lt_wf.fix_eq _ _
/-- The set in `enum_ord_def'` is nonempty. -/
theorem enum_ord_def'_nonempty (hS : unbounded (<) S) (a) : (S ∩ set.Ici a).nonempty :=
let ⟨b, hb, hb'⟩ := hS a in ⟨b, hb, le_of_not_gt hb'⟩
private theorem enum_ord_mem_aux (hS : unbounded (<) S) (o) :
(enum_ord S o) ∈ S ∩ set.Ici (blsub.{u u} o (λ c _, enum_ord S c)) :=
by { rw enum_ord_def', exact Inf_mem (enum_ord_def'_nonempty hS _) }
theorem enum_ord_mem (hS : unbounded (<) S) (o) : enum_ord S o ∈ S :=
(enum_ord_mem_aux hS o).left
theorem blsub_le_enum_ord (hS : unbounded (<) S) (o) :
blsub.{u u} o (λ c _, enum_ord S c) ≤ enum_ord S o :=
(enum_ord_mem_aux hS o).right
theorem enum_ord_strict_mono (hS : unbounded (<) S) : strict_mono (enum_ord S) :=
λ _ _ h, (lt_blsub.{u u} _ _ h).trans_le (blsub_le_enum_ord hS _)
/-- A more workable definition for `enum_ord`. -/
theorem enum_ord_def (o) :
enum_ord S o = Inf (S ∩ {b | ∀ c, c < o → enum_ord S c < b}) :=
begin
rw enum_ord_def',
congr, ext,
exact ⟨λ h a hao, (lt_blsub.{u u} _ _ hao).trans_le h, blsub_le⟩
end
/-- The set in `enum_ord_def` is nonempty. -/
lemma enum_ord_def_nonempty (hS : unbounded (<) S) {o} :
{x | x ∈ S ∧ ∀ c, c < o → enum_ord S c < x}.nonempty :=
(⟨_, enum_ord_mem hS o, λ _ b, enum_ord_strict_mono hS b⟩)
@[simp] theorem enum_ord_range {f : ordinal → ordinal} (hf : strict_mono f) :
enum_ord (range f) = f :=
funext (λ o, begin
apply ordinal.induction o,
intros a H,
rw enum_ord_def a,
have Hfa : f a ∈ range f ∩ {b | ∀ c, c < a → enum_ord (range f) c < b} :=
⟨mem_range_self a, λ b hb, (by {rw H b hb, exact hf hb})⟩,
refine (cInf_le' Hfa).antisymm ((le_cInf_iff'' ⟨_, Hfa⟩).2 _),
rintros _ ⟨⟨c, rfl⟩, hc : ∀ b < a, enum_ord (range f) b < f c⟩,
rw hf.le_iff_le,
contrapose! hc,
exact ⟨c, hc, (H c hc).ge⟩,
end)
@[simp] theorem enum_ord_univ : enum_ord set.univ = id :=
by { rw ←range_id, exact enum_ord_range strict_mono_id }
@[simp] theorem enum_ord_zero : enum_ord S 0 = Inf S :=
by { rw enum_ord_def, simp [ordinal.not_lt_zero] }
theorem enum_ord_succ_le {a b} (hS : unbounded (<) S) (ha : a ∈ S) (hb : enum_ord S b < a) :
enum_ord S (succ b) ≤ a :=
begin
rw enum_ord_def,
exact cInf_le' ⟨ha, λ c hc, ((enum_ord_strict_mono hS).monotone (le_of_lt_succ hc)).trans_lt hb⟩
end
theorem enum_ord_le_of_subset {S T : set ordinal} (hS : unbounded (<) S) (hST : S ⊆ T) (a) :
enum_ord T a ≤ enum_ord S a :=
begin
apply ordinal.induction a,
intros b H,
rw enum_ord_def,
exact cInf_le' ⟨hST (enum_ord_mem hS b), λ c h, (H c h).trans_lt (enum_ord_strict_mono hS h)⟩
end
theorem enum_ord_surjective (hS : unbounded (<) S) : ∀ s ∈ S, ∃ a, enum_ord S a = s :=
λ s hs, ⟨Sup {a | enum_ord S a ≤ s}, begin
apply le_antisymm,
{ rw enum_ord_def,
refine cInf_le' ⟨hs, λ a ha, _⟩,
have : enum_ord S 0 ≤ s := by { rw enum_ord_zero, exact cInf_le' hs },
rcases exists_lt_of_lt_cSup (by exact ⟨0, this⟩) ha with ⟨b, hb, hab⟩,
exact (enum_ord_strict_mono hS hab).trans_le hb },
{ by_contra' h,
exact (le_cSup ⟨s, λ a,
(lt_wf.self_le_of_strict_mono (enum_ord_strict_mono hS) a).trans⟩
(enum_ord_succ_le hS hs h)).not_lt (lt_succ _) }
end⟩
/-- An order isomorphism between an unbounded set of ordinals and the ordinals. -/
def enum_ord_order_iso (hS : unbounded (<) S) : ordinal ≃o S :=
strict_mono.order_iso_of_surjective (λ o, ⟨_, enum_ord_mem hS o⟩) (enum_ord_strict_mono hS)
(λ s, let ⟨a, ha⟩ := enum_ord_surjective hS s s.prop in ⟨a, subtype.eq ha⟩)
theorem range_enum_ord (hS : unbounded (<) S) : range (enum_ord S) = S :=
by { rw range_eq_iff, exact ⟨enum_ord_mem hS, enum_ord_surjective hS⟩ }
/-- A characterization of `enum_ord`: it is the unique strict monotonic function with range `S`. -/
theorem eq_enum_ord (f : ordinal → ordinal) (hS : unbounded (<) S) :
strict_mono f ∧ range f = S ↔ f = enum_ord S :=
begin
split,
{ rintro ⟨h₁, h₂⟩,
rwa [←lt_wf.eq_strict_mono_iff_eq_range h₁ (enum_ord_strict_mono hS), range_enum_ord hS] },
{ rintro rfl,
exact ⟨enum_ord_strict_mono hS, range_enum_ord hS⟩ }
end
end
/-! ### Casting naturals into ordinals, compatibility with operations -/
@[simp] theorem one_add_nat_cast (m : ℕ) : 1 + (m : ordinal) = succ m :=
by { rw [←nat.cast_one, ←nat.cast_add, add_comm], refl }
@[simp, norm_cast] theorem nat_cast_mul (m : ℕ) : ∀ n : ℕ, ((m * n : ℕ) : ordinal) = m * n
| 0 := by simp
| (n+1) := by rw [nat.mul_succ, nat.cast_add, nat_cast_mul, nat.cast_succ, mul_add_one]
@[simp, norm_cast] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [←cardinal.ord_nat, ←cardinal.ord_nat, cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp, norm_cast] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp, norm_cast] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp, norm_cast] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp, norm_cast] theorem nat_cast_sub (m n : ℕ) : ((m - n : ℕ) : ordinal) = m - n :=
begin
cases le_total m n with h h,
{ rw [tsub_eq_zero_iff_le.2 h, ordinal.sub_eq_zero_iff_le.2 (nat_cast_le.2 h)],
refl },
{ apply (add_left_cancel n).1,
rw [←nat.cast_add, add_tsub_cancel_of_le h, ordinal.add_sub_cancel_of_le (nat_cast_le.2 h)] }
end
@[simp, norm_cast] theorem nat_cast_div (m n : ℕ) : ((m / n : ℕ) : ordinal) = m / n :=
begin
rcases eq_or_ne n 0 with rfl | hn,
{ simp },
{ have hn' := nat_cast_ne_zero.2 hn,
apply le_antisymm,
{ rw [le_div hn', ←nat_cast_mul, nat_cast_le, mul_comm],
apply nat.div_mul_le_self },
{ rw [div_le hn', ←add_one_eq_succ, ←nat.cast_succ, ←nat_cast_mul, nat_cast_lt, mul_comm,
←nat.div_lt_iff_lt_mul (nat.pos_of_ne_zero hn)],
apply nat.lt_succ_self } }
end
@[simp, norm_cast] theorem nat_cast_mod (m n : ℕ) : ((m % n : ℕ) : ordinal) = m % n :=
by rw [←add_left_cancel, div_add_mod, ←nat_cast_div, ←nat_cast_mul, ←nat.cast_add, nat.div_add_mod]
@[simp] theorem lift_nat_cast : ∀ n : ℕ, lift.{u v} n = n
| 0 := by simp
| (n+1) := by simp [lift_nat_cast n]
end ordinal
/-! ### Properties of `omega` -/
namespace cardinal
open ordinal
@[simp] theorem ord_aleph_0 : ord.{u} ℵ₀ = ω :=
le_antisymm (ord_le.2 $ le_rfl) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ←lift_card, lift_lt_aleph_0, ←typein_enum (<) h'],
exact lt_aleph_0_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_aleph_0_le {c} (h : ℵ₀ ≤ c) : c + 1 = c :=
begin
rw [add_comm, ←card_ord c, ←card_one, ←card_add, one_add_of_omega_le],
rwa [←ord_aleph_0, ord_le_ord]
end
end cardinal
namespace ordinal
theorem lt_add_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b + c ↔ ∃ c' < c, a < b + c' :=
by rw [←is_normal.bsup_eq.{u u} (add_is_normal b) h, lt_bsup]
theorem lt_omega {o : ordinal} : o < ω ↔ ∃ n : ℕ, o = n :=
by simp_rw [←cardinal.ord_aleph_0, cardinal.lt_ord, lt_aleph_0, card_eq_nat]
theorem nat_lt_omega (n : ℕ) : ↑n < ω :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < ω := nat_lt_omega 0
theorem omega_ne_zero : ω ≠ 0 := omega_pos.ne'
theorem one_lt_omega : 1 < ω := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit ω :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal} : ω ≤ o ↔ ∀ n : ℕ, ↑n ≤ o :=
⟨λ h n, (nat_lt_omega _).le.trans h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ←succ_le_iff]; exact H (n+1)⟩
@[simp] theorem sup_nat_cast : sup nat.cast = ω :=
(sup_le $ λ n, (nat_lt_omega n).le).antisymm $ omega_le.2 $ le_sup _
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, ↑n < o
| 0 := lt_of_le_of_ne (ordinal.zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : ω ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ ω ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / ω, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [←div_lt omega_ne_zero, ←succ_le_iff, le_div omega_ne_zero, mul_succ,
add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact (add_le_add_right (mul_div_le _ _) _).trans
(lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _).le },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit (ordinal.pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply (mul_le_mul_left' (le_succ c') _).trans,
rw IH _ h,
apply (add_le_add_left _ _).trans,
{ rw ← mul_succ, exact mul_le_mul_left' (succ_le_of_lt $ l.2 _ h) _ },
{ apply_instance },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right' (le_add_right _ _) _)
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem add_le_of_forall_add_lt {a b c : ordinal} (hb : 0 < b) (h : ∀ d < b, a + d < c) :
a + b ≤ c :=
begin
have H : a + (c - a) = c := ordinal.add_sub_cancel_of_le (by {rw ←add_zero a, exact (h _ hb).le}),
rw ←H,
apply add_le_add_left _ a,
by_contra' hb,
exact (h _ hb).ne H
end
theorem is_normal.apply_omega {f : ordinal.{u} → ordinal.{u}} (hf : is_normal f) :
sup.{0 u} (f ∘ nat.cast) = f ω :=
by rw [←sup_nat_cast, is_normal.sup.{0 u u} hf]
@[simp] theorem sup_add_nat (o : ordinal) : sup (λ n : ℕ, o + n) = o + ω :=
(add_is_normal o).apply_omega
@[simp] theorem sup_mul_nat (o : ordinal) : sup (λ n : ℕ, o * n) = o * ω :=
begin
rcases eq_zero_or_pos o with rfl | ho,
{ rw zero_mul, exact sup_eq_zero_iff.2 (λ n, zero_mul n) },
{ exact (mul_is_normal ho).apply_omega }
end
end ordinal
variables {α : Type u} {r : α → α → Prop} {a b : α}
namespace acc
/-- The rank of an element `a` accessible under a relation `r` is defined inductively as the
smallest ordinal greater than the ranks of all elements below it (i.e. elements `b` such that
`r b a`). -/
noncomputable def rank (h : acc r a) : ordinal.{u} :=
acc.rec_on h $ λ a h ih, ordinal.sup.{u u} $ λ b : {b // r b a}, order.succ $ ih b b.2
lemma rank_eq (h : acc r a) :
h.rank = ordinal.sup.{u u} (λ b : {b // r b a}, order.succ (h.inv b.2).rank) :=
by { change (acc.intro a $ λ _, h.inv).rank = _, refl }
/-- if `r a b` then the rank of `a` is less than the rank of `b`. -/
lemma rank_lt_of_rel (hb : acc r b) (h : r a b) : (hb.inv h).rank < hb.rank :=
(order.lt_succ _).trans_le $ by { rw hb.rank_eq, refine le_trans _ (ordinal.le_sup _ ⟨a, h⟩), refl }
end acc
namespace well_founded
variables (hwf : well_founded r)
include hwf
/-- The rank of an element `a` under a well-founded relation `r` is defined inductively as the
smallest ordinal greater than the ranks of all elements below it (i.e. elements `b` such that
`r b a`). -/
noncomputable def rank (a : α) : ordinal.{u} := (hwf.apply a).rank
lemma rank_eq : hwf.rank a = ordinal.sup.{u u} (λ b : {b // r b a}, order.succ $ hwf.rank b) :=
by { rw [rank, acc.rank_eq], refl }
lemma rank_lt_of_rel (h : r a b) : hwf.rank a < hwf.rank b := acc.rank_lt_of_rel _ h
omit hwf
lemma rank_strict_mono [preorder α] [well_founded_lt α] :
strict_mono (rank $ @is_well_founded.wf α (<) _) :=
λ _ _, rank_lt_of_rel _
lemma rank_strict_anti [preorder α] [well_founded_gt α] :
strict_anti (rank $ @is_well_founded.wf α (>) _) :=
λ _ _, rank_lt_of_rel $ @is_well_founded.wf α (>) _
end well_founded
|
c449cdad25c1998fe2f94003bb103c5a7d251251 | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /stage0/src/Lean/Data/FormatMacro.lean | 177281b50b852360132a50313ad19b4e67e2af2d | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 464 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.Format
namespace Lean
syntax:max "f!" (interpolatedStr term) : term
macro_rules
| `(f! $interpStr) => do
let chunks := interpStr.getArgs
let r ← Lean.Syntax.expandInterpolatedStrChunks chunks (fun a b => `($a ++ $b)) (fun a => `(fmt $a))
`(($r : Format))
end Lean
|
8d2199d87a2fd313b20048a5f41baa15a2f56703 | c465bc191b95d7a9e7544551279b09708d373f58 | /real_sense_failure.lean | 181c72c4819f212c840062cd2e650c6fef3f8c7e | [] | no_license | kevinsullivan/physvm_develop | b7a4149c72a10b3a87894c5db5af9b2ce5885c80 | a57e9c87d4d3fb7548dc6dfae3b932a51fc25b67 | refs/heads/main | 1,692,010,146,359 | 1,633,989,164,000 | 1,633,989,164,000 | 397,360,532 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 17,473 | lean | import .phys.time.time
import .phys.time_series.geom3d
import .standards.time_std
noncomputable theory
/-
This sensor-streaming application runs in an assumed
world with 3-d geometry and time as physical dimensions.
We import and will build from phys.geom and phys.time.
These modules provide a 3d geometric affine space and
1d temporal affine space, each with an uninterpreted
"standard" coordinate system. The user of the library
must specify external-world interpretations for origin
and basis vectors.
-/
/-
We need to assume a physical interpretation of the data
that represents our world affine coordinate system. So
here's what we'll assume.
(1) ORIGIN: the world_geom_acs.origin represents the
northwest-ish (back right) lower corner of the Rice Hall
Less Lab
(2) BASIS VECTORS
basis0
- points right/east along the wall
- unit length is 1m
- right handed chirality
basis1
- points to the door along the west wall,
- unit length is 1m
- RHC
basis2
- points up along the NW corner of the room,
- unit length is one meter,
- RHC
Some notes on Chirality/"Handedness":
https://en.wikipedia.org/wiki/Orientation_(vector_space)
http://www.cs.cornell.edu/courses/cs4620/2008fa/asgn/ray1/fcg3-sec245-248.pdf
(3) ACS is given by [Origin, b0, b1, b2]
-/
def geometry3d_acs : geom3d_space _ :=
let origin := mk_position3d geom3d_std_space 0 0 0 in
let basis0 := mk_displacement3d geom3d_std_space 1 0 0 in
let basis1 := mk_displacement3d geom3d_std_space 0 1 0 in
let basis2 := mk_displacement3d geom3d_std_space 0 0 1 in
let fr := mk_geom3d_frame origin basis0 basis1 basis2 in
mk_geom3d_space fr
/-
Note that world_geom_acs is not definitionally equal to
geom3d_std_space because the latter uses fm.base as its
frame, while world-geom_acs uses a frame defined by the
fm.deriv constructor.
-/
/-
Another way to say the same thing perhaps?
But now it's clearer that this is where we
have to attach those extra semantics the raw
geometric objects used here. In particular,
the origin and each vector needs a physical
interpretation, including both orientation
and handedness.
-/
def geometry3d_acs' : geom3d_space _ :=
(mk_geom3d_space
(mk_geom3d_frame
(mk_position3d geom3d_std_space 0 0 0)
(mk_displacement3d geom3d_std_space 1 0 0)
(mk_displacement3d geom3d_std_space 0 1 0)
(mk_displacement3d geom3d_std_space 0 0 1)
)
)
/-
We need to assume a physical interpretation of the data
representing our coordinate system on time.
(1) ORIGIN: January 1, 1970 per UTC standard
(2) BASIS VECTORS
basis0
- points to the future
- unit length is 1 second
(3) ACS is given by [Origin, b0]
-/
def time_acs : time_space _ := coordinated_universal_time_in_seconds
-- let origin := mk_time time_std_space 0 in
-- let basis := mk_duration time_std_space 1 in
-- let fr := mk_time_frame origin basis in
-- mk_time_space fr
/-
We're assuming a RealSense D435I hardware
unit. It comes with a defined coordinate
system
We'll assume that the camera_imu is two
meters to the right along the back wall,
one meter out from the wall and one meter
high. We'll inhert the standard vector
space structure from the world_geom_acs.
That's its position in space. As for its
orientation, we'll assume that
1. The positive x-axis points to the subject.
2. The positive y-axis points down.
3. The positive z-axis points forward
-/
def camera_imu_acs : geom3d_space _ :=
let origin := mk_position3d geometry3d_acs 2 1 1 in
let basis0 := mk_displacement3d geometry3d_acs 1 0 0 in
let basis1 := mk_displacement3d geometry3d_acs 0 0 (-1) in
let basis2 := mk_displacement3d geometry3d_acs 0 1 0 in
let fr := mk_geom3d_frame origin basis0 basis1 basis2 in
mk_geom3d_space fr
-- https://www.intelrealsense.com/how-to-getting-imu-data-from-d435i-and-t265/#Tracking_Sensor_Origin_and_CS
/-
We will assume that the origin of the camera's affine coordinate system is the same as UTC,
so we're using the origin of UTC as the origin Camera's time frame.
--Andrew 8/17: I have changed the origin back to a non-zero value based on our discussion and confirmation today
that there is likely a small delta between the origins of differing devices.
Candidly, my desktop has an offset of -.612 seconds from UTC, my laptop -.413, and my phone +.026.
(1) ORIGIN: 0 seconds AHEAD of our standard UTC origin
(2) BASIS VECTORS
basis0
- points to the future
- unit length is 1 millisecond
(3) ACS is given by [Origin, b0]
-/
/-RealSense developers refer to this as the hardware domain-/
def camera_time_acs : time_space _ :=
let hardware_clock_time_offset : scalar := 0.0 in
let milliseconds := 1000 in
let origin := mk_time coordinated_universal_time_in_seconds hardware_clock_time_offset in
let basis := mk_duration coordinated_universal_time_in_seconds milliseconds in
mk_time_space (mk_time_frame origin basis)
/-
Question: hardware_time_seconds_but_what's_the_origin
The origin is 0 with respect to the hardware frame
-/
def camera_time_seconds : time_space _ :=
let milliseconds_to_seconds := 0.001 in
let origin := mk_time camera_time_acs 0 in
let basis := mk_duration camera_time_acs milliseconds_to_seconds in
mk_time_space (mk_time_frame origin basis)
/-
Hardware time in what units?
-/
/-
This is the consuming ROS node's system time expressed in units seconds
One gap here is that this will be used to annotate the system time, which has a native
representation of seconds + nanoseconds, so there is arguably some mismatch when we
annotate the ros::Time variable simply as having units in seconds.
(1) ORIGIN: .87 seconds AHEAD of our standard UTC origin
(2) BASIS VECTORS
basis0
- points to the future
- unit length is 1 second
(3) ACS is given by [Origin, b0]
-/
def platform_time_in_seconds :=
let local_system_clock_time_offset : scalar := 0.870 in
let seconds := 0.001 in
let origin := mk_time coordinated_universal_time_in_seconds local_system_clock_time_offset in
let basis := mk_duration coordinated_universal_time_in_seconds seconds in
mk_time_space (mk_time_frame origin basis)
/-
The parameter of the method imu_callback_sync, "frame", is either timestamped Acceleration or Angular Velocity Vector.
We have no implementation for either in Peirce (or for sum types for that matter).
Per discussion on last 8/6, this is replaced with a Displacement3D.
void BaseRealSenseNode::imu_callback_sync(rs2::frame dataframe, imu_sync_method sync_method)
-/
def imu_callback_sync : timestamped camera_time_acs (displacement3d camera_imu_acs) → punit :=
/-
We define the argument to the method, dataframe. It has an interpretation of
timestamped camera_time_acs (position3d camera_imu_acs)
, although it's actual physical type manifest in the code would be an Acceleration or Angular Velocity Vector, representing
a timestamped reading coming from a Gyroscope or Accelerometer.
-/
λ dataframe,
/-
double frame_time = frame.get_timestamp();
In this line, we extract the timestamp of the dataframe, which represents the timestamp at which the IMU data was gathered.
-/
let dataframe_time := dataframe.timestamp in
/-setBaseTime(frame_time, frame.get_frame_timestamp_domain());
_ros_time_base = ros::Time::now();
_camera_time_base = frame_time;
A call is made to the method "setBaseTime". setBaseTime contains two salient lines: setting both _ros_time_base and
_camera_time_base. _ros_time_base is intended to represent the first time point at which the camera
has sent an IMU data reading, expressed in terms of of the local system clock that is reading
data from the RealSense camera data feed. _camera_time_base is intended to represent the first time point at which the camera
has sent an IMU data reading, expressed in terms of the clock directly on the camera.
-/
let _ros_time_base := mk_time platform_time_in_seconds 1629200210 in
let _camera_time_base := dataframe_time in
--double elapsed_camera_ms = (/*ms*/ frame_time - /*ms*/ _camera_time_base) / 1000.0;
/-
We take the difference between the first camera measurement, when the method "imu_callback_sync" was first called, and
the current camera measurement, as contained in "dataframe_time". Thus, the resulting difference is a duration in time.
The variable name suggests that the resulting computation is in milliseconds. The dataframe_time and the _camera_time_base
are expressed in milliseconds due to the implementation of the camera's clock, however, the actual units are expressed in seconds,
as there is a division by 1000. Thus, we transform the duration from its native millisecond frame to a seconds ACS. Mathematically,
we might represent this as Tₘˢ(t₂-t₁). Finally,
there is a type error, as we are attempting to assign a value in an ACS representing seconds to a variable in an ACS
representing milliseconds, which portrays a misconception by the developer when naming this variable.
-/
let elapsed_camera_ms : duration camera_time_acs
:= (camera_time_acs.mk_time_transform_to camera_time_seconds).transform_duration (dataframe_time -ᵥ _camera_time_base) in
/-
auto crnt_reading = *(reinterpret_cast<const float3*>(frame.get_data()));
Eigen::Vector3d v(crnt_reading.x, crnt_reading.y, crnt_reading.z);
There are some uneventful assignments that occur here.
The first casts (via static_casting) the vector-quantity data that the frame argument encapsulates to a "float3 object"
and stores it into a variable named "crnt_reading".
The second converts the prior "float3" object into an "Eigen::Vector3d" object, by extracting its x, y, and z coordinates,
using those respectively in the constructor to Eigen::Vector3d, and binding the constructed value into a variable called v.
We model in this in Lean simply by defining a value called "crnt_reading" and assigning the vector-valued data property stored in the
timestamped dataframe method argument. Since the physical type of the dataframe is "timestamped camera_time_acs (displacement3d camera_imu_acs)",
we know that the type of crnt_reading must simply be "displacement3d camera_imu_acs".
Next, we construct the vector v in the code. We define a variable v, which, again, has the physical type "displacement3d camera_imu_acs",
since it is built by simply constructing a new displacement3d using the exact same x, y, and z coordinates of the prior value, crnt_reading.
-/
let crnt_reading : displacement3d camera_imu_acs := dataframe.value in
let v : displacement3d camera_imu_acs := mk_displacement3d camera_imu_acs crnt_reading.x crnt_reading.y crnt_reading.z in
--CimuData imu_data(stream_index, v, elapsed_camera_ms);
/-
The constructor of CimuData in the next line of code simply re-packages the vector data stored in the original frame argument,
whose physical interpretation was a timestamped displacement3d in the camera, back into an another object which represents
a timestamped displacement3d, but this time, the timestamp is expressed in terms of the camera_time_seconds ACS, as the developer
explicitly converted from milliseconds into seconds when constructing what is intended to be the timestamp, elapsed_camera_seconds.
Thus, in order to formalize this in Lean, declare a variable called "imu_data" with type "timestamped camera_time_seconds (displacement3d camera_imu_acs)",
and populate it using the vector-valued data v (which is, again, the same displacement3d encapsulated in the argument to the method),
as well as the variable "elapsed_camera_ms" as a timestamp, which, again is a duration, not a point,
as it is the result of subtracting two time variables, and so, we see an error here in our formalization.
-/
let imu_data : timestamped camera_time_seconds (displacement3d camera_imu_acs) := ⟨elapsed_camera_ms, v⟩ in
/-
std::deque<sensor_msgs::Imu> imu_msgs;
switch (sync_method)
{
case NONE: //Cannot really be NONE. Just to avoid compilation warning.
case COPY:
FillImuData_Copy(imu_data, imu_msgs);
break;
case LINEAR_INTERPOLATION:
FillImuData_LinearInterpolation(imu_data, imu_msgs);
break;
}
-/
/-
We define a double-ended queue called "imu_msgs" and attempt to populate it. A call is made to the procedure "FillImuData_Copy"
or "FillImuData_LinearInterpolation", which is omitted here. The purpose of these procedures includes are to construct IMU messages,
specifically tuples of 2 3-dimensional (non-geometric) vectors, along with a linear interpolation that are beyond
the scope of what we can currently formalize, and the resulting IMU messages stores either 0 (if the dataframe argument came from an accelerometer),
1 (if the dataframe argument came from a gyroscope and sync_method is set to "COPY"), or n (if the dataframe argument came from a gyroscope
and sync_method is set to "LINEAR_INTERPOLATION") into deque "imu_msgs". The purpose of the method call is that entries are added to imu_msgs, so this is
simulated by simply instantiating the list with an initial value: imu_data - the timestamped value that we've constructed above. Note that
due to our limitations in Peirce, we have annotated the type of imu_msgs as being the type of the data that we have available,
"(timestamped camera_time_seconds (displacement3d camera_imu_acs))", as opposed to a timestamped IMU message, since we are not yet able to formalize the latter.
-/
let imu_msgs : list (timestamped camera_time_seconds (displacement3d camera_imu_acs)) := [imu_data] in
/-
while (imu_msgs.size())
{
sensor_msgs::Imu imu_msg = imu_msgs.front();
-/
/-
We now process each entry in the deque. Each entry has its timestamp updated, then it is published, and then it is removed from the queue, until the queue is empty.
Firstly, we retrieve the front of the queue, which is simply a call to "list.head" in Lean, and,
since "imu_msgs" has type "list (timestamped camera_time_seconds (displacement3d camera_imu_acs))",
the resulting expression is simply of type "(timestamped camera_time_seconds (displacement3d camera_imu_acs))"
-/
let imu_msg : timestamped camera_time_seconds (displacement3d camera_imu_acs) := imu_msgs.head in
--ros::Time t(_ros_time_base.toSec() + imu_msg.header.stamp.toSec());
/-
The developers now construct a new timestamp for the IMU message first by
retrieving "base time" of the "platform"/local system time (which was computed earlier, specifically in the first call to this method (imu_callback_sync)),
stored in variable "_ros_time_base", and then converting its value into seconds along with extracting its underlying coordinate via a "toSec" call.
Next, they retrieve timestamp of imu_msg, stored as "imu_msg.header.stamp" in C++ or "imu_msg.timestamp" in our formalization,
whose value is an alias of elapsed_camera_ms, which represents the "offset"/difference
between the current hardware/camera timestamp and the "base" of the hardware/camera time (which, again,
was computed specifically in the first call to this method) with the overall expression expressed in seconds. The coordinates of this object are extracted via the
"toSec" call. These two coordinates are added together and used as an argument in the construction of the ros::Time object.
We've formalized this by interpreting t as a time expressed in the hardware_time_acs. We bind a value to it by constructing a new
value of type "time camera_time_seconds" via our mk_time call. The complexity resides in how we compute the coordinates to the new time.
We define an overload of the "toSec" call for both _ros_time_base and imu_msg.timestamp, whether to provide a global or context-dependent interpretation for
toSec is a nuanced issue. Regardless, both overloads of "toSec", "_ros_time_base_toSec" and "_imu_msg_timestamp_toSec", simply extract
the respective coordinates of _ros_time_base and _imu_msg_timestamp. Thus, the respective overloads are applied using the respective values, _ros_time_base and _imu_msg_timestamp,
and the resulting expressions, which have type "scalar", are added together and supplied as an argument to the newly constructed time.
Note here that, although there is no error here, there should be. The coordinates composing the addition operation hail from two different spaces: platform_time_acs and camera_time_seconds,
which should yield a type error - as these coordinates hail from different ACSes.
-/
let t : time camera_time_seconds :=
mk_time _
((
let _ros_time_base_toSec : time platform_time_in_seconds → scalar :=
λt,
(t).coord in
_ros_time_base_toSec _ros_time_base
)
+
(
--casting time to duration discussed
--Whether or not to first convert "imu_msg.timestamp" from a time (point) to a duration (vector) should be confirmed by Dr. S
--let imu_time_as_duration := mk_duration camera_time_seconds imu_msg.timestamp.coord in
let _imu_msg_timestamp_toSec : time camera_time_seconds → scalar :=
λt,
t.coord in
_imu_msg_timestamp_toSec imu_msg.timestamp--imu_time_as_duration
)) in
punit.star |
3c40efce95a89be931272090682e14d0a95d3017 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/library_search/nat.lean | 2f88dfda03f360972531ac7b84221c66ba32c3a7 | [
"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,467 | 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 tactic.suggest
import data.nat.basic
namespace test.library_search
/- Turn off trace messages so they don't pollute the test build: -/
set_option trace.silence_library_search true
/- For debugging purposes, we can display the list of lemmas: -/
-- set_option trace.suggest true
def lt_one (n : ℕ) := n < 1
lemma zero_lt_one (n : ℕ) (h : n = 0) : lt_one n := by subst h; dsimp [lt_one]; simp
-- Verify that calls to solve_by_elim to discharge subgoals use `rfl`
example : lt_one 0 :=
by library_search
example {n m : ℕ} (h : m < n) : m ≤ n - 1 :=
by library_search -- says: `exact nat.le_pred_of_lt h`
example (a b : ℕ) : 0 < a → 0 < b → 0 < a + b :=
by library_search -- says: `exact add_pos`
section synonym
-- Synonym `>` for `<` in the goal
example (a b : ℕ) : 0 < a → 0 < b → a + b > 0 :=
by library_search -- says: `exact add_pos`
-- Synonym `>` for `<` in another part of the goal
example (a b : ℕ) : a > 0 → 0 < b → 0 < a + b :=
by library_search -- says: `exact add_pos`
end synonym
example {a b c : ℕ} (ha : a > 0) (w : b ∣ c) : a * b ∣ a * c :=
by library_search -- exact mul_dvd_mul_left a w
-- We have control of how `library_search` uses `solve_by_elim`.
-- In particular, we can add extra lemmas to the `solve_by_elim` step
-- (i.e. for `library_search` to use to attempt to discharge subgoals
-- after successfully applying a lemma from the library.)
example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=
begin
library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)`
end
-- We can also use attributes:
meta def ex_attr : user_attribute := {
name := `ex,
descr := "A lemma that should be applied by `library_search` when discharging subgoals."
}
run_cmd attribute.register ``ex_attr
attribute [ex] add_lt_add
example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) :=
begin
library_search with ex, -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)`
end
example (a b : ℕ) (h : 0 < b) : (a * b) / b = a :=
by library_search -- Says: `exact nat.mul_div_left a h`
example (a b : ℕ) (h : b ≠ 0) : (a * b) / b = a :=
begin
success_if_fail { library_search },
library_search [pos_iff_ne_zero.mpr],
end
end test.library_search
|
49631c0fd4afe0df604afc28bcdf13b2729bcacf | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/data/real/nnreal.lean | e00bd3c2478bda624c61ea0e6f633643358333b6 | [
"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 | 24,883 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
Nonnegative real numbers.
-/
import data.real.basic order.lattice algebra.field
noncomputable theory
open_locale classical
/-- Nonnegative real numbers. -/
def nnreal := {r : ℝ // 0 ≤ r}
localized "notation ` ℝ≥0 ` := nnreal" in nnreal
namespace nnreal
instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩
/- Simp lemma to put back `n.val` into the normal form given by the coercion. -/
@[simp] lemma val_eq_coe (n : nnreal) : n.val = n := rfl
instance : can_lift ℝ nnreal :=
{ coe := coe,
cond := λ r, r ≥ 0,
prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ }
protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq
protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m :=
iff.intro nnreal.eq (congr_arg coe)
lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y :=
not_iff_not_of_iff $ nnreal.eq_iff
protected def of_real (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩
lemma coe_of_real (r : ℝ) (hr : 0 ≤ r) : (nnreal.of_real r : ℝ) = r :=
max_eq_left hr
lemma le_coe_of_real (r : ℝ) : r ≤ nnreal.of_real r :=
le_max_left r 0
lemma coe_nonneg (r : nnreal) : (0 : ℝ) ≤ r := r.2
@[elim_cast, simp, nolint simp_nf] -- takes a crazy amount of time simplify lhs
theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl
instance : has_zero ℝ≥0 := ⟨⟨0, le_refl 0⟩⟩
instance : has_one ℝ≥0 := ⟨⟨1, zero_le_one⟩⟩
instance : has_add ℝ≥0 := ⟨λa b, ⟨a + b, add_nonneg a.2 b.2⟩⟩
instance : has_sub ℝ≥0 := ⟨λa b, nnreal.of_real (a - b)⟩
instance : has_mul ℝ≥0 := ⟨λa b, ⟨a * b, mul_nonneg a.2 b.2⟩⟩
instance : has_inv ℝ≥0 := ⟨λa, ⟨(a.1)⁻¹, inv_nonneg.2 a.2⟩⟩
instance : has_div ℝ≥0 := ⟨λa b, ⟨a.1 / b.1, div_nonneg' a.2 b.2⟩⟩
instance : has_le ℝ≥0 := ⟨λ r s, (r:ℝ) ≤ s⟩
instance : has_bot ℝ≥0 := ⟨0⟩
instance : inhabited ℝ≥0 := ⟨0⟩
@[simp] protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
@[simp] protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
@[simp, move_cast] protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl
@[simp, move_cast] protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl
@[simp, move_cast] protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl
@[simp, move_cast] protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl
@[simp] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ :=
max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h]
-- TODO: setup semifield!
@[simp] protected lemma zero_div (r : ℝ≥0) : 0 / r = 0 := nnreal.eq (zero_div _)
@[simp, elim_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := @nnreal.eq_iff r 0
@[elim_cast] lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by simp
instance : comm_semiring ℝ≥0 :=
begin
refine { zero := 0, add := (+), one := 1, mul := (*), ..};
{ intros;
apply nnreal.eq;
simp [mul_comm, mul_assoc, add_comm_monoid.add, left_distrib, right_distrib,
add_comm_monoid.zero, add_comm, add_left_comm] }
end
instance : is_semiring_hom (coe : ℝ≥0 → ℝ) := by refine_struct {..}; intros; refl
instance : comm_group_with_zero ℝ≥0 :=
{ zero_ne_one := assume h, zero_ne_one $ nnreal.eq_iff.2 h,
inv_zero := nnreal.eq $ inv_zero,
mul_inv_cancel := assume x h, nnreal.eq $ mul_inv_cancel $ ne_iff.2 h,
.. (by apply_instance : has_inv ℝ≥0),
.. (_ : comm_semiring ℝ≥0),
.. (_ : semiring ℝ≥0) }
@[move_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
is_monoid_hom.map_pow coe r n
@[move_cast] lemma coe_list_sum (l : list ℝ≥0) :
((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum :=
eq.symm $ l.sum_hom coe
@[move_cast] lemma coe_list_prod (l : list ℝ≥0) :
((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod :=
eq.symm $ l.prod_hom coe
@[move_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) :
((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum :=
eq.symm $ s.sum_hom coe
@[move_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) :
((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod :=
eq.symm $ s.prod_hom coe
@[move_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.sum f) = s.sum (λa, (f a : ℝ)) :=
eq.symm $ s.sum_hom coe
@[move_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} :
↑(s.prod f) = s.prod (λa, (f a : ℝ)) :=
eq.symm $ s.prod_hom coe
@[move_cast] lemma smul_coe (r : ℝ≥0) (n : ℕ) : ↑(add_monoid.smul n r) = add_monoid.smul n (r:ℝ) :=
is_add_monoid_hom.map_smul coe r n
@[simp, squash_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
(ring_hom.of (coe : ℝ≥0 → ℝ)).map_nat_cast n
instance : decidable_linear_order ℝ≥0 :=
decidable_linear_order.lift (coe : ℝ≥0 → ℝ) subtype.val_injective (by apply_instance)
@[elim_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl
@[elim_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl
@[elim_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl
@[elim_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := subtype.ext.symm
protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2
protected lemma of_real_mono : monotone nnreal.of_real :=
λ x y h, max_le_max h (le_refl 0)
@[simp] lemma of_real_coe {r : ℝ≥0} : nnreal.of_real r = r :=
nnreal.eq $ max_eq_left r.2
/-- `nnreal.of_real` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/
protected def gi : galois_insertion nnreal.of_real coe :=
galois_insertion.monotone_intro nnreal.coe_mono nnreal.of_real_mono
le_coe_of_real (λ _, of_real_coe)
instance : order_bot ℝ≥0 :=
{ bot := ⊥, bot_le := assume ⟨a, h⟩, h, .. nnreal.decidable_linear_order }
instance : canonically_ordered_add_monoid ℝ≥0 :=
{ add_le_add_left := assume a b h c, @add_le_add_left ℝ _ a b h c,
lt_of_add_lt_add_left := assume a b c, @lt_of_add_lt_add_left ℝ _ a b c,
le_iff_exists_add := assume ⟨a, ha⟩ ⟨b, hb⟩,
iff.intro
(assume h : a ≤ b,
⟨⟨b - a, le_sub_iff_add_le.2 $ by simp [h]⟩,
nnreal.eq $ show b = a + (b - a), by rw [add_sub_cancel'_right]⟩)
(assume ⟨⟨c, hc⟩, eq⟩, eq.symm ▸ show a ≤ a + c, from (le_add_iff_nonneg_right a).2 hc),
..nnreal.comm_semiring,
..nnreal.order_bot,
..nnreal.decidable_linear_order }
instance : distrib_lattice ℝ≥0 := by apply_instance
instance : semilattice_inf_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : semilattice_sup_bot ℝ≥0 :=
{ .. nnreal.order_bot, .. nnreal.distrib_lattice }
instance : linear_ordered_semiring ℝ≥0 :=
{ add_left_cancel := assume a b c h, nnreal.eq $ @add_left_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
add_right_cancel := assume a b c h, nnreal.eq $ @add_right_cancel ℝ _ a b c (nnreal.eq_iff.2 h),
le_of_add_le_add_left := assume a b c, @le_of_add_le_add_left ℝ _ a b c,
mul_lt_mul_of_pos_left := assume a b c, @mul_lt_mul_of_pos_left ℝ _ a b c,
mul_lt_mul_of_pos_right := assume a b c, @mul_lt_mul_of_pos_right ℝ _ a b c,
zero_lt_one := @zero_lt_one ℝ _,
.. nnreal.decidable_linear_order,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : canonically_ordered_comm_semiring ℝ≥0 :=
{ zero_ne_one := assume h, @zero_ne_one ℝ _ $ congr_arg subtype.val $ h,
mul_eq_zero_iff := assume a b, nnreal.eq_iff.symm.trans $ mul_eq_zero.trans $ by simp,
.. nnreal.linear_ordered_semiring,
.. nnreal.canonically_ordered_add_monoid,
.. nnreal.comm_semiring }
instance : densely_ordered ℝ≥0 :=
⟨assume a b (h : (a : ℝ) < b), let ⟨c, hac, hcb⟩ := dense h in
⟨⟨c, le_trans a.property $ le_of_lt $ hac⟩, hac, hcb⟩⟩
instance : no_top_order ℝ≥0 :=
⟨assume a, let ⟨b, hb⟩ := no_top (a:ℝ) in ⟨⟨b, le_trans a.property $ le_of_lt $ hb⟩, hb⟩⟩
lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : nnreal → ℝ) '' s) ↔ bdd_above s :=
iff.intro
(assume ⟨b, hb⟩, ⟨nnreal.of_real b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from
le_max_left_of_le $ hb $ set.mem_image_of_mem _ hys⟩)
(assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩)
lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : nnreal → ℝ) '' s) :=
⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩
instance : has_Sup ℝ≥0 :=
⟨λs, ⟨Sup ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Sup_empty] },
rcases h with ⟨⟨b, hb⟩, hbs⟩,
by_cases h' : bdd_above s,
{ exact le_cSup_of_le (bdd_above_coe.2 h') (set.mem_image_of_mem _ hbs) hb },
{ rw [real.Sup_of_not_bdd_above], rwa [bdd_above_coe] }
end⟩⟩
instance : has_Inf ℝ≥0 :=
⟨λs, ⟨Inf ((coe : nnreal → ℝ) '' s),
begin
cases s.eq_empty_or_nonempty with h h,
{ simp [h, set.image_empty, real.Inf_empty] },
exact le_cInf (h.image _) (assume r ⟨q, _, eq⟩, eq ▸ q.2)
end⟩⟩
lemma coe_Sup (s : set nnreal) : (↑(Sup s) : ℝ) = Sup ((coe : nnreal → ℝ) '' s) := rfl
lemma coe_Inf (s : set nnreal) : (↑(Inf s) : ℝ) = Inf ((coe : nnreal → ℝ) '' s) := rfl
instance : conditionally_complete_linear_order_bot ℝ≥0 :=
{ Sup := Sup,
Inf := Inf,
le_cSup := assume s a hs ha, le_cSup (bdd_above_coe.2 hs) (set.mem_image_of_mem _ ha),
cSup_le := assume s a hs h,show Sup ((coe : nnreal → ℝ) '' s) ≤ a, from
cSup_le (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cInf_le := assume s a _ has, cInf_le (bdd_below_coe s) (set.mem_image_of_mem _ has),
le_cInf := assume s a hs h, show (↑a : ℝ) ≤ Inf ((coe : nnreal → ℝ) '' s), from
le_cInf (by simp [hs]) $ assume r ⟨b, hb, eq⟩, eq ▸ h hb,
cSup_empty := nnreal.eq $ by simp [coe_Sup, real.Sup_empty]; refl,
decidable_le := begin assume x y, apply classical.dec end,
.. nnreal.linear_ordered_semiring, .. lattice_of_decidable_linear_order,
.. nnreal.order_bot }
instance : archimedean nnreal :=
⟨ assume x y pos_y,
let ⟨n, hr⟩ := archimedean.arch (x:ℝ) (pos_y : (0 : ℝ) < y) in
⟨n, show (x:ℝ) ≤ (add_monoid.smul n y : nnreal), by simp [*, smul_coe]⟩ ⟩
lemma le_of_forall_epsilon_le {a b : nnreal} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b :=
le_of_forall_le_of_dense $ assume x hxb,
begin
rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩,
exact h _ ((lt_add_iff_pos_right b).1 hxb)
end
lemma lt_iff_exists_rat_btwn (a b : nnreal) :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < nnreal.of_real q ∧ nnreal.of_real q < b) :=
iff.intro
(assume (h : (↑a:ℝ) < (↑b:ℝ)),
let ⟨q, haq, hqb⟩ := exists_rat_btwn h in
have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq,
⟨q, rat.cast_nonneg.1 this, by simp [coe_of_real _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩)
(assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb)
lemma bot_eq_zero : (⊥ : nnreal) = 0 := rfl
lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) :=
begin
cases le_total b c with h h,
{ simp [sup_eq_max, max_eq_right h, max_eq_right (mul_le_mul_of_nonneg_left h (zero_le a))] },
{ simp [sup_eq_max, max_eq_left h, max_eq_left (mul_le_mul_of_nonneg_left h (zero_le a))] },
end
lemma mul_finset_sup {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
r * s.sup f = s.sup (λa, r * f a) :=
begin
refine s.induction_on _ _,
{ simp [bot_eq_zero] },
{ assume a s has ih, simp [has, ih, mul_sup], }
end
@[simp, move_cast] lemma coe_max (x y : nnreal) :
((max x y : nnreal) : ℝ) = max (x : ℝ) (y : ℝ) :=
by { delta max, split_ifs; refl }
@[simp, move_cast] lemma coe_min (x y : nnreal) :
((min x y : nnreal) : ℝ) = min (x : ℝ) (y : ℝ) :=
by { delta min, split_ifs; refl }
section of_real
@[simp] lemma zero_le_coe {q : nnreal} : 0 ≤ (q : ℝ) := q.2
@[simp] lemma of_real_zero : nnreal.of_real 0 = 0 :=
by simp [nnreal.of_real]; refl
@[simp] lemma of_real_one : nnreal.of_real 1 = 1 :=
by simp [nnreal.of_real, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl
@[simp] lemma of_real_pos {r : ℝ} : 0 < nnreal.of_real r ↔ 0 < r :=
by simp [nnreal.of_real, nnreal.coe_lt_coe.symm, lt_irrefl]
@[simp] lemma of_real_eq_zero {r : ℝ} : nnreal.of_real r = 0 ↔ r ≤ 0 :=
by simpa [-of_real_pos] using (not_iff_not.2 (@of_real_pos r))
lemma of_real_of_nonpos {r : ℝ} : r ≤ 0 → nnreal.of_real r = 0 :=
of_real_eq_zero.2
@[simp] lemma of_real_le_of_real_iff {r p : ℝ} (hp : 0 ≤ p) :
nnreal.of_real r ≤ nnreal.of_real p ↔ r ≤ p :=
by simp [nnreal.coe_le_coe.symm, nnreal.of_real, hp]
@[simp] lemma of_real_lt_of_real_iff' {r p : ℝ} :
nnreal.of_real r < nnreal.of_real p ↔ r < p ∧ 0 < p :=
by simp [nnreal.coe_lt_coe.symm, nnreal.of_real, lt_irrefl]
lemma of_real_lt_of_real_iff {r p : ℝ} (h : 0 < p) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans (and_iff_left h)
lemma of_real_lt_of_real_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
nnreal.of_real r < nnreal.of_real p ↔ r < p :=
of_real_lt_of_real_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩
@[simp] lemma of_real_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real (r + p) = nnreal.of_real r + nnreal.of_real p :=
nnreal.eq $ by simp [nnreal.of_real, hr, hp, add_nonneg]
lemma of_real_add_of_real {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
nnreal.of_real r + nnreal.of_real p = nnreal.of_real (r + p) :=
(of_real_add hr hp).symm
lemma of_real_le_of_real {r p : ℝ} (h : r ≤ p) : nnreal.of_real r ≤ nnreal.of_real p :=
nnreal.of_real_mono h
lemma of_real_add_le {r p : ℝ} : nnreal.of_real (r + p) ≤ nnreal.of_real r + nnreal.of_real p :=
nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe
lemma of_real_le_iff_le_coe {r : ℝ} {p : nnreal} : nnreal.of_real r ≤ p ↔ r ≤ ↑p :=
nnreal.gi.gc r p
lemma le_of_real_iff_coe_le {r : nnreal} {p : ℝ} (hp : p ≥ 0) : r ≤ nnreal.of_real p ↔ ↑r ≤ p :=
by rw [← nnreal.coe_le_coe, nnreal.coe_of_real p hp]
lemma of_real_lt_iff_lt_coe {r : ℝ} {p : nnreal} (ha : r ≥ 0) : nnreal.of_real r < p ↔ r < ↑p :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_of_real r ha]
lemma lt_of_real_iff_coe_lt {r : nnreal} {p : ℝ} : r < nnreal.of_real p ↔ ↑r < p :=
begin
cases le_total 0 p,
{ rw [← nnreal.coe_lt_coe, nnreal.coe_of_real p h] },
{ rw [of_real_eq_zero.2 h], split,
intro, have := not_lt_of_le (zero_le r), contradiction,
intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (coe_nonneg _) rp), contradiction }
end
end of_real
section mul
lemma mul_eq_mul_left {a b c : nnreal} (h : a ≠ 0) : (a * b = a * c ↔ b = c) :=
begin
rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split,
{ exact eq_of_mul_eq_mul_left (mt (@nnreal.eq_iff a 0).1 h) },
{ assume h, rw [h] }
end
lemma of_real_mul {p q : ℝ} (hp : 0 ≤ p) :
nnreal.of_real (p * q) = nnreal.of_real p * nnreal.of_real q :=
begin
cases le_total 0 q with hq hq,
{ apply nnreal.eq,
have := max_eq_left (mul_nonneg hp hq),
simpa [nnreal.of_real, hp, hq, max_eq_left] },
{ have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq,
rw [of_real_eq_zero.2 hq, of_real_eq_zero.2 hpq, mul_zero] }
end
@[field_simps] theorem mul_ne_zero' {a b : nnreal} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 :=
mul_ne_zero'' h₁ h₂
end mul
section sub
lemma sub_def {r p : ℝ≥0} : r - p = nnreal.of_real (r - p) := rfl
lemma sub_eq_zero {r p : ℝ≥0} (h : r ≤ p) : r - p = 0 :=
nnreal.eq $ max_eq_right $ sub_le_iff_le_add.2 $ by simpa [nnreal.coe_le_coe] using h
@[simp] lemma sub_self {r : ℝ≥0} : r - r = 0 := sub_eq_zero $ le_refl r
@[simp] lemma sub_zero {r : ℝ≥0} : r - 0 = r :=
by rw [sub_def, nnreal.coe_zero, sub_zero, nnreal.of_real_coe]
lemma sub_pos {r p : ℝ≥0} : 0 < r - p ↔ p < r :=
of_real_pos.trans $ sub_pos.trans $ nnreal.coe_lt_coe
protected lemma sub_lt_self {r p : nnreal} : 0 < r → 0 < p → r - p < r :=
assume hr hp,
begin
cases le_total r p,
{ rwa [sub_eq_zero h] },
{ rw [← nnreal.coe_lt_coe, nnreal.coe_sub h], exact sub_lt_self _ hp }
end
@[simp] lemma sub_le_iff_le_add {r p q : nnreal} : r - p ≤ q ↔ r ≤ q + p :=
match le_total p r with
| or.inl h :=
by rw [← nnreal.coe_le_coe, ← nnreal.coe_le_coe, nnreal.coe_sub h, nnreal.coe_add, sub_le_iff_le_add]
| or.inr h :=
have r ≤ p + q, from le_add_right h,
by simpa [nnreal.coe_le_coe, nnreal.coe_le_coe, sub_eq_zero h, add_comm]
end
@[simp] lemma sub_le_self {r p : ℝ≥0} : r - p ≤ r :=
sub_le_iff_le_add.2 $ le_add_right $ le_refl r
lemma add_sub_cancel {r p : nnreal} : (p + r) - r = p :=
nnreal.eq $ by rw [nnreal.coe_sub, nnreal.coe_add, add_sub_cancel]; exact le_add_left (le_refl _)
lemma add_sub_cancel' {r p : nnreal} : (r + p) - r = p :=
by rw [add_comm, add_sub_cancel]
@[simp] lemma sub_add_cancel_of_le {a b : nnreal} (h : b ≤ a) : (a - b) + b = a :=
nnreal.eq $ by rw [nnreal.coe_add, nnreal.coe_sub h, sub_add_cancel]
lemma sub_sub_cancel_of_le {r p : ℝ≥0} (h : r ≤ p) : p - (p - r) = r :=
by rw [nnreal.sub_def, nnreal.sub_def, nnreal.coe_of_real _ $ sub_nonneg.2 h,
sub_sub_cancel, nnreal.of_real_coe]
lemma lt_sub_iff_add_lt {p q r : nnreal} : p < q - r ↔ p + r < q :=
begin
split,
{ assume H,
have : (((q - r) : nnreal) : ℝ) = (q : ℝ) - (r : ℝ) :=
nnreal.coe_sub (le_of_lt (sub_pos.1 (lt_of_le_of_lt (zero_le _) H))),
rwa [← nnreal.coe_lt_coe, this, lt_sub_iff_add_lt, ← nnreal.coe_add] at H },
{ assume H,
have : r ≤ q := le_trans (le_add_left (le_refl _)) (le_of_lt H),
rwa [← nnreal.coe_lt_coe, nnreal.coe_sub this, lt_sub_iff_add_lt, ← nnreal.coe_add] }
end
end sub
section inv
lemma div_def {r p : nnreal} : r / p = r * p⁻¹ := rfl
@[simp] lemma inv_zero : (0 : nnreal)⁻¹ = 0 := nnreal.eq inv_zero
@[simp] lemma inv_eq_zero {r : nnreal} : (r : nnreal)⁻¹ = 0 ↔ r = 0 :=
inv_eq_zero
@[simp] lemma inv_pos {r : nnreal} : 0 < r⁻¹ ↔ 0 < r :=
by simp [zero_lt_iff_ne_zero]
lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p :=
mul_pos hr (inv_pos.2 hp)
@[simp] lemma inv_one : (1:ℝ≥0)⁻¹ = 1 := nnreal.eq $ inv_one
@[simp] lemma div_one {r : ℝ≥0} : r / 1 = r := by rw [div_def, inv_one, mul_one]
protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv' _ _
protected lemma inv_pow {r : ℝ≥0} {n : ℕ} : (r^n)⁻¹ = (r⁻¹)^n :=
nnreal.eq $ by { push_cast, exact (inv_pow' _ _).symm }
@[simp] lemma inv_mul_cancel {r : ℝ≥0} (h : r ≠ 0) : r⁻¹ * r = 1 :=
nnreal.eq $ inv_mul_cancel $ mt (@nnreal.eq_iff r 0).1 h
@[simp] lemma mul_inv_cancel {r : ℝ≥0} (h : r ≠ 0) : r * r⁻¹ = 1 :=
by rw [mul_comm, inv_mul_cancel h]
@[simp] lemma div_self {r : ℝ≥0} (h : r ≠ 0) : r / r = 1 :=
mul_inv_cancel h
@[simp] lemma div_mul_cancel {r p : ℝ≥0} (h : p ≠ 0) : r / p * p = r :=
by rw [div_def, mul_assoc, inv_mul_cancel h, mul_one]
@[simp] lemma mul_div_cancel {r p : ℝ≥0} (h : p ≠ 0) : r * p / p = r :=
by rw [div_def, mul_assoc, mul_inv_cancel h, mul_one]
@[simp] lemma mul_div_cancel' {r p : ℝ≥0} (h : r ≠ 0) : r * (p / r) = p :=
by rw [mul_comm, div_mul_cancel h]
@[simp] lemma inv_inv {r : ℝ≥0} : r⁻¹⁻¹ = r := nnreal.eq (inv_inv' _)
@[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h]
lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p :=
by by_cases r = 0; simp [*, inv_le]
@[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) :=
by rw [← mul_le_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
@[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) :=
by rw [← mul_lt_mul_left (zero_lt_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm]
lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b :=
have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm,
by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul]
lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
by rw [div_def, mul_comm, ← mul_le_iff_le_inv hr, mul_comm]
lemma le_of_forall_lt_one_mul_lt {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y :=
le_of_forall_ge_of_dense $ assume a ha,
have hx : x ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha),
have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero],
have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv],
have (a * x⁻¹) * x ≤ y, from h _ this,
by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this
lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c :=
eq.symm $ right_distrib a b (c⁻¹)
lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two
lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a)
lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a :=
by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact
half_lt_self (bot_lt_iff_ne_bot.2 h)
lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 :=
by simpa [div_def] using half_lt_self zero_ne_one.symm
lemma div_lt_iff {a b c : ℝ≥0} (hc : c ≠ 0) : b / c < a ↔ b < a * c :=
begin
rw [← nnreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_div, nnreal.coe_mul],
exact div_lt_iff (zero_lt_iff_ne_zero.mpr hc)
end
lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 :=
begin
rwa [div_lt_iff, one_mul],
exact ne_of_gt (lt_of_le_of_lt (zero_le _) h)
end
@[field_simps] theorem div_pow {a b : ℝ≥0} (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
div_pow _ _ _
@[field_simps] lemma mul_div_assoc' (a b c : ℝ≥0) : a * (b / c) = (a * b) / c :=
by rw [div_def, div_def, mul_assoc]
@[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0}
(hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) :=
begin
rw ← nnreal.eq_iff,
simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul],
exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd)
end
@[field_simps] lemma inv_eq_one_div (a : ℝ≥0) : a⁻¹ = 1/a :=
by rw [div_def, one_mul]
@[field_simps] lemma div_mul_eq_mul_div (a b c : ℝ≥0) : (a / b) * c = (a * c) / b :=
by { rw [div_def, div_def], ac_refl }
@[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) :
b + a / c = (b * c + a) / c :=
by simpa using div_add_div b a one_ne_zero hc
@[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) :
a / c + b = (a + b * c) / c :=
by rwa [add_comm, add_div', add_comm]
lemma one_div_eq_inv (a : ℝ≥0) : 1 / a = a⁻¹ :=
one_mul a⁻¹
lemma one_div_div (a b : ℝ≥0) : 1 / (a / b) = b / a :=
by { rw ← nnreal.eq_iff, simp [one_div_div] }
lemma div_eq_mul_one_div (a b : ℝ≥0) : a / b = a * (1 / b) :=
by rw [div_def, div_def, one_mul]
@[field_simps] lemma div_div_eq_mul_div (a b c : ℝ≥0) : a / (b / c) = (a * c) / b :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_mul_div] }
@[field_simps] lemma div_div_eq_div_mul (a b c : ℝ≥0) : (a / b) / c = a / (b * c) :=
by { rw ← nnreal.eq_iff, simp [div_div_eq_div_mul] }
@[field_simps] lemma div_eq_div_iff {a b c d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) :
a / b = c / d ↔ a * d = c * b :=
div_eq_div_iff hb hd
@[field_simps] lemma div_eq_iff {a b c : ℝ≥0} (hb : b ≠ 0) : a / b = c ↔ a = c * b :=
by simpa using @div_eq_div_iff a b c 1 hb one_ne_zero
@[field_simps] lemma eq_div_iff {a b c : ℝ≥0} (hb : b ≠ 0) : c = a / b ↔ c * b = a :=
by simpa using @div_eq_div_iff c 1 a b one_ne_zero hb
end inv
section pow
theorem pow_eq_zero {a : ℝ≥0} {n : ℕ} (h : a^n = 0) : a = 0 :=
begin
rw ← nnreal.eq_iff,
rw [← nnreal.eq_iff, coe_pow] at h,
exact pow_eq_zero h
end
@[field_simps] theorem pow_ne_zero {a : ℝ≥0} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
end pow
end nnreal
|
daa3d33710cc5076d15ce34d93a3e8280f480b99 | 4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d | /src/Lean/Util/Recognizers.lean | 9447e91aa87e872aeb91638d39a47e1dfb929ec1 | [
"Apache-2.0"
] | permissive | subfish-zhou/leanprover-zh_CN.github.io | 30b9fba9bd790720bd95764e61ae796697d2f603 | 8b2985d4a3d458ceda9361ac454c28168d920d3f | refs/heads/master | 1,689,709,967,820 | 1,632,503,056,000 | 1,632,503,056,000 | 409,962,097 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,031 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Environment
namespace Lean
namespace Expr
@[inline] def const? (e : Expr) : Option (Name × List Level) :=
match e with
| Expr.const n us _ => some (n, us)
| _ => none
@[inline] def app1? (e : Expr) (fName : Name) : Option Expr :=
if e.isAppOfArity fName 1 then
some e.appArg!
else
none
@[inline] def app2? (e : Expr) (fName : Name) : Option (Expr × Expr) :=
if e.isAppOfArity fName 2 then
some (e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def app3? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr) :=
if e.isAppOfArity fName 3 then
some (e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def app4? (e : Expr) (fName : Name) : Option (Expr × Expr × Expr × Expr) :=
if e.isAppOfArity fName 4 then
some (e.appFn!.appFn!.appFn!.appArg!, e.appFn!.appFn!.appArg!, e.appFn!.appArg!, e.appArg!)
else
none
@[inline] def eq? (p : Expr) : Option (Expr × Expr × Expr) :=
p.app3? ``Eq
@[inline] def ne? (p : Expr) : Option (Expr × Expr × Expr) :=
p.app3? ``Ne
@[inline] def iff? (p : Expr) : Option (Expr × Expr) :=
p.app2? ``Iff
@[inline] def not? (p : Expr) : Option Expr :=
p.app1? ``Not
@[inline] def notNot? (p : Expr) : Option Expr :=
match p.not? with
| some p => p.not?
| none => none
@[inline] def and? (p : Expr) : Option (Expr × Expr) :=
p.app2? ``And
@[inline] def heq? (p : Expr) : Option (Expr × Expr × Expr × Expr) :=
p.app4? ``HEq
def natAdd? (e : Expr) : Option (Expr × Expr) :=
e.app2? ``Nat.add
@[inline] def arrow? : Expr → Option (Expr × Expr)
| Expr.forallE _ α β _ => if β.hasLooseBVars then none else some (α, β)
| _ => none
def isEq (e : Expr) :=
e.isAppOfArity ``Eq 3
def isHEq (e : Expr) :=
e.isAppOfArity ``HEq 4
def isIte (e : Expr) :=
e.isAppOfArity ``ite 5
def isDIte (e : Expr) :=
e.isAppOfArity ``dite 5
partial def listLit? (e : Expr) : Option (Expr × List Expr) :=
let rec loop (e : Expr) (acc : List Expr) :=
if e.isAppOfArity ``List.nil 1 then
some (e.appArg!, acc.reverse)
else if e.isAppOfArity ``List.cons 3 then
loop e.appArg! (e.appFn!.appArg! :: acc)
else
none
loop e []
def arrayLit? (e : Expr) : Option (Expr × List Expr) :=
match e.app2? ``List.toArray with
| some (_, e) => e.listLit?
| none => none
/-- Recognize `α × β` -/
def prod? (e : Expr) : Option (Expr × Expr) :=
e.app2? ``Prod
private def getConstructorVal? (env : Environment) (ctorName : Name) : Option ConstructorVal := do
match env.find? ctorName with
| some (ConstantInfo.ctorInfo v) => v
| _ => none
def isConstructorApp? (env : Environment) (e : Expr) : Option ConstructorVal :=
match e with
| Expr.lit (Literal.natVal n) _ => if n == 0 then getConstructorVal? env `Nat.zero else getConstructorVal? env `Nat.succ
| _ =>
match e.getAppFn with
| Expr.const n _ _ => match getConstructorVal? env n with
| some v => if v.numParams + v.numFields == e.getAppNumArgs then some v else none
| none => none
| _ => none
def isConstructorApp (env : Environment) (e : Expr) : Bool :=
e.isConstructorApp? env |>.isSome
def constructorApp? (env : Environment) (e : Expr) : Option (ConstructorVal × Array Expr) :=
OptionM.run do
match e with
| Expr.lit (Literal.natVal n) _ =>
if n == 0 then do
let v ← getConstructorVal? env `Nat.zero
pure (v, #[])
else do
let v ← getConstructorVal? env `Nat.succ
pure (v, #[mkNatLit (n-1)])
| _ =>
match e.getAppFn with
| Expr.const n _ _ => do
let v ← getConstructorVal? env n
if v.numParams + v.numFields == e.getAppNumArgs then
pure (v, e.getAppArgs)
else
none
| _ => none
end Lean.Expr
|
d8d3531256eb589796409dcd319b2ac52de55422 | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/topology/sheaves/sheaf_condition/pairwise_intersections.lean | 6b7f1e1bb5d78b2e2556f57cf867fbbb5de0512d | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 12,070 | 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 topology.sheaves.sheaf
import category_theory.limits.preserves.basic
import category_theory.category.pairwise
/-!
# Equivalent formulations of the sheaf condition
We give an equivalent formulation of the sheaf condition.
Given any indexed type `ι`, we define `overlap ι`,
a category with objects corresponding to
* individual open sets, `single i`, and
* intersections of pairs of open sets, `pair i j`,
with morphisms from `pair i j` to both `single i` and `single j`.
Any open cover `U : ι → opens X` provides a functor `diagram U : overlap ι ⥤ (opens X)ᵒᵖ`.
There is a canonical cone over this functor, `cone U`, whose cone point is `supr U`,
and in fact this is a limit cone.
A presheaf `F : presheaf C X` is a sheaf precisely if it preserves this limit.
We express this in two equivalent ways, as
* `is_limit (F.map_cone (cone U))`, or
* `preserves_limit (diagram U) F`
-/
noncomputable theory
universes v u
open topological_space
open Top
open category_theory
open category_theory.limits
namespace Top.presheaf
variables {X : Top.{v}}
variables {C : Type u} [category.{v} C]
/--
An alternative formulation of the sheaf condition
(which we prove equivalent to the usual one below as
`sheaf_condition_equiv_sheaf_condition_pairwise_intersections`).
A presheaf is a sheaf if `F` sends the cone `pairwise.cone U` to a limit cone.
(Recall `pairwise.cone U`, has cone point `supr U`, mapping down to the `U i` and the `U i ⊓ U j`.)
-/
@[derive subsingleton, nolint has_inhabited_instance]
def sheaf_condition_pairwise_intersections (F : presheaf C X) : Type (max u (v+1)) :=
Π ⦃ι : Type v⦄ (U : ι → opens X), is_limit (F.map_cone (pairwise.cone U))
/--
An alternative formulation of the sheaf condition
(which we prove equivalent to the usual one below as
`sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections`).
A presheaf is a sheaf if `F` preserves the limit of `pairwise.diagram U`.
(Recall `pairwise.diagram U` is the diagram consisting of the pairwise intersections
`U i ⊓ U j` mapping into the open sets `U i`. This diagram has limit `supr U`.)
-/
@[derive subsingleton, nolint has_inhabited_instance]
def sheaf_condition_preserves_limit_pairwise_intersections
(F : presheaf C X) : Type (max u (v+1)) :=
Π ⦃ι : Type v⦄ (U : ι → opens X), preserves_limit (pairwise.diagram U) F
/-!
The remainder of this file shows that these conditions are equivalent
to the usual sheaf condition.
-/
variables [has_products C]
namespace sheaf_condition_pairwise_intersections
open category_theory.pairwise category_theory.pairwise.hom
open sheaf_condition_equalizer_products
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps]
def cone_equiv_functor_obj (F : presheaf C X)
⦃ι : Type v⦄ (U : ι → opens ↥X) (c : limits.cone (diagram U ⋙ F)) :
limits.cone (sheaf_condition_equalizer_products.diagram F U) :=
{ X := c.X,
π :=
{ app := λ Z,
walking_parallel_pair.cases_on Z
(pi.lift (λ (i : ι), c.π.app (single i)))
(pi.lift (λ (b : ι × ι), c.π.app (pair b.1 b.2))),
naturality' := λ Y Z f,
begin
cases Y; cases Z; cases f,
{ ext i, dsimp,
simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc],
dsimp,
simp only [limit.lift_π, category.id_comp, fan.mk_π_app], },
{ ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.left_res],
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
have h := c.π.naturality (hom.left i j),
dsimp at h,
simpa using h, },
{ ext ⟨i, j⟩, dsimp [sheaf_condition_equalizer_products.right_res],
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
have h := c.π.naturality (hom.right i j),
dsimp at h,
simpa using h, },
{ ext i, dsimp,
simp only [limit.lift_π, category.id_comp, fan.mk_π_app, category_theory.functor.map_id, category.assoc],
dsimp,
simp only [limit.lift_π, category.id_comp, fan.mk_π_app], },
end, }, }
section
local attribute [tidy] tactic.case_bash
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps]
def cone_equiv_functor (F : presheaf C X)
⦃ι : Type v⦄ (U : ι → opens ↥X) :
limits.cone (diagram U ⋙ F) ⥤ limits.cone (sheaf_condition_equalizer_products.diagram F U) :=
{ obj := λ c, cone_equiv_functor_obj F U c,
map := λ c c' f,
{ hom := f.hom, }, }.
end
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps]
def cone_equiv_inverse_obj (F : presheaf C X)
⦃ι : Type v⦄ (U : ι → opens ↥X)
(c : limits.cone (sheaf_condition_equalizer_products.diagram F U)) : limits.cone (diagram U ⋙ F) :=
{ X := c.X,
π :=
{ app :=
begin
rintro (⟨i⟩|⟨i,j⟩),
{ exact c.π.app (walking_parallel_pair.zero) ≫ pi.π _ i, },
{ exact c.π.app (walking_parallel_pair.one) ≫ pi.π _ (i, j), }
end,
naturality' :=
begin
rintro (⟨i⟩|⟨⟩) (⟨⟩|⟨j,j⟩) ⟨⟩,
{ dsimp, erw [F.map_id], simp, },
{ dsimp, simp only [category.id_comp, category.assoc],
have h := c.π.naturality (walking_parallel_pair_hom.left),
dsimp [sheaf_condition_equalizer_products.left_res] at h,
simp only [category.id_comp] at h,
have h' := h =≫ pi.π _ (i, j),
rw h',
simp,
refl, },
{ dsimp, simp only [category.id_comp, category.assoc],
have h := c.π.naturality (walking_parallel_pair_hom.right),
dsimp [sheaf_condition_equalizer_products.right_res] at h,
simp only [category.id_comp] at h,
have h' := h =≫ pi.π _ (j, i),
rw h',
simp,
refl, },
{ dsimp, erw [F.map_id], simp, },
end, }, }
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps]
def cone_equiv_inverse (F : presheaf C X)
⦃ι : Type v⦄ (U : ι → opens ↥X) :
limits.cone (sheaf_condition_equalizer_products.diagram F U) ⥤ limits.cone (diagram U ⋙ F) :=
{ obj := λ c, cone_equiv_inverse_obj F U c,
map := λ c c' f,
{ hom := f.hom,
w' :=
begin
rintro (⟨i⟩|⟨i,j⟩),
{ dsimp,
rw [←(f.w walking_parallel_pair.zero), category.assoc], },
{ dsimp,
rw [←(f.w walking_parallel_pair.one), category.assoc], },
end }, }.
section
local attribute [tidy] tactic.case_bash
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps]
def cone_equiv_unit_iso_app (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens ↥X)
(c : cone (diagram U ⋙ F)) :
(𝟭 (cone (diagram U ⋙ F))).obj c ≅
(cone_equiv_functor F U ⋙ cone_equiv_inverse F U).obj c :=
{ hom := { hom := 𝟙 _ }, inv := { hom := 𝟙 _ }}
end
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps {rhs_md := semireducible}]
def cone_equiv_unit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) :
𝟭 (limits.cone (diagram U ⋙ F)) ≅
cone_equiv_functor F U ⋙ cone_equiv_inverse F U :=
nat_iso.of_components (cone_equiv_unit_iso_app F U) (by tidy)
/-- Implementation of `sheaf_condition_pairwise_intersections.cone_equiv`. -/
@[simps {rhs_md := semireducible}]
def cone_equiv_counit_iso (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) :
cone_equiv_inverse F U ⋙ cone_equiv_functor F U ≅
𝟭 (limits.cone (sheaf_condition_equalizer_products.diagram F U)) :=
nat_iso.of_components (λ c,
{ hom :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨_|_⟩,
{ ext, dsimp, simp, },
{ ext ⟨i,j⟩, dsimp, simp, },
end },
inv :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨_|_⟩,
{ ext, dsimp, simp, },
{ ext ⟨i,j⟩, dsimp, simp, },
end, }}) (by tidy)
/--
Cones over `diagram U ⋙ F` are the same as a cones over the usual sheaf condition equalizer diagram.
-/
@[simps]
def cone_equiv (F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X) :
limits.cone (diagram U ⋙ F) ≌ limits.cone (sheaf_condition_equalizer_products.diagram F U) :=
{ functor := cone_equiv_functor F U,
inverse := cone_equiv_inverse F U,
unit_iso := cone_equiv_unit_iso F U,
counit_iso := cone_equiv_counit_iso F U, }
local attribute [reducible]
sheaf_condition_equalizer_products.res
sheaf_condition_equalizer_products.left_res
/--
If `sheaf_condition_equalizer_products.fork` is an equalizer,
then `F.map_cone (cone U)` is a limit cone.
-/
def is_limit_map_cone_of_is_limit_sheaf_condition_fork
(F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X)
(P : is_limit (sheaf_condition_equalizer_products.fork F U)) :
is_limit (F.map_cone (cone U)) :=
is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U).symm).symm P)
{ hom :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨⟩,
{ dsimp, simp, refl, },
{ dsimp,
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
rw ←F.map_comp,
refl, }
end },
inv :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨⟩,
{ dsimp, simp, refl, },
{ dsimp,
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
rw ←F.map_comp,
refl, }
end }, }
/--
If `F.map_cone (cone U)` is a limit cone,
then `sheaf_condition_equalizer_products.fork` is an equalizer.
-/
def is_limit_sheaf_condition_fork_of_is_limit_map_cone
(F : presheaf C X) ⦃ι : Type v⦄ (U : ι → opens X)
(Q : is_limit (F.map_cone (cone U))) :
is_limit (sheaf_condition_equalizer_products.fork F U) :=
is_limit.of_iso_limit ((is_limit.of_cone_equiv (cone_equiv F U)).symm Q)
{ hom :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨⟩,
{ dsimp, simp, refl, },
{ dsimp, ext ⟨i, j⟩,
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
rw ←F.map_comp,
refl, }
end },
inv :=
{ hom := 𝟙 _,
w' :=
begin
rintro ⟨⟩,
{ dsimp, simp, refl, },
{ dsimp, ext ⟨i, j⟩,
simp only [limit.lift_π, limit.lift_π_assoc, category.id_comp, fan.mk_π_app, category.assoc],
rw ←F.map_comp,
refl, }
end }, }
end sheaf_condition_pairwise_intersections
open sheaf_condition_pairwise_intersections
/--
The sheaf condition in terms of an equalizer diagram is equivalent
to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`.
-/
def sheaf_condition_equiv_sheaf_condition_pairwise_intersections (F : presheaf C X) :
F.sheaf_condition ≃ F.sheaf_condition_pairwise_intersections :=
equiv.Pi_congr_right (λ i, equiv.Pi_congr_right (λ U,
equiv_of_subsingleton_of_subsingleton
(is_limit_map_cone_of_is_limit_sheaf_condition_fork F U)
(is_limit_sheaf_condition_fork_of_is_limit_map_cone F U)))
/--
The sheaf condition in terms of an equalizer diagram is equivalent
to the reformulation in terms of the presheaf preserving the limit of the diagram
consisting of the `U i` and `U i ⊓ U j`.
-/
def sheaf_condition_equiv_sheaf_condition_preserves_limit_pairwise_intersections
(F : presheaf C X) :
F.sheaf_condition ≃ F.sheaf_condition_preserves_limit_pairwise_intersections :=
equiv.trans
(sheaf_condition_equiv_sheaf_condition_pairwise_intersections F)
(equiv.Pi_congr_right (λ i, equiv.Pi_congr_right (λ U,
equiv_of_subsingleton_of_subsingleton
(λ P, preserves_limit_of_preserves_limit_cone (pairwise.cone_is_limit U) P)
(by { introI, exact preserves_limit.preserves (pairwise.cone_is_limit U) }))))
end Top.presheaf
|
d87546045265c38a97f25f8641d245773bcac91d | cbcb0199842f03e7606d4e43666573fc15dd07a5 | /src/topology/metric_space/basic.lean | 6ca34d759a3a0ce4fcaf228e0ea7b1749dda6ae9 | [
"Apache-2.0"
] | permissive | truonghoangle/mathlib | a6a7c14b3767ec71156239d8ea97f6921fe79627 | 673bae584febcd830c2c9256eb7e7a81e27ed303 | refs/heads/master | 1,590,347,998,944 | 1,559,728,860,000 | 1,559,728,860,000 | 187,431,971 | 0 | 0 | null | 1,558,238,525,000 | 1,558,238,525,000 | null | UTF-8 | Lean | false | false | 56,228 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Metric spaces.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
-/
import data.real.nnreal topology.metric_space.emetric_space topology.algebra.ordered
open lattice set filter classical topological_space
noncomputable theory
local notation `𝓤` := uniformity
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Construct a uniform structure from a distance function and metric space axioms -/
def uniform_space_of_dist
(dist : α → α → ℝ)
(dist_self : ∀ x : α, dist x x = 0)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt},
comp := le_infi $ assume ε, le_infi $ assume h, lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos_of_pos_of_pos h two_pos) (subset.refl _)) $
have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε,
from assume a b c hac hcb,
calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _
... < ε / 2 + ε / 2 : add_lt_add hac hcb
... = ε : by rw [div_add_div_same, add_self_div_two],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] }
/-- The distance function (given an ambient metric space on `α`), which returns
a nonnegative real number `dist x y` given `x y : α`. -/
class has_dist (α : Type*) := (dist : α → α → ℝ)
export has_dist (dist)
/-- Metric space
Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. In the same way, each metric space induces an emetric space structure.
It is included in the structure, but filled in by default.
When one instantiates a metric space structure, for instance a product structure,
this makes it possible to use a uniform structure and an edistance that are exactly
the ones for the uniform spaces product and the emetric spaces products, thereby
ensuring that everything in defeq in diamonds.-/
class metric_space (α : Type u) extends has_dist α : Type u :=
(dist_self : ∀ x : α, dist x x = 0)
(eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y)
(dist_comm : ∀ x y : α, dist x y = dist y x)
(dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z)
(edist : α → α → ennreal := λx y, ennreal.of_real (dist x y))
(edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac)
(to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle)
(uniformity_dist : 𝓤 α = ⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε} . control_laws_tac)
variables [metric_space α]
instance metric_space.to_uniform_space' : uniform_space α :=
metric_space.to_uniform_space α
instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩
@[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x
theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y :=
metric_space.eq_of_dist_eq_zero
theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y
theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) :=
metric_space.edist_dist _ x y
@[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y :=
iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _)
@[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y :=
by rw [eq_comm, dist_eq_zero]
theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z :=
metric_space.dist_triangle x y z
theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y :=
by rw dist_comm z; apply dist_triangle
theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z :=
by rw dist_comm y; apply dist_triangle
lemma dist_triangle4 (x y z w : α) :
dist x w ≤ dist x y + dist y z + dist z w :=
calc
dist x w ≤ dist x z + dist z w : dist_triangle x z w
... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _
lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) :
dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) :=
by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4
lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) :
dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ :=
by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4
theorem swap_dist : function.swap (@dist α _) = dist :=
by funext x y; exact dist_comm _ _
theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y :=
abs_sub_le_iff.2
⟨sub_le_iff_le_add.2 (dist_triangle _ _ _),
sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩
theorem dist_nonneg {x y : α} : 0 ≤ dist x y :=
have 2 * dist x y ≥ 0,
from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul]
... ≥ 0 : by rw ← dist_self x; apply dist_triangle,
nonneg_of_mul_nonneg_left this two_pos
@[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y :=
by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y
@[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y :=
by simpa [-dist_le_zero] using not_congr (@dist_le_zero _ _ x y)
@[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b :=
abs_of_nonneg dist_nonneg
theorem eq_of_forall_dist_le {x y : α} (h : ∀ε, ε > 0 → dist x y ≤ ε) : x = y :=
eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h)
def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩
/--Express `nndist` in terms of `edist`-/
lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--Express `edist` in terms of `nndist`-/
lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) :=
by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real]
/--In a metric space, the extended distance is always finite-/
lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ :=
by rw [edist_dist x y]; apply ennreal.coe_ne_top
/--`nndist x x` vanishes-/
@[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a)
/--Express `dist` in terms of `nndist`-/
lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl
/--Express `nndist` in terms of `dist`-/
lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) :=
by rw [dist_nndist, nnreal.of_real_coe]
/--Deduce the equality of points with the vanishing of the nonnegative distance-/
theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
theorem nndist_comm (x y : α) : nndist x y = nndist y x :=
by simpa [nnreal.eq_iff.symm] using dist_comm x y
/--Characterize the equality of points with the vanishing of the nonnegative distance-/
@[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, dist_eq_zero]
@[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y :=
by simp only [nnreal.eq_iff.symm, (dist_nndist _ _).symm, imp_self, nnreal.coe_zero, zero_eq_dist]
/--Triangle inequality for the nonnegative distance-/
theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z :=
by simpa [nnreal.coe_le] using dist_triangle x y z
theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y :=
by simpa [nnreal.coe_le] using dist_triangle_left x y z
theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z :=
by simpa [nnreal.coe_le] using dist_triangle_right x y z
/--Express `dist` in terms of `edist`-/
lemma dist_edist (x y : α) : dist x y = (edist x y).to_real :=
by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)]
namespace metric
/- instantiate metric space as a topology -/
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
/-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/
def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl
/-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/
def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y, by simp; intros h; apply le_of_lt h
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : ε > 0 :=
lt_of_le_of_lt dist_nonneg hy
theorem mem_ball_self (h : ε > 0) : x ∈ ball x ε :=
show dist x x < ε, by rw dist_self; assumption
theorem mem_closed_ball_self (h : ε ≥ 0) : x ∈ closed_ball x ε :=
show dist x x ≤ ε, by rw dist_self; assumption
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [dist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (dist_triangle_left x y z)
(lt_of_lt_of_le (add_lt_add h₁ h₂) h)
theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ :=
ball_disjoint $ by rwa [← two_mul, ← le_div_iff' two_pos]
theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact
lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h)
theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε :=
ball_subset $ by rw sub_self_div_two; exact le_of_lt h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩
theorem ball_eq_empty_iff_nonpos : ε ≤ 0 ↔ ball x ε = ∅ :=
(eq_empty_iff_forall_not_mem.trans
⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0,
λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩).symm
theorem uniformity_dist : 𝓤 α = (⨅ ε>0, principal {p:α×α | dist p.1 p.2 < ε}) :=
metric_space.uniformity_dist _
theorem uniformity_dist' : 𝓤 α = (⨅ε:{ε:ℝ // ε>0}, principal {p:α×α | dist p.1 p.2 < ε.val}) :=
by simp [infi_subtype]; exact uniformity_dist
theorem mem_uniformity_dist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) :=
begin
rw [uniformity_dist', mem_infi],
simp [subset_def],
exact assume ⟨r, hr⟩ ⟨p, hp⟩, ⟨⟨min r p, lt_min hr hp⟩, by simp [lt_min_iff, (≥)] {contextual := tt}⟩,
exact ⟨⟨1, zero_lt_one⟩⟩
end
theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) :
{p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩
theorem uniform_continuous_iff [metric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε :=
uniform_continuous_def.trans
⟨λ H ε ε0, mem_uniformity_dist.1 $ H _ $ dist_mem_uniformity ε0,
λ H r ru,
let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨δ, δ0, hδ⟩ := H _ ε0 in
mem_uniformity_dist.2 ⟨δ, δ0, λ a b h, hε (hδ h)⟩⟩
theorem uniform_embedding_iff [metric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (dist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
/-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the
space from finitely many data. -/
lemma totally_bounded_of_finite_discretization {α : Type u} [metric_space α] {s : set α}
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β),
∀x y, F x = F y → dist (x:α) y < ε) :
totally_bounded s :=
begin
classical, by_cases hs : s = ∅,
{ rw hs, exact totally_bounded_empty },
rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩,
haveI : inhabited s := ⟨⟨x0, hx0⟩⟩,
refine totally_bounded_iff.2 (λ ε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩,
let x' := Finv (F ⟨x, xs⟩),
have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩,
simp only [set.mem_Union, set.mem_range],
exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩
end
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε :=
cauchy_iff.trans $ and_congr iff.rfl
⟨λ H ε ε0, let ⟨t, tf, ts⟩ := H _ (dist_mem_uniformity ε0) in
⟨t, tf, λ x y xt yt, @ts (x, y) ⟨xt, yt⟩⟩,
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru,
⟨t, tf, h⟩ := H ε ε0 in
⟨t, tf, λ ⟨x, y⟩ ⟨hx, hy⟩, hε (h x y hx hy)⟩⟩
theorem nhds_eq : nhds x = (⨅ε:{ε:ℝ // ε>0}, principal (ball x ε.val)) :=
begin
rw [nhds_eq_uniformity, uniformity_dist', lift'_infi],
{ apply congr_arg, funext ε,
rw [lift'_principal],
{ simp [ball, dist_comm] },
{ exact monotone_preimage } },
{ exact ⟨⟨1, zero_lt_one⟩⟩ },
{ intros, refl }
end
theorem mem_nhds_iff : s ∈ nhds x ↔ ∃ε>0, ball x ε ⊆ s :=
begin
rw [nhds_eq, mem_infi],
{ simp },
{ intros y z, cases y with y hy, cases z with z hz,
refine ⟨⟨min y z, lt_min hy hz⟩, _⟩,
simp [ball_subset_ball, min_le_left, min_le_right, (≥)] },
{ exact ⟨⟨1, zero_lt_one⟩⟩ }
end
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ nhds x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} :
tendsto f (nhds a) (nhds b) ↔
∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε :=
⟨λ H ε ε0, mem_nhds_iff.1 (H (ball_mem_nhds _ ε0)),
λ H s hs,
let ⟨ε, ε0, hε⟩ := mem_nhds_iff.1 hs, ⟨δ, δ0, hδ⟩ := H _ ε0 in
mem_nhds_iff.2 ⟨δ, δ0, λ x h, hε (hδ h)⟩⟩
theorem continuous_iff [metric_space β] {f : α → β} :
continuous f ↔
∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds
theorem exists_delta_of_continuous [metric_space β] {f : α → β} {ε : ℝ}
(hf : continuous f) (hε : ε > 0) (b : α) :
∃ δ > 0, ∀a, dist a b ≤ δ → dist (f a) (f b) < ε :=
let ⟨δ, δ_pos, hδ⟩ := continuous_iff.1 hf b ε hε in
⟨δ / 2, half_pos δ_pos, assume a ha, hδ a $ lt_of_le_of_lt ha $ div_two_lt_of_pos δ_pos⟩
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (nhds a) ↔ ∀ ε > 0, ∃ n ∈ f, ∀x ∈ n, dist (u x) a < ε :=
by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_principal, mem_ball];
exact forall_congr (assume ε, forall_congr (assume hε, exists_sets_subset_iff.symm))
theorem continuous_iff' [topological_space β] {f : β → α} :
continuous f ↔ ∀a (ε > 0), ∃ n ∈ nhds a, ∀b ∈ n, dist (f b) (f a) < ε :=
continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds
theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} :
tendsto u at_top (nhds a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε :=
by simp only [metric.nhds_eq, tendsto_infi, subtype.forall, tendsto_at_top_principal]; refl
end metric
open metric
instance metric_space.to_separated : separated α :=
separated_def.2 $ λ x y h, eq_of_forall_dist_le $
λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0))
/-Instantiate a metric space as an emetric space. Before we can state the instance,
we need to show that the uniform structure coming from the edistance and the
distance coincide. -/
/-- Expressing the uniformity in terms of `edist` -/
protected lemma metric.mem_uniformity_edist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
begin
refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩,
{ refine ⟨ennreal.of_real ε, _, λ a b, _⟩,
{ rwa [gt, ennreal.of_real_pos] },
{ rw [edist_dist, ennreal.of_real_lt_of_real_iff ε0],
exact Hε } },
{ rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩,
rw [ennreal.of_real_pos] at ε0',
refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩,
rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] }
end
protected theorem metric.uniformity_edist' : 𝓤 α = (⨅ε:{ε:ennreal // ε>0}, principal {p:α×α | edist p.1 p.2 < ε.val}) :=
begin
ext s, rw mem_infi,
{ simp [metric.mem_uniformity_edist, subset_def] },
{ rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩,
simp [lt_min_iff, (≥)] {contextual := tt} },
{ exact ⟨⟨1, ennreal.zero_lt_one⟩⟩ }
end
theorem uniformity_edist : 𝓤 α = (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}) :=
by simpa [infi_subtype] using @metric.uniformity_edist' α _
/-- A metric space induces an emetric space -/
instance metric_space.to_emetric_space : emetric_space α :=
{ edist := edist,
edist_self := by simp [edist_dist],
eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h,
edist_comm := by simp only [edist_dist, dist_comm]; simp,
edist_triangle := assume x y z, begin
simp only [edist_dist, (ennreal.of_real_add _ _).symm, dist_nonneg],
rw ennreal.of_real_le_of_real_iff _,
{ exact dist_triangle _ _ _ },
{ simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg }
end,
uniformity_edist := uniformity_edist,
..‹metric_space α› }
/-- Balls defined using the distance or the edistance coincide -/
lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε :=
begin
classical, by_cases h : 0 < ε,
{ ext y, by simp [edist_dist, ennreal.of_real_lt_of_real_iff h] },
{ have h' : ε ≤ 0, by simpa using h,
have A : ball x ε = ∅, by simpa [ball_eq_empty_iff_nonpos.symm],
have B : emetric.ball x (ennreal.of_real ε) = ∅,
by simp [ennreal.of_real_eq_zero.2 h', emetric.ball_eq_empty_iff],
rwa [A, B] }
end
/-- Closed balls defined using the distance or the edistance coincide -/
lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) :
emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε :=
by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h
def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α)
(H : @uniformity _ U = @uniformity _ (metric_space.to_uniform_space α)) :
metric_space α :=
{ dist := @dist _ m.to_has_dist,
dist_self := dist_self,
eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _,
dist_comm := dist_comm,
dist_triangle := dist_triangle,
edist := edist,
edist_dist := edist_dist,
to_uniform_space := U,
uniformity_dist := H.trans (metric_space.uniformity_dist α) }
/-- One gets a metric space from an emetric space if the edistance
is everywhere finite. We set it up so that the edist and the uniformity are
defeq in the metric space and the emetric space -/
def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) :
metric_space α :=
let m : metric_space α :=
{ dist := λx y, ennreal.to_real (edist x y),
eq_of_dist_eq_zero := λx y hxy, by simpa [dist, ennreal.to_real_eq_zero_iff, h x y] using hxy,
dist_self := λx, by simp,
dist_comm := λx y, by simp [emetric_space.edist_comm],
dist_triangle := λx y z, begin
rw [← ennreal.to_real_add (h _ _) (h _ _), ennreal.to_real_le_to_real (h _ _)],
{ exact edist_triangle _ _ _ },
{ simp [ennreal.add_eq_top, h] }
end,
edist := λx y, edist x y,
edist_dist := λx y, by simp [ennreal.of_real_to_real, h] } in
metric_space.replace_uniformity m (by rw [uniformity_edist, uniformity_edist']; refl)
section real
/-- Instantiate the reals as a metric space. -/
instance real.metric_space : metric_space ℝ :=
{ dist := λx y, abs (x - y),
dist_self := by simp [abs_zero],
eq_of_dist_eq_zero := by simp [add_neg_eq_zero],
dist_comm := assume x y, abs_sub _ _,
dist_triangle := assume x y z, abs_sub_le _ _ _ }
theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl
theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x :=
by simp [real.dist_eq]
instance : orderable_topology ℝ :=
orderable_topology_of_nhds_abs $ λ x, begin
simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r,
by simp [-sub_eq_add_neg, abs_sub, ball, real.dist_eq]],
apply le_antisymm,
{ simp [le_infi_iff],
exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) },
{ intros s h,
rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩,
exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) },
end
lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) :=
by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq,
abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le]
lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t)
(g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) :=
begin
apply tendsto_of_tendsto_of_tendsto_of_le_of_le (tendsto_const_nhds) g0;
simp [*]; exact filter.univ_mem_sets
end
theorem metric.uniformity_eq_comap_nhds_zero :
𝓤 α = comap (λp:α×α, dist p.1 p.2) (nhds (0 : ℝ)) :=
begin
simp only [uniformity_dist', nhds_eq, comap_infi, comap_principal],
congr, funext ε,
rw [principal_eq_iff_eq],
ext ⟨a, b⟩,
simp [real.dist_0_eq_abs]
end
lemma cauchy_seq_iff_tendsto_dist_at_top_0 [inhabited β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (nhds 0) :=
by rw [cauchy_seq_iff_prod_map, metric.uniformity_eq_comap_nhds_zero, ← map_le_iff_le_comap,
filter.map_map, tendsto, prod.map_def]
end real
section cauchy_seq
variables [inhabited β] [semilattice_sup β]
/-- In a metric space, Cauchy sequences are characterized by the fact that, eventually,
the distance between its elements is arbitrarily small -/
theorem metric.cauchy_seq_iff {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε :=
begin
unfold cauchy_seq,
rw metric.cauchy_iff,
simp only [true_and, exists_prop, filter.mem_at_top_sets, filter.at_top_ne_bot,
filter.mem_map, ne.def, filter.map_eq_bot_iff, not_false_iff, set.mem_set_of_eq],
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨t, ⟨N, hN⟩, ht⟩,
exact ⟨N, λm n hm hn, ht _ _ (hN _ hm) (hN _ hn)⟩ },
{ intros H ε εpos,
rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩,
existsi ball (u N) (ε/2),
split,
{ exact ⟨N, λx hx, hN _ _ hx (le_refl N)⟩ },
{ exact λx y hx hy, calc
dist x y ≤ dist x (u N) + dist y (u N) : dist_triangle_right _ _ _
... < ε/2 + ε/2 : add_lt_add hx hy
... = ε : add_halves _ } }
end
/-- A variation around the metric characterization of Cauchy sequences -/
theorem metric.cauchy_seq_iff' {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε :=
begin
rw metric.cauchy_seq_iff,
split,
{ intros H ε εpos,
rcases H ε εpos with ⟨N, hN⟩,
exact ⟨N, λn hn, hN _ _ hn (le_refl N)⟩ },
{ intros H ε εpos,
rcases H (ε/2) (half_pos εpos) with ⟨N, hN⟩,
exact ⟨N, λ m n hm hn, calc
dist (u m) (u n) ≤ dist (u m) (u N) + dist (u n) (u N) : dist_triangle_right _ _ _
... < ε/2 + ε/2 : add_lt_add (hN _ hm) (hN _ hn)
... = ε : add_halves _⟩ }
end
/-- A Cauchy sequence on the natural numbers is bounded. -/
theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) :
∃ R > 0, ∀ m n, dist (u m) (u n) < R :=
begin
rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩,
suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R,
{ rcases this with ⟨R, R0, H⟩,
exact ⟨_, add_pos R0 R0, λ m n,
lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ },
let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)),
refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩,
cases le_or_lt N n,
{ exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) },
{ have : _ ≤ R := finset.le_sup (finset.mem_range.2 h),
exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) }
end
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ,
(∀ n, 0 ≤ b n) ∧
(∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧
tendsto b at_top (nhds 0) :=
⟨λ hs, begin
/- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking
the supremum of the distances between `s n` and `s m` for `n m ≥ N`.
First, we prove that all these distances are bounded, as otherwise the Sup
would not make sense. -/
let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N},
have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x,
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩,
exact le_of_lt (hR m n) },
have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))),
{ rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩,
use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) },
-- Prove that it bounds the distances of points in the Cauchy sequence
have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ real.Sup (S N) :=
λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩,
have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩,
have S0 := λ n, real.le_Sup _ (hS n) (S0m n),
-- Prove that it tends to `0`, by using the Cauchy property of `s`
refine ⟨λ N, real.Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩,
refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _),
rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)],
refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0),
rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩,
exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn'))
end,
λ ⟨b, _, b_bound, b_lim⟩, metric.cauchy_seq_iff.2 $ λ ε ε0,
(metric.tendsto_at_top.1 b_lim ε ε0).imp $ λ N hN m n hm hn,
calc dist (s m) (s n) ≤ b N : b_bound m n N hm hn
... ≤ abs (b N) : le_abs_self _
... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl
... < ε : (hN _ (le_refl N)) ⟩
end cauchy_seq
def metric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : metric_space β) : metric_space α :=
{ dist := λ x y, dist (f x) (f y),
dist_self := λ x, dist_self _,
eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h),
dist_comm := λ x y, dist_comm _ _,
dist_triangle := λ x y z, dist_triangle _ _ _,
edist := λ x y, edist (f x) (f y),
edist_dist := λ x y, edist_dist _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_dist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
instance subtype.metric_space {p : α → Prop} [t : metric_space α] : metric_space (subtype p) :=
metric_space.induced subtype.val (λ x y, subtype.eq) t
theorem subtype.dist_eq {p : α → Prop} [t : metric_space α] (x y : subtype p) :
dist x y = dist x.1 y.1 := rfl
section nnreal
instance : metric_space nnreal := by unfold nnreal; apply_instance
end nnreal
section prod
instance prod.metric_space_max [metric_space β] : metric_space (α × β) :=
{ dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2),
dist_self := λ x, by simp,
eq_of_dist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩
end,
dist_comm := λ x y, by simp [dist_comm],
dist_triangle := λ x y z, max_le
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _)))
(le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))),
edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_dist := assume x y, begin
have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h,
rw [edist_dist, edist_dist, (max_distrib_of_monotone this).symm]
end,
uniformity_dist := begin
refine uniformity_prod.trans _,
simp [uniformity_dist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.dist_eq [metric_space β] {x y : α × β} :
dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl
end prod
theorem uniform_continuous_dist' : uniform_continuous (λp:α×α, dist p.1 p.2) :=
metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0,
begin
suffices,
{ intros p q h, cases p with p₁ p₂, cases q with q₁ q₂,
cases max_lt_iff.1 h with h₁ h₂, clear h,
dsimp at h₁ h₂ ⊢,
rw real.dist_eq,
refine abs_sub_lt_iff.2 ⟨_, _⟩,
{ revert p₁ p₂ q₁ q₂ h₁ h₂, exact this },
{ apply this; rwa dist_comm } },
intros p₁ p₂ q₁ q₂ h₁ h₂,
have := add_lt_add
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1
(abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1,
rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this
end⟩)
theorem uniform_continuous_dist [uniform_space β] {f g : β → α}
(hf : uniform_continuous f) (hg : uniform_continuous g) :
uniform_continuous (λb, dist (f b) (g b)) :=
(hf.prod_mk hg).comp uniform_continuous_dist'
theorem continuous_dist' : continuous (λp:α×α, dist p.1 p.2) :=
uniform_continuous_dist'.continuous
theorem continuous_dist [topological_space β] {f g : β → α}
(hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) :=
continuous_dist'.comp (hf.prod_mk hg)
theorem tendsto_dist {f g : β → α} {x : filter β} {a b : α}
(hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) :
tendsto (λx, dist (f x) (g x)) x (nhds (dist a b)) :=
have tendsto (λp:α×α, dist p.1 p.2) (nhds (a, b)) (nhds (dist a b)),
from continuous_iff_continuous_at.mp continuous_dist' (a, b),
(hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this)
lemma nhds_comap_dist (a : α) : (nhds (0 : ℝ)).comap (λa', dist a' a) = nhds a :=
have h₁ : ∀ε, (λa', dist a' a) ⁻¹' ball 0 ε ⊆ ball a ε,
by simp [subset_def, real.dist_0_eq_abs],
have h₂ : tendsto (λa', dist a' a) (nhds a) (nhds (dist a a)),
from tendsto_dist tendsto_id tendsto_const_nhds,
le_antisymm
(by simp [h₁, nhds_eq, infi_le_infi, principal_mono,
-le_principal_iff, -le_infi_iff])
(by simpa [map_le_iff_le_comap.symm, tendsto] using h₂)
lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} :
(tendsto f x (nhds a)) ↔ (tendsto (λb, dist (f b) a) x (nhds 0)) :=
by rw [← nhds_comap_dist a, tendsto_comap_iff]
lemma uniform_continuous_nndist' : uniform_continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_subtype_mk uniform_continuous_dist' _
lemma continuous_nndist' : continuous (λp:α×α, nndist p.1 p.2) :=
uniform_continuous_nndist'.continuous
lemma tendsto_nndist' (a b :α) :
tendsto (λp:α×α, nndist p.1 p.2) (filter.prod (nhds a) (nhds b)) (nhds (nndist a b)) :=
by rw [← nhds_prod_eq]; exact continuous_iff_continuous_at.1 continuous_nndist' _
namespace metric
variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α}
theorem is_closed_ball : is_closed (closed_ball x ε) :=
is_closed_le (continuous_dist continuous_id continuous_const) continuous_const
/-- ε-characterization of the closure in metric spaces-/
theorem mem_closure_iff' {α : Type u} [metric_space α] {s : set α} {a : α} :
a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
⟨begin
intros ha ε hε,
have A : ball a ε ∩ s ≠ ∅ := mem_closure_iff.1 ha _ is_open_ball (mem_ball_self hε),
cases ne_empty_iff_exists_mem.1 A with b hb,
simp,
exact ⟨b, ⟨hb.2, by have B := hb.1; simpa [mem_ball'] using B⟩⟩
end,
begin
intros H,
apply mem_closure_iff.2,
intros o ho ao,
rcases is_open_iff.1 ho a ao with ⟨ε, ⟨εpos, hε⟩⟩,
rcases H ε εpos with ⟨b, ⟨bs, bdist⟩⟩,
have B : b ∈ o ∩ s := ⟨hε (by simpa [dist_comm]), bs⟩,
apply ne_empty_of_mem B
end⟩
theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s)
{a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε :=
by simpa only [closure_eq_of_is_closed hs] using @mem_closure_iff' _ _ s a
end metric
section pi
open finset lattice
variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)]
instance has_dist_pi : has_dist (Πb, π b) :=
⟨λf g, ((finset.sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)⟩
lemma dist_pi_def (f g : Πb, π b) :
dist f g = (finset.sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl
instance metric_space_pi : metric_space (Πb, π b) :=
{ dist := dist,
dist_self := assume f, (nnreal.coe_eq_zero _).2 $ bot_unique $ finset.sup_le $ by simp,
dist_comm := assume f g, nnreal.eq_iff.2 $ by congr; ext a; exact nndist_comm _ _,
dist_triangle := assume f g h, show dist f h ≤ (dist f g) + (dist g h), from
begin
simp only [dist_pi_def, (nnreal.coe_add _ _).symm, nnreal.coe_le.symm,
finset.sup_le_iff],
assume b hb,
exact le_trans (nndist_triangle _ (g b) _) (add_le_add (le_sup hb) (le_sup hb))
end,
eq_of_dist_eq_zero := assume f g eq0,
begin
simp only [dist_pi_def, nnreal.coe_eq_zero, nnreal.bot_eq_zero.symm, eq_bot_iff,
finset.sup_le_iff] at eq0,
exact (funext $ assume b, eq_of_nndist_eq_zero $ bot_unique $ eq0 b $ mem_univ b),
end,
edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_dist := assume x y, begin
have A : sup univ (λ (b : β), ((nndist (x b) (y b)) : ennreal)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))),
{ refine eq.symm (comp_sup_eq_sup_comp _ _ _),
exact (assume x y h, ennreal.coe_le_coe.2 h), refl },
simp [dist, edist_nndist, ennreal.of_real, A]
end }
end pi
section compact
/-- Any compact set in a metric space can be covered by finitely many balls of a given positive
radius -/
lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α}
(hs : compact s) {e : ℝ} (he : e > 0) :
∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e :=
begin
apply compact_elim_finite_subcover_image hs,
{ simp [is_open_ball] },
{ intros x xs,
simp,
exact ⟨x, ⟨xs, by simpa⟩⟩ }
end
end compact
section proper_space
open metric
/-- A metric space is proper if all closed balls are compact. -/
class proper_space (α : Type u) [metric_space α] : Prop :=
(compact_ball : ∀x:α, ∀r, compact (closed_ball x r))
/- A compact metric space is proper -/
instance proper_of_compact [metric_space α] [compact_space α] : proper_space α :=
⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩
/-- A proper space is locally compact -/
instance locally_compact_of_proper [metric_space α] [proper_space α] :
locally_compact_space α :=
begin
apply locally_compact_of_compact_nhds,
intros x,
existsi closed_ball x 1,
split,
{ apply mem_nhds_iff.2,
existsi (1 : ℝ),
simp,
exact ⟨zero_lt_one, ball_subset_closed_ball⟩ },
{ apply proper_space.compact_ball }
end
/-- A proper space is complete -/
instance complete_of_proper {α : Type u} [metric_space α] [proper_space α] : complete_space α :=
⟨begin
intros f hf,
/- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed
ball (therefore compact by properness) where it is nontrivial. -/
have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one,
rcases A with ⟨t, ⟨t_fset, ht⟩⟩,
rcases inhabited_of_mem_sets hf.1 t_fset with ⟨x, xt⟩,
have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt),
have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this,
rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this)
with ⟨y, _, hy⟩,
exact ⟨y, hy⟩
end⟩
/-- A proper metric space is separable, and therefore second countable. Indeed, any ball is
compact, and therefore admits a countable dense subset. Taking a countable union over the balls
centered at a fixed point and with integer radius, one obtains a countable set which is
dense in the whole space. -/
instance second_countable_of_proper [metric_space α] [proper_space α] :
second_countable_topology α :=
begin
/- We show that the space admits a countable dense subset. The case where the space is empty
is special, and trivial. -/
have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩,
have B : (univ : set α) ≠ ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) :=
begin
/- When the space is not empty, we take a point `x` in the space, and then a countable set
`T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set
`t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union
of countable sets, and dense in the space by construction. -/
assume non_empty,
rcases ne_empty_iff_exists_mem.1 non_empty with ⟨x, x_univ⟩,
choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t),
from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _),
let t := (⋃n:ℕ, T (n : ℝ)),
have T₁ : countable t := by finish [countable_Union],
have T₂ : closure t ⊆ univ := by simp,
have T₃ : univ ⊆ closure t :=
begin
intros y y_univ,
rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩,
have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large,
have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish,
have : y ∈ closure (T (n : ℝ)) := by rwa h' at h,
show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))),
end,
exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩
end,
haveI : separable_space α := ⟨by_cases A B⟩,
apply emetric.second_countable_of_separable,
end
end proper_space
namespace metric
section second_countable
open topological_space
/-- A metric space is second countable if, for every ε > 0, there is a countable set which is ε-dense. -/
lemma second_countable_of_almost_dense_set
(H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) :
second_countable_topology α :=
begin
choose T T_dense using H,
have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 :=
λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)),
have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos'.2 (I1 n),
let t := ⋃n:ℕ, T (n+1)⁻¹ (I n),
have count_t : countable t := by finish [countable_Union],
have clos_t : closure t = univ,
{ refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff'.2 (λε εpos, _)),
rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩,
have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one),
have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this,
rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩,
have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))),
exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ },
haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩,
exact emetric.second_countable_of_separable α
end
/-- A metric space space is second countable if one can reconstruct up to any ε>0 any element of the
space from countably many data. -/
lemma second_countable_of_countable_discretization {α : Type u} [metric_space α]
(H : ∀ε > (0 : ℝ), ∃ (β : Type u) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) :
second_countable_topology α :=
begin
classical, by_cases hs : (univ : set α) = ∅,
{ haveI : compact_space α := ⟨by rw hs; exact compact_of_finite (set.finite_empty)⟩, by apply_instance },
rcases exists_mem_of_ne_empty hs with ⟨x0, hx0⟩,
letI : inhabited α := ⟨x0⟩,
refine second_countable_of_almost_dense_set (λε ε0, _),
rcases H ε ε0 with ⟨β, fβ, F, hF⟩,
let Finv := function.inv_fun F,
refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩,
let x' := Finv (F x),
have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩,
exact ⟨x', mem_range_self _, hF _ _ this.symm⟩
end
end second_countable
end metric
lemma lebesgue_number_lemma_of_metric
{s : set α} {ι} {c : ι → set α} (hs : compact s)
(hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) :
∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i :=
let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂,
⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in
⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in
⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩
lemma lebesgue_number_lemma_of_metric_sUnion
{s : set α} {c : set (set α)} (hs : compact s)
(hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) :
∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t :=
by rw sUnion_eq_Union at hc₂;
simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂
namespace metric
/-- Boundedness of a subset of a metric space. We formulate the definition to work
even in the empty space. -/
def bounded (s : set α) : Prop :=
∃C, ∀x y ∈ s, dist x y ≤ C
section bounded
variables {x : α} {s t : set α} {r : ℝ}
@[simp] lemma bounded_empty : bounded (∅ : set α) :=
⟨0, by simp⟩
lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s :=
⟨λ h _ _, h, λ H, begin
classical, by_cases s = ∅,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
exact H x hx }
end⟩
/-- Subsets of a bounded set are also bounded -/
lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s :=
Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy)
/-- Closed balls are bounded -/
lemma bounded_closed_ball : bounded (closed_ball x r) :=
⟨r + r, λ y z hy hz, begin
simp only [mem_closed_ball] at *,
calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add hy hz
end⟩
/-- Open balls are bounded -/
lemma bounded_ball : bounded (ball x r) :=
bounded_closed_ball.subset ball_subset_closed_ball
/-- Given a point, a bounded subset is included in some ball around this point -/
lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r :=
begin
split; rintro ⟨C, hC⟩,
{ classical, by_cases s = ∅,
{ subst s, exact ⟨0, by simp⟩ },
{ rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
exact ⟨C + dist x c, λ y hy, calc
dist y c ≤ dist y x + dist x c : dist_triangle _ _ _
... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } },
{ exact bounded_closed_ball.subset hC }
end
/-- The union of two bounded sets is bounded iff each of the sets is bounded -/
@[simp] lemma bounded_union :
bounded (s ∪ t) ↔ bounded s ∧ bounded t :=
⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩,
begin
rintro ⟨hs, ht⟩,
refine bounded_iff_mem_bounded.2 (λ x _, _),
rw bounded_iff_subset_ball x at hs ht ⊢,
rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩,
exact ⟨max Cs Ct, union_subset
(subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _)
(subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩,
end⟩
/-- A finite union of bounded sets is bounded -/
lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) :
bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) :=
finite.induction_on H (by simp) $ λ x I _ _ IH,
by simp [or_imp_distrib, forall_and_distrib, IH]
/-- A compact set is bounded -/
lemma bounded_of_compact {s : set α} (h : compact s) : bounded s :=
-- We cover the compact set by finitely many balls of radius 1,
-- and then argue that a finite union of bounded sets is bounded
let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in
bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball
/-- A finite set is bounded -/
lemma bounded_of_finite {s : set α} (h : finite s) : bounded s :=
bounded_of_compact $ compact_of_finite h
/-- A singleton is bounded -/
lemma bounded_singleton {x : α} : bounded ({x} : set α) :=
bounded_of_finite $ finite_singleton _
/-- Characterization of the boundedness of the range of a function -/
lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C :=
exists_congr $ λ C, ⟨
λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩,
by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩
/-- In a compact space, all sets are bounded -/
lemma bounded_of_compact_space [compact_space α] : bounded s :=
(bounded_of_compact compact_univ).subset (subset_univ _)
/-- In a proper space, a set is compact if and only if it is closed and bounded -/
lemma compact_iff_closed_bounded [proper_space α] :
compact s ↔ is_closed s ∧ bounded s :=
⟨λ h, ⟨closed_of_compact _ h, bounded_of_compact h⟩, begin
rintro ⟨hc, hb⟩,
classical, by_cases s = ∅, {simp [h, compact_empty]},
rcases exists_mem_of_ne_empty h with ⟨x, hx⟩,
rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩,
exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr
end⟩
end bounded
section diam
variables {s : set α} {x y : α}
/-- The diameter of a set in a metric space. To get controllable behavior even when the diameter
should be infinite, we express it in terms of the emetric.diameter -/
def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s)
/-- The diameter of a set is always nonnegative -/
lemma diam_nonneg : 0 ≤ diam s :=
by simp [diam]
/-- The empty set has zero diameter -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
by simp [diam]
/-- A singleton has zero diameter -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
by simp [diam]
/-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/
lemma bounded_iff_diam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ :=
begin
classical, by_cases hs : s = ∅,
{ simp [hs] },
{ rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hx⟩,
split,
{ assume bs,
rcases (bounded_iff_subset_ball x).1 bs with ⟨r, hr⟩,
have r0 : 0 ≤ r := by simpa [closed_ball] using hr hx,
have : emetric.diam s < ⊤ := calc
emetric.diam s ≤ emetric.diam (emetric.closed_ball x (ennreal.of_real r)) :
by rw emetric_closed_ball r0; exact emetric.diam_mono hr
... ≤ 2 * (ennreal.of_real r) : emetric.diam_closed_ball
... < ⊤ : begin apply ennreal.lt_top_iff_ne_top.2, simp [ennreal.mul_eq_top], end,
exact ennreal.lt_top_iff_ne_top.1 this },
{ assume ds,
have : s ⊆ closed_ball x (ennreal.to_real (emetric.diam s)),
{ rw [← emetric_closed_ball ennreal.to_real_nonneg, ennreal.of_real_to_real ds],
exact λy hy, emetric.edist_le_diam_of_mem hy hx },
exact bounded.subset this (bounded_closed_ball) }}
end
/-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`.
This lemma makes it possible to avoid side conditions in some situations -/
lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 :=
begin
simp only [bounded_iff_diam_ne_top, not_not, ne.def] at h,
simp [diam, h]
end
/-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/
lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t :=
begin
unfold diam,
rw ennreal.to_real_le_to_real (bounded_iff_diam_ne_top.1 (bounded.subset h ht)) (bounded_iff_diam_ne_top.1 ht),
exact emetric.diam_mono h
end
/-- The distance between two points in a set is controlled by the diameter of the set. -/
lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s :=
begin
rw [diam, dist_edist],
rw ennreal.to_real_le_to_real (edist_ne_top _ _) (bounded_iff_diam_ne_top.1 h),
exact emetric.edist_le_diam_of_mem hx hy
end
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le_of_forall_dist_le {d : real} (hd : d ≥ 0) (h : ∀x y ∈ s, dist x y ≤ d) : diam s ≤ d :=
begin
have I : emetric.diam s ≤ ennreal.of_real d,
{ refine emetric.diam_le_of_forall_edist_le (λx y hx hy, _),
rw [edist_dist],
exact ennreal.of_real_le_of_real (h x y hx hy) },
have A : emetric.diam s ≠ ⊤ :=
ennreal.lt_top_iff_ne_top.1 (lt_of_le_of_lt I (ennreal.lt_top_iff_ne_top.2 (by simp))),
rw [← ennreal.to_real_of_real hd, diam, ennreal.to_real_le_to_real A],
{ exact I },
{ simp }
end
/-- The diameter of a union is controlled by the sum of the diameters, and the distance between
any two points in each of the sets. This lemma is true without any side condition, since it is
obviously true if `s ∪ t` is unbounded. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t :=
have I1 : ¬(bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh, calc
diam (s ∪ t) = 0 + 0 + 0 : by simp [diam_eq_zero_of_unbounded h]
... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg,
have I2 : (bounded (s ∪ t)) → diam (s ∪ t) ≤ diam s + dist x y + diam t := λh,
begin
have : bounded s := bounded.subset (subset_union_left _ _) h,
have : bounded t := bounded.subset (subset_union_right _ _) h,
have A : ∀a ∈ s, ∀b ∈ t, dist a b ≤ diam s + dist x y + diam t := λa ha b hb, calc
dist a b ≤ dist a x + dist x y + dist y b : dist_triangle4 _ _ _ _
... ≤ diam s + dist x y + diam t :
add_le_add (add_le_add (dist_le_diam_of_mem ‹bounded s› ha xs) (le_refl _)) (dist_le_diam_of_mem ‹bounded t› yt hb),
have B : ∀a b ∈ s ∪ t, dist a b ≤ diam s + dist x y + diam t := λa b ha hb,
begin
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc dist a b ≤ diam s : dist_le_diam_of_mem ‹bounded s› h'a h'b
... = diam s + (0 + 0) : by simp
... ≤ diam s + (dist x y + diam t) : add_le_add (le_refl _) (add_le_add dist_nonneg diam_nonneg)
... = diam s + dist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [dist_comm] at Z },
{ calc dist a b ≤ diam t : dist_le_diam_of_mem ‹bounded t› h'a h'b
... = (0 + 0) + diam t : by simp
... ≤ (diam s + dist x y) + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) (le_refl _) }
end,
have C : 0 ≤ diam s + dist x y + diam t := calc
0 = 0 + 0 + 0 : by simp
... ≤ diam s + dist x y + diam t : add_le_add (add_le_add diam_nonneg dist_nonneg) diam_nonneg,
exact diam_le_of_forall_dist_le C B
end,
classical.by_cases I2 I1
/-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/
lemma diam_union' {t : set α} (h : s ∩ t ≠ ∅) : diam (s ∪ t) ≤ diam s + diam t :=
begin
rcases ne_empty_iff_exists_mem.1 h with ⟨x, ⟨xs, xt⟩⟩,
simpa using diam_union xs xt
end
/-- The diameter of a closed ball of radius `r` is at most `2 r`. -/
lemma diam_closed_ball {r : ℝ} (h : r ≥ 0) : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_dist_le (mul_nonneg (by norm_num) h) $ λa b ha hb, calc
dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _
... ≤ r + r : add_le_add ha hb
... = 2 * r : by simp [mul_two, mul_comm]
/-- The diameter of a ball of radius `r` is at most `2 r`. -/
lemma diam_ball {r : ℝ} (h : r ≥ 0) : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h)
end diam
end metric
|
827bea7de65be384c5b585b864da52fa2c1ce2a8 | 13d50f9487a2afddb5e1ae1bbe68f7870f70e79a | /OldRecursor.lean | fd67cd3bf7890d244c743ca09f3bc300bd877129 | [] | no_license | gebner/lean4-mathlib-import | 09a09d9cc30738bcc253e919ab3485e13b8f992d | 719c0558dfa9c4ec201aa40f4786d5f1c1e4bd1e | refs/heads/master | 1,649,553,984,859 | 1,584,121,837,000 | 1,584,121,837,000 | 238,557,672 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,263 | lean | import Init.Lean
-- import Import.ExportParser
open Lean Lean.Meta
namespace Array
def take {α} (xs : Array α) (i : Nat) : Array α :=
(xs.toList.take i).toArray
def splitAt {α} (xs : Array α) (i : Nat) : Array α × Array α :=
((xs.toList.take i).toArray, (xs.toList.drop i).toArray)
end Array
namespace Lean
-- #print Or.rec
-- def Or.ndrec : ∀ {a b C : Prop}, (a → C) → (b → C) → a ∨ b → C :=
-- fun a b C => @Or.rec a b (fun _ => C)
-- inductive less_than_or_equal (a : Nat) : Nat → Prop
-- | refl : less_than_or_equal a
-- | step : ∀ {b}, less_than_or_equal b → less_than_or_equal (Nat.succ b)
-- #print less_than_or_equal.rec
-- def less_than_or_equal.ndrec : ∀ {a : Nat} {C : Nat → Prop},
-- C a →
-- (∀ {b : Nat}, less_than_or_equal a b → C b → C (Nat.succ b)) →
-- ∀ {a_1 : Nat}, less_than_or_equal a a_1 → C a_1 :=
-- fun a C => @less_than_or_equal.rec a (fun a _ => C a)
def mkOldRecursor (indTy : Name) : MetaM (Option Declaration) := do
some (ConstantInfo.inductInfo indI) ← getConst indTy |
panic! (toString indTy);
indTy' ← inferType (mkConst indI.name (indI.lparams.map mkLevelParam));
forallTelescopeReducing indTy' $ fun _ indSort => do
Expr.sort level _ ← pure indSort | panic! (toString indSort);
let useDepElim := level.normalize != levelZero;
if useDepElim then pure none else some <$> do
some (ConstantInfo.recInfo recI) ← getConst (indTy ++ "rec") |
panic! (toString $ indTy ++ "rec");
let rec := mkConst recI.name (recI.lparams.map mkLevelParam);
recTy ← inferType rec;
forallTelescopeReducing recTy $ fun args _ => do
-- Meta.dbgTrace args;
let (params, args) := args.splitAt recI.nparams;
let (motive, args) := args.splitAt 1;
let motive := motive.get! 0;
motiveTy ← inferType motive;
forallTelescopeReducing motiveTy $ fun _ elimSort => do
Expr.sort elimLevel _ ← pure elimSort | panic! (toString elimSort);
let (minorPremises, args) := args.splitAt recI.nminors;
let (indices, major) := args.splitAt recI.nindices;
let majorPremise := major.get! 0;
-- Meta.dbgTrace (params, motive, indices, minorPremises, majorPremise);
oldMotiveTy ← Meta.mkForall indices (mkSort elimLevel);
withLocalDecl `C oldMotiveTy BinderInfo.implicit $ fun oldMotive => do
newMotive ← Meta.mkLambda (indices.push majorPremise) (mkAppN oldMotive indices);
val ← Meta.mkLambda ((params).push oldMotive) $ mkAppN rec ((params).push newMotive);
-- Meta.dbgTrace val;
ty ← inferType val;
-- Meta.dbgTrace ty;
pure $ Declaration.defnDecl {
name := indTy ++ "meinNdRec",
lparams := recI.lparams,
type := ty,
value := val,
isUnsafe := false,
hints := ReducibilityHints.regular 0,
}
-- #eval do mkOldRecursor `Eq; pure ()
-- #print Eq.rec
-- #print prefix Eq
-- let (params, indices) := paramsIndices.splitAt indI.nparams;
-- let useDepElim := !level.normalize.isZero;
-- if useDepElim then pure none else some <$> do
-- let elimIntoProp := true; -- FIXME
-- elimLevel ← if elimIntoProp then pure levelZero else mkLevelParam <$> mkFreshId;
-- oldMotiveTy ← Meta.mkForall params (mkSort elimLevel);
-- withLocalDecl `C oldMotiveTy BinderInfo.default $ fun oldMotive =>
-- #eval do Declaration.defnDecl v ← mkOldRecursor `Or | panic! "2"; pure v.type
end Lean
|
41c896d38bdbac5d23d0e687e6db2e07a32a1a0d | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Config/LeanExe.lean | 565861f35687c3ffae05399b20f9fe05157704ec | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,994 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Config.Module
namespace Lake
open Lean System
/-- A Lean executable -- its package plus its configuration. -/
structure LeanExe where
/-- The package the executable belongs to. -/
pkg : Package
/-- The executable's user-defined configuration. -/
config : LeanExeConfig
/-- The Lean executables of the package (as an Array). -/
@[inline] def Package.leanExes (self : Package) : Array LeanExe :=
self.leanExeConfigs.fold (fun a _ v => a.push (⟨self, v⟩)) #[]
/-- Try to find a Lean executable in the package with the given name. -/
@[inline] def Package.findLeanExe? (name : Name) (self : Package) : Option LeanExe :=
self.leanExeConfigs.find? name |>.map (⟨self, ·⟩)
/--
Converts the executable configuration into a library
with a single module (the root).
-/
def LeanExeConfig.toLeanLibConfig (self : LeanExeConfig) : LeanLibConfig where
name := self.name
srcDir := self.srcDir
roots := #[]
libName := self.exeName
extraDepTargets := self.extraDepTargets
nativeFacets := self.nativeFacets
toLeanConfig := self.toLeanConfig
namespace LeanExe
/-- The executable's well-formed name. -/
@[inline] def name (self : LeanExe) : Name :=
self.config.name
/-- Converts the executable into a library with a single module (the root). -/
@[inline] def toLeanLib (self : LeanExe) : LeanLib :=
⟨self.pkg, self.config.toLeanLibConfig⟩
/-- The executable's root module. -/
@[inline] def root (self : LeanExe) : Module where
lib := self.toLeanLib
name := self.config.root
keyName := self.pkg.name ++ self.config.root
/-- Return the the root module if the name matches, otherwise return none. -/
def isRoot? (name : Name) (self : LeanExe) : Option Module :=
if name == self.config.root then some self.root else none
/--
The file name of binary executable
(i.e., `exeName` plus the platform's `exeExtension`).
-/
@[inline] def fileName (self : LeanExe) : FilePath :=
FilePath.withExtension self.config.exeName FilePath.exeExtension
/-- The path to the executable in the package's `binDir`. -/
@[inline] def file (self : LeanExe) : FilePath :=
self.pkg.binDir / self.fileName
/--
The arguments to pass to `leanc` when linking the binary executable.
That is, `-rdynamic` (if non-Windows and `supportInterpreter`) plus the
package's and then the executable's `moreLinkArgs`.
-/
def linkArgs (self : LeanExe) : Array String :=
if self.config.supportInterpreter && !Platform.isWindows then
#["-rdynamic"] ++ self.pkg.moreLinkArgs ++ self.config.moreLinkArgs
else
self.pkg.moreLinkArgs ++ self.config.moreLinkArgs
end LeanExe
/-- Locate the named module in the package (if it is buildable and local to it). -/
def Package.findModule? (mod : Name) (self : Package) : Option Module :=
self.leanExes.findSome? (·.isRoot? mod) <|>
self.leanLibs.findSome? (·.findModule? mod)
|
d14cda2c9455c7ef7633056621a3ccad5087fc6d | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_geometry/Spec.lean | 05e1db2032b9528b6814badd35d0ec99b80b4ddb | [
"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 | 10,917 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import algebraic_geometry.locally_ringed_space
import algebraic_geometry.structure_sheaf
import logic.equiv.transfer_instance
import ring_theory.localization.localization_localization
import topology.sheaves.sheaf_condition.sites
import topology.sheaves.functors
/-!
# $Spec$ as a functor to locally ringed spaces.
We define the functor $Spec$ from commutative rings to locally ringed spaces.
## Implementation notes
We define $Spec$ in three consecutive steps, each with more structure than the last:
1. `Spec.to_Top`, valued in the category of topological spaces,
2. `Spec.to_SheafedSpace`, valued in the category of sheafed spaces and
3. `Spec.to_LocallyRingedSpace`, valued in the category of locally ringed spaces.
Additionally, we provide `Spec.to_PresheafedSpace` as a composition of `Spec.to_SheafedSpace` with
a forgetful functor.
## Related results
The adjunction `Γ ⊣ Spec` is constructed in `algebraic_geometry/Gamma_Spec_adjunction.lean`.
-/
noncomputable theory
universes u v
namespace algebraic_geometry
open opposite
open category_theory
open structure_sheaf Spec (structure_sheaf)
/--
The spectrum of a commutative ring, as a topological space.
-/
def Spec.Top_obj (R : CommRing) : Top := Top.of (prime_spectrum R)
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of topological spaces.
-/
def Spec.Top_map {R S : CommRing} (f : R ⟶ S) :
Spec.Top_obj S ⟶ Spec.Top_obj R :=
prime_spectrum.comap f
@[simp] lemma Spec.Top_map_id (R : CommRing) :
Spec.Top_map (𝟙 R) = 𝟙 (Spec.Top_obj R) :=
prime_spectrum.comap_id
lemma Spec.Top_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.Top_map (f ≫ g) = Spec.Top_map g ≫ Spec.Top_map f :=
prime_spectrum.comap_comp _ _
/--
The spectrum, as a contravariant functor from commutative rings to topological spaces.
-/
@[simps] def Spec.to_Top : CommRingᵒᵖ ⥤ Top :=
{ obj := λ R, Spec.Top_obj (unop R),
map := λ R S f, Spec.Top_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.Top_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.Top_map_comp] }
/--
The spectrum of a commutative ring, as a `SheafedSpace`.
-/
@[simps] def Spec.SheafedSpace_obj (R : CommRing) : SheafedSpace CommRing :=
{ carrier := Spec.Top_obj R,
presheaf := (structure_sheaf R).1,
is_sheaf := (structure_sheaf R).2 }
/--
The induced map of a ring homomorphism on the ring spectra, as a morphism of sheafed spaces.
-/
@[simps] def Spec.SheafedSpace_map {R S : CommRing.{u}} (f : R ⟶ S) :
Spec.SheafedSpace_obj S ⟶ Spec.SheafedSpace_obj R :=
{ base := Spec.Top_map f,
c :=
{ app := λ U, comap f (unop U) ((topological_space.opens.map (Spec.Top_map f)).obj (unop U))
(λ p, id),
naturality' := λ U V i, ring_hom.ext $ λ s, subtype.eq $ funext $ λ p, rfl } }
@[simp] lemma Spec.SheafedSpace_map_id {R : CommRing} :
Spec.SheafedSpace_map (𝟙 R) = 𝟙 (Spec.SheafedSpace_obj R) :=
PresheafedSpace.ext _ _ (Spec.Top_map_id R) $ nat_trans.ext _ _ $ funext $ λ U,
begin
dsimp,
erw [PresheafedSpace.id_c_app, comap_id], swap,
{ rw [Spec.Top_map_id, topological_space.opens.map_id_obj_unop] },
simpa [eq_to_hom_map],
end
lemma Spec.SheafedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.SheafedSpace_map (f ≫ g) = Spec.SheafedSpace_map g ≫ Spec.SheafedSpace_map f :=
PresheafedSpace.ext _ _ (Spec.Top_map_comp f g) $ nat_trans.ext _ _ $ funext $ λ U,
by { dsimp, rw category_theory.functor.map_id, rw category.comp_id, erw comap_comp f g, refl }
/--
Spec, as a contravariant functor from commutative rings to sheafed spaces.
-/
@[simps] def Spec.to_SheafedSpace : CommRingᵒᵖ ⥤ SheafedSpace CommRing :=
{ obj := λ R, Spec.SheafedSpace_obj (unop R),
map := λ R S f, Spec.SheafedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.SheafedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.SheafedSpace_map_comp] }
/--
Spec, as a contravariant functor from commutative rings to presheafed spaces.
-/
def Spec.to_PresheafedSpace : CommRingᵒᵖ ⥤ PresheafedSpace.{u} CommRing.{u} :=
Spec.to_SheafedSpace ⋙ SheafedSpace.forget_to_PresheafedSpace
@[simp] lemma Spec.to_PresheafedSpace_obj (R : CommRingᵒᵖ) :
Spec.to_PresheafedSpace.obj R = (Spec.SheafedSpace_obj (unop R)).to_PresheafedSpace := rfl
lemma Spec.to_PresheafedSpace_obj_op (R : CommRing) :
Spec.to_PresheafedSpace.obj (op R) = (Spec.SheafedSpace_obj R).to_PresheafedSpace := rfl
@[simp] lemma Spec.to_PresheafedSpace_map (R S : CommRingᵒᵖ) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f = Spec.SheafedSpace_map f.unop := rfl
lemma Spec.to_PresheafedSpace_map_op (R S : CommRing) (f : R ⟶ S) :
Spec.to_PresheafedSpace.map f.op = Spec.SheafedSpace_map f := rfl
lemma Spec.basic_open_hom_ext {X : RingedSpace} {R : CommRing} {α β : X ⟶ Spec.SheafedSpace_obj R}
(w : α.base = β.base) (h : ∀ r : R, let U := prime_spectrum.basic_open r in
(to_open R U ≫ α.c.app (op U)) ≫ X.presheaf.map (eq_to_hom (by rw w)) =
to_open R U ≫ β.c.app (op U)) : α = β :=
begin
ext1,
{ apply ((Top.sheaf.pushforward β.base).obj X.sheaf).hom_ext _
prime_spectrum.is_basis_basic_opens,
intro r,
apply (structure_sheaf.to_basic_open_epi R r).1,
simpa using h r },
exact w,
end
/--
The spectrum of a commutative ring, as a `LocallyRingedSpace`.
-/
@[simps] def Spec.LocallyRingedSpace_obj (R : CommRing) : LocallyRingedSpace :=
{ local_ring := λ x, @@ring_equiv.local_ring _
(show local_ring (localization.at_prime _), by apply_instance) _
(iso.CommRing_iso_to_ring_equiv $ stalk_iso R x).symm,
.. Spec.SheafedSpace_obj R }
@[elementwise]
lemma stalk_map_to_stalk {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
to_stalk R (prime_spectrum.comap f p) ≫
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p =
f ≫ to_stalk S p :=
begin
erw [← to_open_germ S ⊤ ⟨p, trivial⟩, ← to_open_germ R ⊤ ⟨prime_spectrum.comap f p, trivial⟩,
category.assoc, PresheafedSpace.stalk_map_germ (Spec.SheafedSpace_map f) ⊤ ⟨p, trivial⟩,
Spec.SheafedSpace_map_c_app, to_open_comp_comap_assoc],
refl
end
/--
Under the isomorphisms `stalk_iso`, the map `stalk_map (Spec.SheafedSpace_map f) p` corresponds
to the induced local ring homomorphism `localization.local_ring_hom`.
-/
@[elementwise]
lemma local_ring_hom_comp_stalk_iso {R S : CommRing} (f : R ⟶ S) (p : prime_spectrum S) :
(stalk_iso R (prime_spectrum.comap f p)).hom ≫
@category_struct.comp _ _
(CommRing.of (localization.at_prime (prime_spectrum.comap f p).as_ideal))
(CommRing.of (localization.at_prime p.as_ideal)) _
(localization.local_ring_hom (prime_spectrum.comap f p).as_ideal p.as_ideal f rfl)
(stalk_iso S p).inv =
PresheafedSpace.stalk_map (Spec.SheafedSpace_map f) p :=
(stalk_iso R (prime_spectrum.comap f p)).eq_inv_comp.mp $ (stalk_iso S p).comp_inv_eq.mpr $
localization.local_ring_hom_unique _ _ _ _ $ λ x, by
rw [stalk_iso_hom, stalk_iso_inv, comp_apply, comp_apply, localization_to_stalk_of,
stalk_map_to_stalk_apply, stalk_to_fiber_ring_hom_to_stalk]
/--
The induced map of a ring homomorphism on the prime spectra, as a morphism of locally ringed spaces.
-/
@[simps] def Spec.LocallyRingedSpace_map {R S : CommRing} (f : R ⟶ S) :
Spec.LocallyRingedSpace_obj S ⟶ Spec.LocallyRingedSpace_obj R :=
LocallyRingedSpace.hom.mk (Spec.SheafedSpace_map f) $ λ p, is_local_ring_hom.mk $ λ a ha,
begin
-- Here, we are showing that the map on prime spectra induced by `f` is really a morphism of
-- *locally* ringed spaces, i.e. that the induced map on the stalks is a local ring homomorphism.
rw ← local_ring_hom_comp_stalk_iso_apply at ha,
replace ha := (stalk_iso S p).hom.is_unit_map ha,
rw iso.inv_hom_id_apply at ha,
replace ha := is_local_ring_hom.map_nonunit _ ha,
convert ring_hom.is_unit_map (stalk_iso R (prime_spectrum.comap f p)).inv ha,
rw iso.hom_inv_id_apply
end
@[simp] lemma Spec.LocallyRingedSpace_map_id (R : CommRing) :
Spec.LocallyRingedSpace_map (𝟙 R) = 𝟙 (Spec.LocallyRingedSpace_obj R) :=
LocallyRingedSpace.hom.ext _ _ $
by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_id], refl }
lemma Spec.LocallyRingedSpace_map_comp {R S T : CommRing} (f : R ⟶ S) (g : S ⟶ T) :
Spec.LocallyRingedSpace_map (f ≫ g) =
Spec.LocallyRingedSpace_map g ≫ Spec.LocallyRingedSpace_map f :=
LocallyRingedSpace.hom.ext _ _ $
by { rw [Spec.LocallyRingedSpace_map_val, Spec.SheafedSpace_map_comp], refl }
/--
Spec, as a contravariant functor from commutative rings to locally ringed spaces.
-/
@[simps] def Spec.to_LocallyRingedSpace : CommRingᵒᵖ ⥤ LocallyRingedSpace :=
{ obj := λ R, Spec.LocallyRingedSpace_obj (unop R),
map := λ R S f, Spec.LocallyRingedSpace_map f.unop,
map_id' := λ R, by rw [unop_id, Spec.LocallyRingedSpace_map_id],
map_comp' := λ R S T f g, by rw [unop_comp, Spec.LocallyRingedSpace_map_comp] }
section Spec_Γ
open algebraic_geometry.LocallyRingedSpace
/-- The counit morphism `R ⟶ Γ(Spec R)` given by `algebraic_geometry.structure_sheaf.to_open`. -/
@[simps] def to_Spec_Γ (R : CommRing) : R ⟶ Γ.obj (op (Spec.to_LocallyRingedSpace.obj (op R))) :=
structure_sheaf.to_open R ⊤
instance is_iso_to_Spec_Γ (R : CommRing) : is_iso (to_Spec_Γ R) :=
by { cases R, apply structure_sheaf.is_iso_to_global }
@[reassoc]
lemma Spec_Γ_naturality {R S : CommRing} (f : R ⟶ S) :
f ≫ to_Spec_Γ S = to_Spec_Γ R ≫ Γ.map (Spec.to_LocallyRingedSpace.map f.op).op :=
by { ext, symmetry, apply localization.local_ring_hom_to_map }
/-- The counit (`Spec_Γ_identity.inv.op`) of the adjunction `Γ ⊣ Spec` is an isomorphism. -/
@[simps hom_app inv_app] def Spec_Γ_identity : Spec.to_LocallyRingedSpace.right_op ⋙ Γ ≅ 𝟭 _ :=
iso.symm $ nat_iso.of_components (λ R, as_iso (to_Spec_Γ R) : _) (λ _ _, Spec_Γ_naturality)
end Spec_Γ
/-- The stalk map of `Spec M⁻¹R ⟶ Spec R` is an iso for each `p : Spec M⁻¹R`. -/
lemma Spec_map_localization_is_iso (R : CommRing) (M : submonoid R)
(x : prime_spectrum (localization M)) :
is_iso (PresheafedSpace.stalk_map (Spec.to_PresheafedSpace.map
(CommRing.of_hom (algebra_map R (localization M))).op) x) :=
begin
erw ← local_ring_hom_comp_stalk_iso,
apply_with is_iso.comp_is_iso { instances := ff },
apply_instance,
apply_with is_iso.comp_is_iso { instances := ff },
/- I do not know why this is defeq to the goal, but I'm happy to accept that it is. -/
exact (show is_iso (is_localization.localization_localization_at_prime_iso_localization
M x.as_ideal).to_ring_equiv.to_CommRing_iso.hom, by apply_instance),
apply_instance
end
end algebraic_geometry
|
1e47356e7f1b7c16be8be003104c9facff70807d | 5883d9218e6f144e20eee6ca1dab8529fa1a97c0 | /src/vrel/update.lean | b5c2958734610b9eefcc0c8748ccae79cea36c85 | [] | no_license | spl/alpha-conversion-is-easy | 0d035bc570e52a6345d4890e4d0c9e3f9b8126c1 | ed937fe85d8495daffd9412a5524c77b9fcda094 | refs/heads/master | 1,607,649,280,020 | 1,517,380,240,000 | 1,517,380,240,000 | 52,174,747 | 4 | 0 | null | 1,456,052,226,000 | 1,456,001,163,000 | Lean | UTF-8 | Lean | false | false | 3,590 | lean | /-
This file contains the `vrel` `update` operation and its properties.
-/
import .type
import data.fresh
import data.sigma.extra
namespace acie -----------------------------------------------------------------
namespace vrel -----------------------------------------------------------------
variables {V : Type} [decidable_eq V] -- Type of variable names
variables {a b : V} -- Variable names
variables {vs : Type → Type} [vset vs V] -- Type of variable name sets
variables {X Y : vs V} -- Variable name sets
/-
The `update` operation takes `R : X ×ν Y`, erases from `R` every pair with
either `a` on the left or `b` on the right, and extends the relation with the
pair `(a, b)`.
A simple way to think about `update a b` is (using brackets for readability):
(a = x ∧ b = y) ∨ (a ≠ x ∧ b ≠ y ∧ x ∈ X ∧ y ∈ Y ∧ R a b)
However, that does not give the proper type indexing of `R`. A closer model is:
(a = x ∧ b = y) ∨ (a ≠ x ∧ b ≠ y ∧ R (vname.erase x px) (vname.erase y py))
But note that `px : a ≠ x` and `py : b ≠ y` are not available as arguments to
`R`. Therefore, we use an existentially quantified right alternative to include
these as propositions as well as their types as arguments.
-/
@[reducible]
protected
def update (a b : V) : X ×ν Y → insert a X ×ν insert b Y :=
assume (R : X ×ν Y) (x : ν∈ insert a X) (y : ν∈ insert b Y),
(x.1 = a ∧ y.1 = b) ∨
(∃ (px : x.1 ≠ a) (py : y.1 ≠ b), R (vname.erase x px) (vname.erase y py))
-- Notation for `update`: union with minus sign.
-- Source: http://www.fileformat.info/info/unicode/char/2a41/index.htm
notation R ` ⩁ `:65 (a `, ` b) := vrel.update a b R
namespace update ---------------------------------------------------------------
section ------------------------------------------------------------------------
variables {F : X →ν Y} -- Function on variable name set members
-- Lift a `vname.update` of a fresh variable to a `vrel.update`.
protected
theorem lift
(x : ν∈ insert a X) (y : ν∈ insert (fresh Y).1 Y)
: ⟪x, y⟫ ∈ν vrel.lift (vname.update a (fresh Y).1 F)
→ ⟪x, y⟫ ∈ν vrel.lift F ⩁ (a, (fresh Y).1) :=
begin
cases x with x px,
cases y with y py,
unfold vrel.lift vname.update,
intro H,
cases decidable.em (x = a) with x_eq_a x_ne_a,
begin /- x_eq_a : x = a -/
rw [dif_pos x_eq_a] at H,
left, split, exact x_eq_a, rw [← H]
end,
begin /- x_ne_a : x ≠ a -/
rw [dif_neg x_ne_a] at H,
right,
existsi x_ne_a,
simp [vname.insert] at H,
induction H,
existsi vname.ne_if_mem_and_not_mem (F (vname.erase ⟨x, px⟩ x_ne_a)) (fresh Y),
simp [vname.erase]
end
end
end /- section -/ --------------------------------------------------------------
section ------------------------------------------------------------------------
variables {R₁ R₂ : X ×ν Y} -- Variable name set relations
protected
theorem map (F : ∀ {x : ν∈ X} {y : ν∈ Y}, ⟪x, y⟫ ∈ν R₁ → ⟪x, y⟫ ∈ν R₂)
{x : ν∈ insert a X} {y : ν∈ insert b Y}
: ⟪x, y⟫ ∈ν R₁ ⩁ (a, b) → ⟪x, y⟫ ∈ν R₂ ⩁ (a, b) :=
or.imp_right (λ ⟨px, ⟨py, p⟩⟩, ⟨px, ⟨py, F p⟩⟩)
end /- section -/ --------------------------------------------------------------
end /- namespace -/ update -----------------------------------------------------
end /- namespace -/ vrel -------------------------------------------------------
end /- namespace -/ acie -------------------------------------------------------
|
51766a18dc11b2c4701384fb7c3eb45e778406ec | 77c5b91fae1b966ddd1db969ba37b6f0e4901e88 | /src/algebra/opposites.lean | 29f2b43ef923ea532d87fe0ae838670cb47953a7 | [
"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 | 21,941 | 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.opposite
import algebra.field
import algebra.group.commute
import group_theory.group_action.defs
import data.equiv.mul_add
/-!
# Algebraic operations on `αᵒᵖ`
This file records several basic facts about the opposite of an algebraic structure, e.g. the
opposite of a ring is a ring (with multiplication `x * y = yx`). Use is made of the identity
functions `op : α → αᵒᵖ` and `unop : αᵒᵖ → α`.
-/
namespace opposite
universes u
variables (α : Type u)
instance [has_add α] : has_add (opposite α) :=
{ add := λ x y, op (unop x + unop y) }
instance [has_sub α] : has_sub (opposite α) :=
{ sub := λ x y, op (unop x - unop y) }
instance [add_semigroup α] : add_semigroup (opposite α) :=
{ add_assoc := λ x y z, unop_injective $ add_assoc (unop x) (unop y) (unop z),
.. opposite.has_add α }
instance [add_left_cancel_semigroup α] : add_left_cancel_semigroup (opposite α) :=
{ add_left_cancel := λ x y z H, unop_injective $ add_left_cancel $ op_injective H,
.. opposite.add_semigroup α }
instance [add_right_cancel_semigroup α] : add_right_cancel_semigroup (opposite α) :=
{ add_right_cancel := λ x y z H, unop_injective $ add_right_cancel $ op_injective H,
.. opposite.add_semigroup α }
instance [add_comm_semigroup α] : add_comm_semigroup (opposite α) :=
{ add_comm := λ x y, unop_injective $ add_comm (unop x) (unop y),
.. opposite.add_semigroup α }
instance [has_zero α] : has_zero (opposite α) :=
{ zero := op 0 }
instance [nontrivial α] : nontrivial (opposite α) :=
let ⟨x, y, h⟩ := exists_pair_ne α in nontrivial_of_ne (op x) (op y) (op_injective.ne h)
section
local attribute [semireducible] opposite
@[simp] lemma unop_eq_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop = (0 : α) ↔ a = (0 : αᵒᵖ) :=
iff.refl _
@[simp] lemma op_eq_zero_iff {α} [has_zero α] (a : α) : op a = (0 : αᵒᵖ) ↔ a = (0 : α) :=
iff.refl _
end
lemma unop_ne_zero_iff {α} [has_zero α] (a : αᵒᵖ) : a.unop ≠ (0 : α) ↔ a ≠ (0 : αᵒᵖ) :=
not_iff_not.mpr $ unop_eq_zero_iff a
lemma op_ne_zero_iff {α} [has_zero α] (a : α) : op a ≠ (0 : αᵒᵖ) ↔ a ≠ (0 : α) :=
not_iff_not.mpr $ op_eq_zero_iff a
instance [add_zero_class α] : add_zero_class (opposite α) :=
{ zero_add := λ x, unop_injective $ zero_add $ unop x,
add_zero := λ x, unop_injective $ add_zero $ unop x,
.. opposite.has_add α, .. opposite.has_zero α }
instance [add_monoid α] : add_monoid (opposite α) :=
{ .. opposite.add_semigroup α, .. opposite.add_zero_class α }
instance [add_comm_monoid α] : add_comm_monoid (opposite α) :=
{ .. opposite.add_monoid α, .. opposite.add_comm_semigroup α }
instance [has_neg α] : has_neg (opposite α) :=
{ neg := λ x, op $ -(unop x) }
instance [add_group α] : add_group (opposite α) :=
{ add_left_neg := λ x, unop_injective $ add_left_neg $ unop x,
sub_eq_add_neg := λ x y, unop_injective $ sub_eq_add_neg (unop x) (unop y),
.. opposite.add_monoid α, .. opposite.has_neg α, .. opposite.has_sub α }
instance [add_comm_group α] : add_comm_group (opposite α) :=
{ .. opposite.add_group α, .. opposite.add_comm_monoid α }
instance [has_mul α] : has_mul (opposite α) :=
{ mul := λ x y, op (unop y * unop x) }
instance [semigroup α] : semigroup (opposite α) :=
{ mul_assoc := λ x y z, unop_injective $ eq.symm $ mul_assoc (unop z) (unop y) (unop x),
.. opposite.has_mul α }
instance [right_cancel_semigroup α] : left_cancel_semigroup (opposite α) :=
{ mul_left_cancel := λ x y z H, unop_injective $ mul_right_cancel $ op_injective H,
.. opposite.semigroup α }
instance [left_cancel_semigroup α] : right_cancel_semigroup (opposite α) :=
{ mul_right_cancel := λ x y z H, unop_injective $ mul_left_cancel $ op_injective H,
.. opposite.semigroup α }
instance [comm_semigroup α] : comm_semigroup (opposite α) :=
{ mul_comm := λ x y, unop_injective $ mul_comm (unop y) (unop x),
.. opposite.semigroup α }
instance [has_one α] : has_one (opposite α) :=
{ one := op 1 }
section
local attribute [semireducible] opposite
@[simp] lemma unop_eq_one_iff {α} [has_one α] (a : αᵒᵖ) : a.unop = 1 ↔ a = 1 :=
iff.refl _
@[simp] lemma op_eq_one_iff {α} [has_one α] (a : α) : op a = 1 ↔ a = 1 :=
iff.refl _
end
instance [mul_one_class α] : mul_one_class (opposite α) :=
{ one_mul := λ x, unop_injective $ mul_one $ unop x,
mul_one := λ x, unop_injective $ one_mul $ unop x,
.. opposite.has_mul α, .. opposite.has_one α }
instance [monoid α] : monoid (opposite α) :=
{ .. opposite.semigroup α, .. opposite.mul_one_class α }
instance [right_cancel_monoid α] : left_cancel_monoid (opposite α) :=
{ .. opposite.left_cancel_semigroup α, ..opposite.monoid α }
instance [left_cancel_monoid α] : right_cancel_monoid (opposite α) :=
{ .. opposite.right_cancel_semigroup α, ..opposite.monoid α }
instance [cancel_monoid α] : cancel_monoid (opposite α) :=
{ .. opposite.right_cancel_monoid α, ..opposite.left_cancel_monoid α }
instance [comm_monoid α] : comm_monoid (opposite α) :=
{ .. opposite.monoid α, .. opposite.comm_semigroup α }
instance [cancel_comm_monoid α] : cancel_comm_monoid (opposite α) :=
{ .. opposite.cancel_monoid α, ..opposite.comm_monoid α }
instance [has_inv α] : has_inv (opposite α) :=
{ inv := λ x, op $ (unop x)⁻¹ }
instance [group α] : group (opposite α) :=
{ mul_left_inv := λ x, unop_injective $ mul_inv_self $ unop x,
.. opposite.monoid α, .. opposite.has_inv α }
instance [comm_group α] : comm_group (opposite α) :=
{ .. opposite.group α, .. opposite.comm_monoid α }
instance [distrib α] : distrib (opposite α) :=
{ left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x),
right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y),
.. opposite.has_add α, .. opposite.has_mul α }
instance [mul_zero_class α] : mul_zero_class (opposite α) :=
{ zero := 0,
mul := (*),
zero_mul := λ x, unop_injective $ mul_zero $ unop x,
mul_zero := λ x, unop_injective $ zero_mul $ unop x }
instance [mul_zero_one_class α] : mul_zero_one_class (opposite α) :=
{ .. opposite.mul_zero_class α, .. opposite.mul_one_class α }
instance [semigroup_with_zero α] : semigroup_with_zero (opposite α) :=
{ .. opposite.semigroup α, .. opposite.mul_zero_class α }
instance [monoid_with_zero α] : monoid_with_zero (opposite α) :=
{ .. opposite.monoid α, .. opposite.mul_zero_one_class α }
instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (opposite α) :=
{ .. opposite.add_comm_monoid α, .. opposite.mul_zero_class α, .. opposite.distrib α }
instance [non_unital_semiring α] : non_unital_semiring (opposite α) :=
{ .. opposite.semigroup_with_zero α, .. opposite.non_unital_non_assoc_semiring α }
instance [non_assoc_semiring α] : non_assoc_semiring (opposite α) :=
{ .. opposite.mul_zero_one_class α, .. opposite.non_unital_non_assoc_semiring α }
instance [semiring α] : semiring (opposite α) :=
{ .. opposite.non_unital_semiring α, .. opposite.non_assoc_semiring α }
instance [comm_semiring α] : comm_semiring (opposite α) :=
{ .. opposite.semiring α, .. opposite.comm_semigroup α }
instance [ring α] : ring (opposite α) :=
{ .. opposite.add_comm_group α, .. opposite.monoid α, .. opposite.semiring α }
instance [comm_ring α] : comm_ring (opposite α) :=
{ .. opposite.ring α, .. opposite.comm_semiring α }
instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors (opposite α) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)),
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H)
(λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), }
instance [integral_domain α] : integral_domain (opposite α) :=
{ .. opposite.no_zero_divisors α, .. opposite.comm_ring α, .. opposite.nontrivial α }
instance [group_with_zero α] : group_with_zero (opposite α) :=
{ mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx,
inv_zero := unop_injective inv_zero,
.. opposite.monoid_with_zero α, .. opposite.nontrivial α, .. opposite.has_inv α }
instance [division_ring α] : division_ring (opposite α) :=
{ .. opposite.group_with_zero α, .. opposite.ring α }
instance [field α] : field (opposite α) :=
{ .. opposite.division_ring α, .. opposite.comm_ring α }
instance (R : Type*) [has_scalar R α] : has_scalar R (opposite α) :=
{ smul := λ c x, op (c • unop x) }
instance (R : Type*) [monoid R] [mul_action R α] : mul_action R (opposite α) :=
{ one_smul := λ x, unop_injective $ one_smul R (unop x),
mul_smul := λ r₁ r₂ x, unop_injective $ mul_smul r₁ r₂ (unop x),
..opposite.has_scalar α R }
instance (R : Type*) [monoid R] [add_monoid α] [distrib_mul_action R α] :
distrib_mul_action R (opposite α) :=
{ smul_add := λ r x₁ x₂, unop_injective $ smul_add r (unop x₁) (unop x₂),
smul_zero := λ r, unop_injective $ smul_zero r,
..opposite.mul_action α R }
instance (R : Type*) [monoid R] [monoid α] [mul_distrib_mul_action R α] :
mul_distrib_mul_action R (opposite α) :=
{ smul_mul := λ r x₁ x₂, unop_injective $ smul_mul' r (unop x₂) (unop x₁),
smul_one := λ r, unop_injective $ smul_one r,
..opposite.mul_action α R }
/-- Like `has_mul.to_has_scalar`, but multiplies on the right.
See also `monoid.to_opposite_mul_action` and `monoid_with_zero.to_opposite_mul_action`. -/
instance _root_.has_mul.to_has_opposite_scalar [has_mul α] : has_scalar (opposite α) α :=
{ smul := λ c x, x * c.unop }
lemma op_smul_eq_mul [has_mul α] {a a' : α} : op a • a' = a' * a := rfl
instance _root_.semigroup.opposite_smul_comm_class [semigroup α] :
smul_comm_class (opposite α) α α :=
{ smul_comm := λ x y z, (mul_assoc _ _ _) }
instance _root_.semigroup.opposite_smul_comm_class' [semigroup α] :
smul_comm_class α (opposite α) α :=
{ smul_comm := λ x y z, (mul_assoc _ _ _).symm }
/-- Like `monoid.to_mul_action`, but multiplies on the right. -/
instance _root_.monoid.to_opposite_mul_action [monoid α] : mul_action (opposite α) α :=
{ smul := (•),
one_smul := mul_one,
mul_smul := λ x y r, (mul_assoc _ _ _).symm }
-- The above instance does not create an unwanted diamond, the two paths to
-- `mul_action (opposite α) (opposite α)` are defeq.
example [monoid α] : monoid.to_mul_action (opposite α) = opposite.mul_action α (opposite α) := rfl
/-- `monoid.to_opposite_mul_action` is faithful on cancellative monoids. -/
instance _root_.left_cancel_monoid.to_has_faithful_opposite_scalar [left_cancel_monoid α] :
has_faithful_scalar (opposite α) α :=
⟨λ x y h, unop_injective $ mul_left_cancel (h 1)⟩
/-- `monoid.to_opposite_mul_action` is faithful on nontrivial cancellative monoids with zero. -/
instance _root_.cancel_monoid_with_zero.to_has_faithful_opposite_scalar
[cancel_monoid_with_zero α] [nontrivial α] : has_faithful_scalar (opposite α) α :=
⟨λ x y h, unop_injective $ mul_left_cancel₀ one_ne_zero (h 1)⟩
@[simp] lemma op_zero [has_zero α] : op (0 : α) = 0 := rfl
@[simp] lemma unop_zero [has_zero α] : unop (0 : αᵒᵖ) = 0 := rfl
@[simp] lemma op_one [has_one α] : op (1 : α) = 1 := rfl
@[simp] lemma unop_one [has_one α] : unop (1 : αᵒᵖ) = 1 := rfl
variable {α}
@[simp] lemma op_add [has_add α] (x y : α) : op (x + y) = op x + op y := rfl
@[simp] lemma unop_add [has_add α] (x y : αᵒᵖ) : unop (x + y) = unop x + unop y := rfl
@[simp] lemma op_neg [has_neg α] (x : α) : op (-x) = -op x := rfl
@[simp] lemma unop_neg [has_neg α] (x : αᵒᵖ) : unop (-x) = -unop x := rfl
@[simp] lemma op_mul [has_mul α] (x y : α) : op (x * y) = op y * op x := rfl
@[simp] lemma unop_mul [has_mul α] (x y : αᵒᵖ) : unop (x * y) = unop y * unop x := rfl
@[simp] lemma op_inv [has_inv α] (x : α) : op (x⁻¹) = (op x)⁻¹ := rfl
@[simp] lemma unop_inv [has_inv α] (x : αᵒᵖ) : unop (x⁻¹) = (unop x)⁻¹ := rfl
@[simp] lemma op_sub [add_group α] (x y : α) : op (x - y) = op x - op y := rfl
@[simp] lemma unop_sub [add_group α] (x y : αᵒᵖ) : unop (x - y) = unop x - unop y := rfl
@[simp] lemma op_smul {R : Type*} [has_scalar R α] (c : R) (a : α) : op (c • a) = c • op a := rfl
@[simp] lemma unop_smul {R : Type*} [has_scalar R α] (c : R) (a : αᵒᵖ) :
unop (c • a) = c • unop a := rfl
lemma semiconj_by.op [has_mul α] {a x y : α} (h : semiconj_by a x y) :
semiconj_by (op a) (op y) (op x) :=
begin
dunfold semiconj_by,
rw [← op_mul, ← op_mul, h.eq]
end
lemma semiconj_by.unop [has_mul α] {a x y : αᵒᵖ} (h : semiconj_by a x y) :
semiconj_by (unop a) (unop y) (unop x) :=
begin
dunfold semiconj_by,
rw [← unop_mul, ← unop_mul, h.eq]
end
@[simp] lemma semiconj_by_op [has_mul α] {a x y : α} :
semiconj_by (op a) (op y) (op x) ↔ semiconj_by a x y :=
begin
split,
{ intro h,
rw [← unop_op a, ← unop_op x, ← unop_op y],
exact semiconj_by.unop h },
{ intro h,
exact semiconj_by.op h }
end
@[simp] lemma semiconj_by_unop [has_mul α] {a x y : αᵒᵖ} :
semiconj_by (unop a) (unop y) (unop x) ↔ semiconj_by a x y :=
by conv_rhs { rw [← op_unop a, ← op_unop x, ← op_unop y, semiconj_by_op] }
lemma commute.op [has_mul α] {x y : α} (h : commute x y) : commute (op x) (op y) :=
begin
dunfold commute at h ⊢,
exact semiconj_by.op h
end
lemma commute.unop [has_mul α] {x y : αᵒᵖ} (h : commute x y) : commute (unop x) (unop y) :=
begin
dunfold commute at h ⊢,
exact semiconj_by.unop h
end
@[simp] lemma commute_op [has_mul α] {x y : α} :
commute (op x) (op y) ↔ commute x y :=
begin
dunfold commute,
rw semiconj_by_op
end
@[simp] lemma commute_unop [has_mul α] {x y : αᵒᵖ} :
commute (unop x) (unop y) ↔ commute x y :=
begin
dunfold commute,
rw semiconj_by_unop
end
/-- The function `op` is an additive equivalence. -/
def op_add_equiv [has_add α] : α ≃+ αᵒᵖ :=
{ map_add' := λ a b, rfl, .. equiv_to_opposite }
@[simp] lemma coe_op_add_equiv [has_add α] : (op_add_equiv : α → αᵒᵖ) = op := rfl
@[simp] lemma coe_op_add_equiv_symm [has_add α] :
(op_add_equiv.symm : αᵒᵖ → α) = unop := rfl
@[simp] lemma op_add_equiv_to_equiv [has_add α] :
(op_add_equiv : α ≃+ αᵒᵖ).to_equiv = equiv_to_opposite :=
rfl
end opposite
open opposite
/-- Inversion on a group is a `mul_equiv` to the opposite group. When `G` is commutative, there is
`mul_equiv.inv`. -/
@[simps {fully_applied := ff}]
def mul_equiv.inv' (G : Type*) [group G] : G ≃* Gᵒᵖ :=
{ to_fun := opposite.op ∘ has_inv.inv,
inv_fun := has_inv.inv ∘ opposite.unop,
map_mul' := λ x y, unop_injective $ mul_inv_rev x y,
..(equiv.inv G).trans equiv_to_opposite}
/-- A monoid homomorphism `f : R →* S` such that `f x` commutes with `f y` for all `x, y` defines
a monoid homomorphism to `Sᵒᵖ`. -/
@[simps {fully_applied := ff}]
def monoid_hom.to_opposite {R S : Type*} [mul_one_class R] [mul_one_class S] (f : R →* S)
(hf : ∀ x y, commute (f x) (f y)) : R →* Sᵒᵖ :=
{ to_fun := opposite.op ∘ f,
map_one' := congr_arg op f.map_one,
map_mul' := λ x y, by simp [(hf x y).eq] }
/-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines
a ring homomorphism to `Sᵒᵖ`. -/
@[simps {fully_applied := ff}]
def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S)
(hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵒᵖ :=
{ to_fun := opposite.op ∘ f,
.. ((opposite.op_add_equiv : S ≃+ Sᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵒᵖ),
.. f.to_monoid_hom.to_opposite hf }
/-- The units of the opposites are equivalent to the opposites of the units. -/
def units.op_equiv {R} [monoid R] : units Rᵒᵖ ≃* (units R)ᵒᵖ :=
{ to_fun := λ u, op ⟨unop u, unop ↑(u⁻¹), op_injective u.4, op_injective u.3⟩,
inv_fun := op_induction $ λ u, ⟨op ↑(u), op ↑(u⁻¹), unop_injective $ u.4, unop_injective u.3⟩,
map_mul' := λ x y, unop_injective $ units.ext $ rfl,
left_inv := λ x, units.ext $ rfl,
right_inv := λ x, unop_injective $ units.ext $ rfl }
@[simp]
lemma units.coe_unop_op_equiv {R} [monoid R] (u : units Rᵒᵖ) :
((units.op_equiv u).unop : R) = unop (u : Rᵒᵖ) :=
rfl
@[simp]
lemma units.coe_op_equiv_symm {R} [monoid R] (u : (units R)ᵒᵖ) :
(units.op_equiv.symm u : Rᵒᵖ) = op (u.unop : R) :=
rfl
/-- A hom `α →* β` can equivalently be viewed as a hom `αᵒᵖ →* βᵒᵖ`. This is the action of the
(fully faithful) `ᵒᵖ`-functor on morphisms. -/
@[simps]
def monoid_hom.op {α β} [mul_one_class α] [mul_one_class β] :
(α →* β) ≃ (αᵒᵖ →* βᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_one' := unop_injective f.map_one,
map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_one' := congr_arg unop f.map_one,
map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of a monoid hom `αᵒᵖ →* βᵒᵖ`. Inverse to `monoid_hom.op`. -/
@[simp] def monoid_hom.unop {α β} [mul_one_class α] [mul_one_class β] :
(αᵒᵖ →* βᵒᵖ) ≃ (α →* β) := monoid_hom.op.symm
/-- A hom `α →+ β` can equivalently be viewed as a hom `αᵒᵖ →+ βᵒᵖ`. This is the action of the
(fully faithful) `ᵒᵖ`-functor on morphisms. -/
@[simps]
def add_monoid_hom.op {α β} [add_zero_class α] [add_zero_class β] :
(α →+ β) ≃ (αᵒᵖ →+ βᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
map_zero' := unop_injective f.map_zero,
map_add' := λ x y, unop_injective (f.map_add x.unop y.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
map_zero' := congr_arg unop f.map_zero,
map_add' := λ x y, congr_arg unop (f.map_add (op x) (op y)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of an additive monoid hom `αᵒᵖ →+ βᵒᵖ`. Inverse to `add_monoid_hom.op`. -/
@[simp] def add_monoid_hom.unop {α β} [add_zero_class α] [add_zero_class β] :
(αᵒᵖ →+ βᵒᵖ) ≃ (α →+ β) := add_monoid_hom.op.symm
/-- A ring hom `α →+* β` can equivalently be viewed as a ring hom `αᵒᵖ →+* βᵒᵖ`. This is the action
of the (fully faithful) `ᵒᵖ`-functor on morphisms. -/
@[simps]
def ring_hom.op {α β} [non_assoc_semiring α] [non_assoc_semiring β] :
(α →+* β) ≃ (αᵒᵖ →+* βᵒᵖ) :=
{ to_fun := λ f, { ..f.to_add_monoid_hom.op, ..f.to_monoid_hom.op },
inv_fun := λ f, { ..f.to_add_monoid_hom.unop, ..f.to_monoid_hom.unop },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of a ring hom `αᵒᵖ →+* βᵒᵖ`. Inverse to `ring_hom.op`. -/
@[simp] def ring_hom.unop {α β} [non_assoc_semiring α] [non_assoc_semiring β] :
(αᵒᵖ →+* βᵒᵖ) ≃ (α →+* β) := ring_hom.op.symm
/-- A iso `α ≃+ β` can equivalently be viewed as an iso `αᵒᵖ ≃+ βᵒᵖ`. -/
@[simps]
def add_equiv.op {α β} [has_add α] [has_add β] :
(α ≃+ β) ≃ (αᵒᵖ ≃+ βᵒᵖ) :=
{ to_fun := λ f, op_add_equiv.symm.trans (f.trans op_add_equiv),
inv_fun := λ f, op_add_equiv.trans (f.trans op_add_equiv.symm),
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of an iso `αᵒᵖ ≃+ βᵒᵖ`. Inverse to `add_equiv.op`. -/
@[simp] def add_equiv.unop {α β} [has_add α] [has_add β] :
(αᵒᵖ ≃+ βᵒᵖ) ≃ (α ≃+ β) := add_equiv.op.symm
/-- A iso `α ≃* β` can equivalently be viewed as an iso `αᵒᵖ ≃+ βᵒᵖ`. -/
@[simps]
def mul_equiv.op {α β} [has_mul α] [has_mul β] :
(α ≃* β) ≃ (αᵒᵖ ≃* βᵒᵖ) :=
{ to_fun := λ f, { to_fun := op ∘ f ∘ unop,
inv_fun := op ∘ f.symm ∘ unop,
left_inv := λ x, unop_injective (f.symm_apply_apply x.unop),
right_inv := λ x, unop_injective (f.apply_symm_apply x.unop),
map_mul' := λ x y, unop_injective (f.map_mul y.unop x.unop) },
inv_fun := λ f, { to_fun := unop ∘ f ∘ op,
inv_fun := unop ∘ f.symm ∘ op,
left_inv := λ x, op_injective (f.symm_apply_apply (op x)),
right_inv := λ x, op_injective (f.apply_symm_apply (op x)),
map_mul' := λ x y, congr_arg unop (f.map_mul (op y) (op x)) },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, refl } }
/-- The 'unopposite' of an iso `αᵒᵖ ≃* βᵒᵖ`. Inverse to `mul_equiv.op`. -/
@[simp] def mul_equiv.unop {α β} [has_mul α] [has_mul β] :
(αᵒᵖ ≃* βᵒᵖ) ≃ (α ≃* β) := mul_equiv.op.symm
section ext
/-- This ext lemma change equalities on `αᵒᵖ →+ β` to equalities on `α →+ β`.
This is useful because there are often ext lemmas for specific `α`s that will apply
to an equality of `α →+ β` such as `finsupp.add_hom_ext'`. -/
@[ext]
lemma add_monoid_hom.op_ext {α β} [add_zero_class α] [add_zero_class β]
(f g : αᵒᵖ →+ β)
(h : f.comp (op_add_equiv : α ≃+ αᵒᵖ).to_add_monoid_hom =
g.comp (op_add_equiv : α ≃+ αᵒᵖ).to_add_monoid_hom) : f = g :=
add_monoid_hom.ext $ λ x, (add_monoid_hom.congr_fun h : _) x.unop
end ext
|
e1fc0a7238d8a731dc8512cd5b41bd25bd5c766b | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/topology/path_connected.lean | 8847f32208b6f4fbb2143aba37e49605bb47a794 | [
"Apache-2.0"
] | permissive | ayush1801/mathlib | 78949b9f789f488148142221606bf15c02b960d2 | ce164e28f262acbb3de6281b3b03660a9f744e3c | refs/heads/master | 1,692,886,907,941 | 1,635,270,866,000 | 1,635,270,866,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36,591 | lean | /-
Copyright (c) 2020 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot
-/
import topology.unit_interval
import topology.algebra.ordered.proj_Icc
import topology.continuous_function.basic
/-!
# Path connectedness
## Main definitions
In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space.
* `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X`
mapping `0` to `x` and `1` to `y`.
* `path.map` is the image of a path under a continuous map.
* `joined (x y : X)` means there is a path between `x` and `y`.
* `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`.
* `path_component (x : X)` is the set of points joined to `x`.
* `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two
points of `X` are joined.
Then there are corresponding relative notions for `F : set X`.
* `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`.
* `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`.
* `path_component_in F (x : X)` is the set of points joined to `x` in `F`.
* `is_path_connected F` asserts that `F` is non-empty and every two
points of `F` are joined in `F`.
* `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected:
each point has a basis of path-connected neighborhoods (we do *not* ask these to be open).
## Main theorems
* `joined` and `joined_in F` are transitive relations.
One can link the absolute and relative version in two directions, using `(univ : set X)` or the
subtype `↥F`.
* `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)`
* `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F`
For locally path connected spaces, we have
* `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X`
* `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U`
## Implementation notes
By default, all paths have `I` as their source and `X` as their target, but there is an
operation `set.Icc_extend` that will extend any continuous map `γ : I → X` into a continuous map
`Icc_extend zero_le_one γ : ℝ → X` that is constant before `0` and after `1`.
This is used to define `path.extend` that turns `γ : path x y` into a continuous map
`γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x`
on `(-∞, 0]` and to `y` on `[1, +∞)`.
-/
noncomputable theory
open_locale classical topological_space filter unit_interval
open filter set function unit_interval
variables {X : Type*} [topological_space X] {x y z : X} {ι : Type*}
/-! ### Paths -/
/-- Continuous path connecting two points `x` and `y` in a topological space -/
@[nolint has_inhabited_instance]
structure path (x y : X) extends C(I, X) :=
(source' : to_fun 0 = x)
(target' : to_fun 1 = y)
instance : has_coe_to_fun (path x y) (λ _, I → X) := ⟨λ p, p.to_fun⟩
@[ext] protected lemma path.ext {X : Type*} [topological_space X] {x y : X} :
∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂
| ⟨⟨x, h11⟩, h12, h13⟩ ⟨⟨.(x), h21⟩, h22, h23⟩ rfl := rfl
namespace path
@[simp] lemma coe_mk (f : I → X) (h₁ h₂ h₃) : ⇑(mk ⟨f, h₁⟩ h₂ h₃ : path x y) = f := rfl
variable (γ : path x y)
@[continuity]
protected lemma continuous : continuous γ :=
γ.continuous_to_fun
@[simp] protected lemma source : γ 0 = x :=
γ.source'
@[simp] protected lemma target : γ 1 = y :=
γ.target'
/-- See Note [custom simps projection]. We need to specify this projection explicitly in this case,
because it is a composition of multiple projections. -/
def simps.apply : I → X := γ
initialize_simps_projections path (to_continuous_map_to_fun → simps.apply, -to_continuous_map)
@[simp] lemma coe_to_continuous_map : ⇑γ.to_continuous_map = γ := rfl
/-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/
instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} :
has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X :=
⟨λ φ p, φ p.1 p.2⟩
/-- The constant path from a point to itself -/
@[refl, simps] def refl (x : X) : path x x :=
{ to_fun := λ t, x,
continuous_to_fun := continuous_const,
source' := rfl,
target' := rfl }
@[simp] lemma refl_range {X : Type*} [topological_space X] {a : X} :
range (path.refl a) = {a} :=
by simp [path.refl, has_coe_to_fun.coe, coe_fn]
/-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/
@[symm, simps] def symm (γ : path x y) : path y x :=
{ to_fun := γ ∘ σ,
continuous_to_fun := by continuity,
source' := by simpa [-path.target] using γ.target,
target' := by simpa [-path.source] using γ.source }
@[simp] lemma symm_symm {γ : path x y} : γ.symm.symm = γ :=
by { ext, simp }
@[simp] lemma refl_symm {X : Type*} [topological_space X] {a : X} :
(path.refl a).symm = path.refl a :=
by { ext, refl }
@[simp] lemma symm_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) :
range γ.symm = range γ :=
begin
ext x,
simp only [mem_range, path.symm, has_coe_to_fun.coe, coe_fn, unit_interval.symm, set_coe.exists,
comp_app, subtype.coe_mk, subtype.val_eq_coe],
split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, mem_iff_one_sub_mem.mp hy, _⟩; convert hxy,
simp
end
/-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/
def extend : ℝ → X := Icc_extend zero_le_one γ
@[continuity]
lemma continuous_extend : continuous γ.extend :=
γ.continuous.Icc_extend
@[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X}
(γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ :=
Icc_extend_of_mem _ γ ht
lemma extend_zero : γ.extend 0 = x :=
by simp
lemma extend_one : γ.extend 1 = y :=
by simp
@[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X}
(γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend t = γ t :=
Icc_extend_coe _ γ t
@[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X}
(γ : path a b) : range γ.extend = range γ :=
Icc_extend_range _ γ
lemma extend_of_le_zero {X : Type*} [topological_space X] {a b : X}
(γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a :=
(Icc_extend_of_le_left _ _ ht).trans γ.source
lemma extend_of_one_le {X : Type*} [topological_space X] {a b : X}
(γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b :=
(Icc_extend_of_right_le _ _ ht).trans γ.target
@[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} :
(path.refl a).extend = λ _, a := rfl
/-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/
def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y :=
{ to_fun := f ∘ coe,
continuous_to_fun := hf.comp_continuous continuous_subtype_coe subtype.prop,
source' := h₀,
target' := h₁ }
lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) :
∀ t, of_line hf h₀ h₁ t ∈ f '' I :=
λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩
local attribute [simp] Iic_def
/-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first
path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/
@[trans] def trans (γ : path x y) (γ' : path y z) : path x z :=
{ to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe,
continuous_to_fun :=
begin
refine (continuous.if_le _ _ continuous_id continuous_const (by norm_num)).comp
continuous_subtype_coe,
-- TODO: the following are provable by `continuity` but it is too slow
exacts [γ.continuous_extend.comp (continuous_const.mul continuous_id),
γ'.continuous_extend.comp ((continuous_const.mul continuous_id).sub continuous_const)]
end,
source' := by norm_num,
target' := by norm_num }
lemma trans_apply (γ : path x y) (γ' : path y z) (t : I) : (γ.trans γ') t =
if h : (t : ℝ) ≤ 1/2 then
γ ⟨2 * t, (mul_pos_mem_iff zero_lt_two).2 ⟨t.2.1, h⟩⟩
else
γ' ⟨2 * t - 1, two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, t.2.2⟩⟩ :=
show ite _ _ _ = _,
by split_ifs; rw extend_extends
@[simp] lemma trans_symm (γ : path x y) (γ' : path y z) :
(γ.trans γ').symm = γ'.symm.trans γ.symm :=
begin
ext t,
simp only [trans_apply, one_div, symm_apply, not_le, comp_app],
split_ifs with h h₁ h₂ h₃ h₄; rw [coe_symm_eq] at h,
{ have ht : (t : ℝ) = 1/2,
{ linarith [unit_interval.nonneg t, unit_interval.le_one t] },
norm_num [ht] },
{ refine congr_arg _ (subtype.ext _),
norm_num [sub_sub_assoc_swap, mul_sub] },
{ refine congr_arg _ (subtype.ext _),
have h : 2 - 2 * (t : ℝ) - 1 = 1 - 2 * t, by linarith,
norm_num [mul_sub, h] },
{ exfalso, linarith [unit_interval.nonneg t, unit_interval.le_one t] }
end
@[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} :
(path.refl a).trans (path.refl a) = path.refl a :=
begin
ext,
simp only [path.trans, if_t_t, one_div, path.refl_extend],
refl
end
lemma trans_range {X : Type*} [topological_space X] {a b c : X}
(γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ :=
begin
rw path.trans,
apply eq_of_subset_of_subset,
{ rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩,
by_cases h : t ≤ 1/2,
{ left,
use [2*t, ⟨by linarith, by linarith⟩],
rw ← γ₁.extend_extends,
unfold_coes at hxt,
simp only [h, comp_app, if_true] at hxt,
exact hxt },
{ right,
use [2*t-1, ⟨by linarith, by linarith⟩],
rw ← γ₂.extend_extends,
unfold_coes at hxt,
simp only [h, comp_app, if_false] at hxt,
exact hxt } },
{ rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩),
{ use ⟨t/2, ⟨by linarith, by linarith⟩⟩,
unfold_coes,
have : t/2 ≤ 1/2 := by linarith,
simp only [this, comp_app, if_true],
ring_nf,
rwa γ₁.extend_extends },
{ by_cases h : t = 0,
{ use ⟨1/2, ⟨by linarith, by linarith⟩⟩,
unfold_coes,
simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (@two_ne_zero ℝ _ _)],
rw γ₁.extend_one,
rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt },
{ use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩,
unfold_coes,
change t ≠ 0 at h,
have ht0 := lt_of_le_of_ne ht0 h.symm,
have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith},
simp only [comp_app, if_false, this],
ring_nf,
rwa γ₂.extend_extends } } }
end
/-- Image of a path from `x` to `y` by a continuous map -/
def map (γ : path x y) {Y : Type*} [topological_space Y]
{f : X → Y} (h : continuous f) : path (f x) (f y) :=
{ to_fun := f ∘ γ,
continuous_to_fun := by continuity,
source' := by simp,
target' := by simp }
@[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y]
{f : X → Y} (h : continuous f) :
(γ.map h : I → Y) = f ∘ γ :=
by { ext t, refl }
/-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/
def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' :=
{ to_fun := γ,
continuous_to_fun := γ.continuous,
source' := by simp [hx],
target' := by simp [hy] }
@[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X}
(γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) :
(γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl
@[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X}
(γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) :
(γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl
@[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) :
(γ.cast hx hy : I → X) = γ :=
rfl
@[continuity]
lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι]
{a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) :
continuous ↿(λ t, (γ t).symm) :=
h.comp (continuous_id.prod_map continuous_symm)
@[continuity]
lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X]
[topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) :
continuous ↿(λ t, (γ t).extend) :=
h.comp (continuous_id.prod_map continuous_proj_Icc)
@[continuity]
lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι]
{a b c : ι → X}
(γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁)
(γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) :
continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) :=
begin
have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁,
have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂,
simp only [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans, (∘)],
refine continuous.if_le _ _ (continuous_subtype_coe.comp continuous_snd) continuous_const _,
{ change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))),
exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) },
{ change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))),
exact h₂'.comp (continuous_id.prod_map $
(continuous_const.mul continuous_subtype_coe).sub continuous_const) },
{ rintros st hst,
simp [hst, mul_inv_cancel (@two_ne_zero ℝ _ _)] }
end
/-! #### Truncating a path -/
/-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the
time interval `[t₀, t₁]` and stays still otherwise. -/
def truncate {X : Type*} [topological_space X] {a b : X}
(γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) :=
{ to_fun := λ s, γ.extend (min (max s t₀) t₁),
continuous_to_fun := γ.continuous_extend.comp
((continuous_subtype_coe.max continuous_const).min continuous_const),
source' :=
begin
simp only [min_def, max_def],
norm_cast,
split_ifs with h₁ h₂ h₃ h₄,
{ simp [γ.extend_of_le_zero h₁] },
{ congr, linarith },
{ have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂),
simp [γ.extend_of_le_zero h₄, γ.extend_of_le_zero h₁] },
all_goals { refl }
end,
target' :=
begin
simp only [min_def, max_def],
norm_cast,
split_ifs with h₁ h₂ h₃,
{ simp [γ.extend_of_one_le h₂] },
{ refl },
{ have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁),
simp [γ.extend_of_one_le h₄, γ.extend_of_one_le (h₄.trans h₃)] },
{ refl }
end }
/-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁`
casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/
def truncate_of_le {X : Type*} [topological_space X] {a b : X}
(γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) :=
(γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl
lemma truncate_range {X : Type*} [topological_space X] {a b : X}
(γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ :=
begin
rw ← γ.extend_range,
simp only [range_subset_iff, set_coe.exists, set_coe.forall],
intros x hx,
simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self]
end
/-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we
mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/
@[continuity]
lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X}
(γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) :=
γ.continuous_extend.comp
(((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min
(continuous_fst.comp continuous_snd))
/- TODO : When `continuity` gets quicker, change the proof back to :
`begin`
`simp only [has_coe_to_fun.coe, coe_fn, path.truncate],`
`continuity,`
`exact continuous_subtype_coe`
`end` -/
@[continuity]
lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X}
(γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) :=
have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id,
by convert γ.truncate_continuous_family.comp key
@[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X}
(γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl :=
begin
ext x,
rw cast_coe,
simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min_def, max_def],
split_ifs with h₁ h₂; congr,
exact le_antisymm ‹_› ‹_›
end
@[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) :
γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero :=
by convert γ.truncate_self 0; exact γ.extend_zero.symm
@[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) :
γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one :=
by convert γ.truncate_self 1; exact γ.extend_one.symm
@[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X}
(γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) :=
begin
ext x,
rw cast_coe,
have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2,
rw [truncate, coe_mk, max_eq_left this.1, min_eq_left this.2, extend_extends']
end
/-! #### Reparametrising a path -/
/--
Given a path `γ` and a function `f : I → I` where `f 0 = 0` and `f 1 = 1`, `γ.reparam f` is the
path defined by `γ ∘ f`.
-/
def reparam (γ : path x y) (f : I → I) (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) :
path x y :=
{ to_fun := γ ∘ f,
continuous_to_fun := by continuity,
source' := by simp [hf₀],
target' := by simp [hf₁] }
@[simp]
lemma coe_to_fun (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0)
(hf₁ : f 1 = 1) : ⇑(γ.reparam f hfcont hf₀ hf₁) = γ ∘ f := rfl
@[simp]
lemma reparam_id (γ : path x y) : γ.reparam id continuous_id rfl rfl = γ :=
by { ext, refl }
lemma range_reparam (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0)
(hf₁ : f 1 = 1) : range ⇑(γ.reparam f hfcont hf₀ hf₁) = range γ :=
begin
change range (γ ∘ f) = range γ,
have : range f = univ,
{ rw range_iff_surjective,
intro t,
have h₁ : continuous (Icc_extend (@zero_le_one ℝ _) f),
{ continuity },
have := intermediate_value_Icc (@zero_le_one ℝ _) h₁.continuous_on,
{ rw [Icc_extend_left, Icc_extend_right] at this,
change Icc (f 0) (f 1) ⊆ _ at this,
rw [hf₀, hf₁] at this,
rcases this t.2 with ⟨w, hw₁, hw₂⟩,
rw Icc_extend_of_mem _ _ hw₁ at hw₂,
use [⟨w, hw₁⟩, hw₂] } },
rw [range_comp, this, image_univ],
end
lemma refl_reparam {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0)
(hf₁ : f 1 = 1) : (refl x).reparam f hfcont hf₀ hf₁ = refl x :=
begin
ext,
simp,
end
end path
/-! ### Being joined by a path -/
/-- The relation "being joined by a path". This is an equivalence relation. -/
def joined (x y : X) : Prop :=
nonempty (path x y)
@[refl] lemma joined.refl (x : X) : joined x x :=
⟨path.refl x⟩
/-- When two points are joined, choose some path from `x` to `y`. -/
def joined.some_path (h : joined x y) : path x y :=
nonempty.some h
@[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x :=
⟨h.some_path.symm⟩
@[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) :
joined x z :=
⟨hxy.some_path.trans hyz.some_path⟩
variables (X)
/-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/
def path_setoid : setoid X :=
{ r := joined,
iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) }
/-- The quotient type of points of a topological space modulo being joined by a continuous path. -/
def zeroth_homotopy := quotient (path_setoid X)
instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩
variables {X}
/-! ### Being joined by a path inside a set -/
/-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not
reflexive for points that do not belong to `F`. -/
def joined_in (F : set X) (x y : X) : Prop :=
∃ γ : path x y, ∀ t, γ t ∈ F
variables {F : set X}
lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F :=
begin
rcases h with ⟨γ, γ_in⟩,
have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in },
simpa using this
end
lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F :=
h.mem.1
lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F :=
h.mem.2
/-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/
def joined_in.some_path (h : joined_in F x y) : path x y :=
classical.some h
lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F :=
classical.some_spec h t
/-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/
lemma joined_in.joined_subtype (h : joined_in F x y) :
joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) :=
⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩,
continuous_to_fun := by continuity,
source' := by simp,
target' := by simp }⟩
lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y)
(hF : f '' I ⊆ F) : joined_in F x y :=
⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩
lemma joined_in.joined (h : joined_in F x y) : joined x y :=
⟨h.some_path⟩
lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) :
joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) :=
⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩
@[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y :=
by simp [joined_in, joined, exists_true_iff_nonempty]
lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y :=
⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩
lemma joined_in.refl (h : x ∈ F) : joined_in F x x :=
⟨path.refl x, λ t, h⟩
@[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x :=
begin
cases h.mem with hx hy,
simp [joined_in_iff_joined, *] at *,
exact h.symm
end
lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z :=
begin
cases hxy.mem with hx hy,
cases hyz.mem with hx hy,
simp [joined_in_iff_joined, *] at *,
exact hxy.trans hyz
end
/-! ### Path component -/
/-- The path component of `x` is the set of points that can be joined to `x`. -/
def path_component (x : X) := {y | joined x y}
@[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x :=
joined.refl x
@[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty :=
⟨x, mem_path_component_self x⟩
lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x :=
joined.symm h
lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x :=
⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩
lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y :=
begin
ext z,
split,
{ intro h',
rw path_component_symm,
exact (h.trans h').symm },
{ intro h',
rw path_component_symm at h' ⊢,
exact h'.trans h },
end
lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x :=
λ y h, (is_connected_range h.some_path.continuous).subset_connected_component
⟨0, by simp⟩ ⟨1, by simp⟩
/-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/
def path_component_in (x : X) (F : set X) := {y | joined_in F x y}
@[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x :=
by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty]
lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) :
z ∈ path_component x :=
hxy.trans hyz
/-! ### Path connected sets -/
/-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/
def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y
lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F :=
begin
split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in],
{ ext y,
exact ⟨λ hy, hy.mem.2, h⟩ },
{ intros y y_in,
rwa ← h at y_in },
end
lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y :=
λ x y x_in y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in)
lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y :=
⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩,
λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b x b_in x_in⟩⟩
lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F)
{f : X → Y} (hf : continuous f) : is_path_connected (f '' F) :=
begin
rcases hF with ⟨x, x_in, hx⟩,
use [f x, mem_image_of_mem f x_in],
rintros _ ⟨y, y_in, rfl⟩,
exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩,
end
lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) :
y ∈ path_component x :=
(h.joined_in x y x_in y_in).joined
lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) :
F ⊆ path_component x :=
λ y y_in, h.mem_path_component x_in y_in
lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V)
(hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) :=
begin
rcases hUV with ⟨x, xU, xV⟩,
use [x, or.inl xU],
rintros y (yU | yV),
{ exact (hU.joined_in x y xU yU).mono (subset_union_left U V) },
{ exact (hV.joined_in x y xV yV).mono (subset_union_right U V) },
end
/-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller
ambient type `U` (when `U` contains `W`). -/
lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) :
is_path_connected ((coe : U → X) ⁻¹' W) :=
begin
rcases hW with ⟨x, x_in, hx⟩,
use [⟨x, hWU x_in⟩, by simp [x_in]],
rintros ⟨y, hyU⟩ hyW,
exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩
end
lemma is_path_connected.exists_path_through_family
{X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s)
(p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) :
∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) :=
begin
let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩,
obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s,
{ have hp' : ∀ i ≤ n, p' i ∈ s,
{ intros i hi,
simp [p', nat.lt_succ_of_le hi, hp] },
clear_value p',
clear hp p,
induction n with n hn,
{ use path.refl (p' 0),
{ split,
{ rintros i hi, rw nat.le_zero_iff.mp hi, exact ⟨0, rfl⟩ },
{ rw range_subset_iff, rintros x, exact hp' 0 (le_refl _) } } },
{ rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩,
rcases h.joined_in (p' n) (p' $ n+1) (hp' n n.le_succ) (hp' (n+1) $ le_refl _) with ⟨γ₁, hγ₁⟩,
let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁,
use γ,
have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁,
split,
{ rintros i hi,
by_cases hi' : i ≤ n,
{ rw range_eq,
left,
exact hγ₀.1 i hi' },
{ rw [not_le, ← nat.succ_le_iff] at hi',
have : i = n.succ := by linarith,
rw this,
use 1,
exact γ.target } },
{ rw range_eq,
apply union_subset hγ₀.2,
rw range_subset_iff,
exact hγ₁ } } },
have hpp' : ∀ k < n+1, p k = p' k,
{ intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast },
use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self),
simp only [γ.cast_coe],
refine and.intro hγ.2 _,
rintros ⟨i, hi⟩,
convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi,
congr,
ext,
rw fin.coe_coe_of_lt hi,
norm_cast
end
lemma is_path_connected.exists_path_through_family'
{X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s)
(p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) :
∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i :=
begin
rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩,
rcases hγ with ⟨h₁, h₂⟩,
simp only [range, mem_set_of_eq] at h₂,
rw range_subset_iff at h₁,
choose! t ht using h₂,
exact ⟨γ, t, h₁, ht⟩
end
/-! ### Path connected spaces -/
/-- A topological space is path-connected if it is non-empty and every two points can be
joined by a continuous path. -/
class path_connected_space (X : Type*) [topological_space X] : Prop :=
(nonempty : nonempty X)
(joined : ∀ x y : X, joined x y)
attribute [instance, priority 50] path_connected_space.nonempty
lemma path_connected_space_iff_zeroth_homotopy :
path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) :=
begin
letI := path_setoid X,
split,
{ introI h,
refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩,
rintros ⟨x⟩ ⟨y⟩,
exact quotient.sound (path_connected_space.joined x y) },
{ unfold zeroth_homotopy,
rintros ⟨h, h'⟩,
resetI,
exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ },
end
namespace path_connected_space
variables [path_connected_space X]
/-- Use path-connectedness to build a path between two points. -/
def some_path (x y : X) : path x y :=
nonempty.some (joined x y)
end path_connected_space
lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F :=
begin
rw is_path_connected_iff,
split,
{ rintro ⟨⟨x, x_in⟩, h⟩,
refine ⟨⟨⟨x, x_in⟩⟩, _⟩,
rintros ⟨y, y_in⟩ ⟨z, z_in⟩,
have H := h y z y_in z_in,
rwa joined_in_iff_joined y_in z_in at H },
{ rintros ⟨⟨x, x_in⟩, H⟩,
refine ⟨⟨x, x_in⟩, λ y z y_in z_in, _⟩,
rw joined_in_iff_joined y_in z_in,
apply H }
end
lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) :=
begin
split,
{ introI h,
inhabit X,
refine ⟨default X, mem_univ _, _⟩,
simpa using path_connected_space.joined (default X) },
{ intro h,
have h' := h.joined_in,
cases h with x h,
exact ⟨⟨x⟩, by simpa using h'⟩ },
end
lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ :=
by simp [path_connected_space_iff_univ, is_path_connected_iff_eq]
@[priority 100] -- see Note [lower instance priority]
instance path_connected_space.connected_space [path_connected_space X] : connected_space X :=
begin
rw connected_space_iff_connected_component,
rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩,
use x,
rw ← univ_subset_iff,
exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x
end
namespace path_connected_space
variables [path_connected_space X]
lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) :
∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) :=
begin
have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance),
rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩,
exact ⟨γ, h⟩
end
lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) :
∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i :=
begin
have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance),
rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩,
exact ⟨γ, t, h⟩
end
end path_connected_space
/-! ### Locally path connected spaces -/
/-- A topological space is locally path connected, at every point, path connected
neighborhoods form a neighborhood basis. -/
class loc_path_connected_space (X : Type*) [topological_space X] : Prop :=
(path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id)
export loc_path_connected_space (path_connected_basis)
lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X}
(h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) :
loc_path_connected_space X :=
begin
constructor,
intro x,
apply (h x).to_has_basis,
{ intros i pi,
exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ },
{ rintros U ⟨U_in, hU⟩,
rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩,
tauto }
end
lemma path_connected_space_iff_connected_space [loc_path_connected_space X] :
path_connected_space X ↔ connected_space X :=
begin
split,
{ introI h,
apply_instance },
{ introI hX,
inhabit X,
let x₀ := default X,
rw path_connected_space_iff_eq,
use x₀,
refine eq_univ_of_nonempty_clopen (by simp) ⟨_, _⟩,
{ rw is_open_iff_mem_nhds,
intros y y_in,
rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩,
apply mem_of_superset U_in,
rw ← path_component_congr y_in,
exact hU.subset_path_component (mem_of_mem_nhds U_in) },
{ rw is_closed_iff_nhds,
intros y H,
rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩,
rcases H U U_in with ⟨z, hz, hz'⟩,
exact ((hU.joined_in z y hz $ mem_of_mem_nhds U_in).joined.mem_path_component hz') } },
end
lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U)
(hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id :=
(path_connected_basis x).has_basis_self_subset (is_open.mem_nhds h hx)
lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) :
loc_path_connected_space U :=
⟨begin
rintros ⟨x, x_in⟩,
rw nhds_subtype_eq_comap,
constructor,
intros V,
rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff,
split,
{ rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩,
exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ },
{ rintros ⟨W, ⟨W_in, hW⟩, hWV⟩,
refine ⟨coe '' W, ⟨filter.image_coe_mem_of_mem_comap (is_open.mem_nhds h x_in) W_in,
hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩,
rintros x ⟨y, ⟨y_in, hy⟩⟩,
rw ← subtype.coe_injective hy,
tauto },
end⟩
lemma is_open.is_connected_iff_is_path_connected
[loc_path_connected_space X] {U : set X} (U_op : is_open U) :
is_path_connected U ↔ is_connected U :=
begin
rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space],
haveI := loc_path_connected_of_is_open U_op,
exact path_connected_space_iff_connected_space
end
|
bf753bf14dbce4381c5b1f9e526df5cc03f2497b | 54deab7025df5d2df4573383df7e1e5497b7a2c2 | /data/seq/parallel.lean | 4e2a56f85e98c5bcac6dd8122c0d6905b17faec5 | [
"Apache-2.0"
] | permissive | HGldJ1966/mathlib | f8daac93a5b4ae805cfb0ecebac21a9ce9469009 | c5c5b504b918a6c5e91e372ee29ed754b0513e85 | refs/heads/master | 1,611,340,395,683 | 1,503,040,489,000 | 1,503,040,489,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,248 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Parallel computation of a computable sequence of computations by
a diagonal enumeration.
The important theorems of this operation are proven as
terminates_parallel and exists_of_mem_parallel.
(This operation is nondeterministic in the sense that it does not
honor sequence equivalence (irrelevance of computation time).)
-/
import data.seq.wseq
universes u v
namespace computation
open wseq
variables {α : Type u} {β : Type v}
def parallel.aux2 : list (computation α) → α ⊕ list (computation α) :=
list.foldr (λc o, match o with
| sum.inl a := sum.inl a
| sum.inr ls := rmap (λ c', c' :: ls) (destruct c)
end) (sum.inr [])
def parallel.aux1 : list (computation α) × wseq (computation α) →
α ⊕ list (computation α) × wseq (computation α)
| (l, S) := rmap (λ l', match seq.destruct S with
| none := (l', nil)
| some (none, S') := (l', S')
| some (some c, S') := (c::l', S')
end) (parallel.aux2 l)
-- parallel computation of an infinite stream of computations,
-- taking the first result
def parallel (S : wseq (computation α)) : computation α :=
corec parallel.aux1 ([], S)
theorem terminates_parallel.aux : ∀ {l : list (computation α)} {S c},
c ∈ l → terminates c → terminates (corec parallel.aux1 (l, S)) :=
begin
have lem1 : ∀ l S, (∃ (a : α), parallel.aux2 l = sum.inl a) →
terminates (corec parallel.aux1 (l, S)),
{ intros l S e, cases e with a e,
have this : corec parallel.aux1 (l, S) = return a,
{ apply destruct_eq_ret, simp [parallel.aux1], rw e, simp [rmap] },
rw this, apply_instance },
intros l S c m T, revert l S,
apply @terminates_rec_on _ _ c T _ _,
{ intros a l S m, apply lem1,
revert m, induction l with c l IH; intro; simp at m, { contradiction },
cases m with e m,
{ rw ←e, simp [parallel.aux2],
cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a' ls,
exacts [⟨a', rfl⟩, ⟨a, rfl⟩] },
{ cases IH m with a' e,
simp [parallel.aux2], simp [parallel.aux2] at e,
rw e, exact ⟨a', rfl⟩ } },
{ intros s IH l S m,
have H1 : ∀ l', parallel.aux2 l = sum.inr l' → s ∈ l',
{ revert m, induction l with c l IH';
intros m l' e'; simp at m, { contradiction },
cases m with e m; simp [parallel.aux2] at e',
{ rw ←e at e',
cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a' ls;
injection e' with e', rw ←e', simp },
{ ginduction list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with e a' ls;
rw e at e', { contradiction },
have := IH' m _ e,
simp [parallel.aux2] at e',
cases destruct c; injection e',
rw ←h, simp [this] } },
ginduction parallel.aux2 l with h a l',
{ exact lem1 _ _ ⟨a, h⟩ },
{ have H2 : corec parallel.aux1 (l, S) = think _,
{ apply destruct_eq_think,
simp [parallel.aux1],
rw h, simp [rmap] },
rw H2, apply @computation.think_terminates _ _ _,
have := H1 _ h,
cases seq.destruct S,
{ simp [parallel.aux1], apply IH, exact this },
{ cases a with c S',
cases c with c; simp [parallel.aux1]; apply IH; simp [this] } } }
end
theorem terminates_parallel {S : wseq (computation α)}
{c} (h : c ∈ S) [T : terminates c] : terminates (parallel S) :=
suffices ∀ n (l : list (computation α)) S c,
c ∈ l ∨ some (some c) = seq.nth S n →
terminates c → terminates (corec parallel.aux1 (l, S)),
from let ⟨n, h⟩ := h in this n [] S c (or.inr h) T,
begin
intro n, induction n with n IH; intros l S c o T,
{ cases o, { exact terminates_parallel.aux a T },
have H : seq.destruct S = some (some c, _),
{ unfold seq.destruct has_map.map, rw ←a, simp [option_map, option_bind] },
ginduction (parallel.aux2 l) with h a l';
have C : corec parallel.aux1 (l, S) = _,
{ apply destruct_eq_ret, simp [parallel.aux1], rw [h], simp [rmap] },
{ rw C, apply_instance },
{ apply destruct_eq_think, simp [parallel.aux1], rw [h, H], simp [rmap] },
{ rw C, apply @computation.think_terminates _ _ _,
apply terminates_parallel.aux _ T, simp } },
{ cases o, { exact terminates_parallel.aux a T },
ginduction (parallel.aux2 l) with h a l';
have C : corec parallel.aux1 (l, S) = _,
{ apply destruct_eq_ret, simp [parallel.aux1], rw [h], simp [rmap] },
{ rw C, apply_instance },
{ apply destruct_eq_think, simp [parallel.aux1], rw [h], simp [rmap] },
{ rw C, apply @computation.think_terminates _ _ _,
have TT : ∀ l', terminates (corec parallel.aux1 (l', S.tail)),
{ intro, apply IH _ _ _ (or.inr _) T, rw a, cases S with f al, refl },
ginduction seq.nth S 0 with e o,
{ have D : seq.destruct S = none,
{ dsimp [seq.destruct], rw e, refl },
rw D, simp [parallel.aux1], have TT := TT l',
rwa [seq.destruct_eq_nil D, seq.tail_nil] at TT },
{ have D : seq.destruct S = some (o, S.tail),
{ dsimp [seq.destruct], rw e, refl },
rw D, cases o with c; simp [parallel.aux1, TT] } } }
end
theorem exists_of_mem_parallel {S : wseq (computation α)}
{a} (h : a ∈ parallel S) : ∃ c ∈ S, a ∈ c :=
suffices ∀ C, a ∈ C → ∀ (l : list (computation α)) S,
corec parallel.aux1 (l, S) = C → ∃ c, (c ∈ l ∨ c ∈ S) ∧ a ∈ c,
from let ⟨c, h1, h2⟩ := this _ h [] S rfl in ⟨c, h1.resolve_left id, h2⟩,
begin
let F : list (computation α) → α ⊕ list (computation α) → Prop,
{ intros l a, cases a with a l',
exact ∃ c ∈ l, a ∈ c,
exact ∀ a', (∃ c ∈ l', a' ∈ c) → (∃ c ∈ l, a' ∈ c) },
have lem1 : ∀ (l : list (computation α)), F l (parallel.aux2 l),
{ intro l, induction l with c l IH; simp [parallel.aux2],
{ intros a h, cases h with c h, cases h with hn,
exact false.elim hn },
{ simp [parallel.aux2] at IH,
cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l with a ls;
simp [parallel.aux2],
{ cases IH with c' cl, cases cl with cl ac,
refine ⟨c', or.inr cl, ac⟩ },
{ ginduction destruct c with h a c'; simp [rmap],
{ refine ⟨c, list.mem_cons_self _ _, _⟩,
rw destruct_eq_ret h,
apply ret_mem },
{ intros a' h, cases h with d h, cases h with dm ad,
simp at dm, cases dm with e dl,
{ rw e at ad, refine ⟨c, list.mem_cons_self _ _, _⟩,
rw destruct_eq_think h,
exact think_mem ad },
{ cases IH a' ⟨d, dl, ad⟩ with d dm, cases dm with dm ad,
exact ⟨d, or.inr dm, ad⟩ } } } } },
intros C aC, refine mem_rec_on aC _ (λ C' IH, _);
intros l S e; have e' := congr_arg destruct e; have := lem1 l;
simp [parallel.aux1] at e'; cases parallel.aux2 l with a' l'; injection e',
{ rw h at this, cases this with c cl, cases cl with cl ac,
exact ⟨c, or.inl cl, ac⟩ },
{ ginduction seq.destruct S with e a; rw e at h,
{ exact let ⟨d, o, ad⟩ := IH _ _ h,
⟨c, cl, ac⟩ := this a ⟨d, o.resolve_right (not_mem_nil _), ad⟩ in
⟨c, or.inl cl, ac⟩ },
{ cases a with o S', cases o with c; simp [parallel.aux1] at h;
cases IH _ _ h with d dm; cases dm with o ad; cases o with dl dS',
{ exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ in ⟨c, or.inl cl, ac⟩ },
{ refine ⟨d, or.inr _, ad⟩,
rw seq.destruct_eq_cons e,
exact seq.mem_cons_of_mem _ dS' },
{ simp at dl, cases dl with dc dl,
{ rw dc at ad, refine ⟨c, or.inr _, ad⟩,
rw seq.destruct_eq_cons e,
apply seq.mem_cons },
{ exact let ⟨c, cl, ac⟩ := this a ⟨d, dl, ad⟩ in ⟨c, or.inl cl, ac⟩ } },
{ refine ⟨d, or.inr _, ad⟩,
rw seq.destruct_eq_cons e,
exact seq.mem_cons_of_mem _ dS' } } }
end
theorem map_parallel (f : α → β) (S) : map f (parallel S) = parallel (S.map (map f)) :=
begin
refine eq_of_bisim (λ c1 c2, ∃ l S,
c1 = map f (corec parallel.aux1 (l, S)) ∧
c2 = corec parallel.aux1 (l.map (map f), S.map (map f))) _ ⟨[], S, rfl, rfl⟩,
intros c1 c2 h, exact match c1, c2, h with ._, ._, ⟨l, S, rfl, rfl⟩ := begin
clear _match,
have : parallel.aux2 (l.map (map f)) = lmap f (rmap (list.map (map f)) (parallel.aux2 l)),
{ simp [parallel.aux2], induction l with c l IH; simp, rw [IH], dsimp [function.comp],
cases list.foldr parallel.aux2._match_1 (sum.inr list.nil) l; simp [parallel.aux2],
cases destruct c; simp },
simp [parallel.aux1], rw this, cases parallel.aux2 l with a l'; simp,
apply S.cases_on _ (λ c S, _) (λ S, _); simp; simp [parallel.aux1];
exact ⟨_, _, rfl, rfl⟩
end end
end
theorem parallel_empty (S : wseq (computation α)) (h : S.head ~> none) :
parallel S = empty _ :=
eq_empty_of_not_terminates $ λ ⟨a, m⟩,
let ⟨c, cs, ac⟩ := exists_of_mem_parallel m,
⟨n, nm⟩ := exists_nth_of_mem cs,
⟨c', h'⟩ := head_some_of_nth_some nm in by injection h h'
-- The reason this isn't trivial from exists_of_mem_parallel is because it eliminates to Sort
def parallel_rec {S : wseq (computation α)} (C : α → Sort v)
(H : ∀ s ∈ S, ∀ a ∈ s, C a) {a} (h : a ∈ parallel S) : C a :=
begin
let T : wseq (computation (α × computation α)) :=
S.map (λc, c.map (λ a, (a, c))),
have : S = T.map (map (λ c, c.1)),
{ rw [←wseq.map_comp], refine (wseq.map_id _).symm.trans (congr_arg (λ f, wseq.map f S) _),
apply funext, intro c, dsimp [id, function.comp], rw [←map_comp], exact (map_id _).symm },
have pe := congr_arg parallel this, rw ←map_parallel at pe,
have h' := h, rw pe at h',
have : terminates (parallel T) := (terminates_map_iff _ _).1 ⟨_, h'⟩,
ginduction get (parallel T) with e a' c,
have : a ∈ c ∧ c ∈ S,
{ cases exists_of_mem_map h' with d h, cases h with dT cd,
rw get_eq_of_mem _ dT at e, cases e, dsimp at cd, cases cd,
cases exists_of_mem_parallel dT with d' h, cases h with dT' ad',
cases wseq.exists_of_mem_map dT' with c' h, cases h with cs' e',
rw ←e' at ad',
cases exists_of_mem_map ad' with a' h, cases h with ac' e', injection e' with i1 i2,
constructor, rwa [i1, i2] at ac', rwa i2 at cs' },
cases this with ac cs, apply H _ cs _ ac
end
theorem parallel_promises {S : wseq (computation α)} {a}
(H : ∀ s ∈ S, s ~> a) : parallel S ~> a :=
λ a' ma', let ⟨c, cs, ac⟩ := exists_of_mem_parallel ma' in H _ cs ac
theorem mem_parallel {S : wseq (computation α)} {a}
(H : ∀ s ∈ S, s ~> a) {c} (cs : c ∈ S) (ac : a ∈ c) : a ∈ parallel S :=
by have := terminates_of_mem ac; have := terminates_parallel cs;
exact mem_of_promises _ (parallel_promises H)
theorem parallel_congr_lem {S T : wseq (computation α)} {a}
(H : S.lift_rel equiv T) : (∀ s ∈ S, s ~> a) ↔ (∀ t ∈ T, t ~> a) :=
⟨λ h1 t tT, let ⟨s, sS, se⟩ := wseq.exists_of_lift_rel_right H tT in
(promises_congr se _).1 (h1 _ sS),
λ h2 s sS, let ⟨t, tT, se⟩ := wseq.exists_of_lift_rel_left H sS in
(promises_congr se _).2 (h2 _ tT)⟩
-- The parallel operation is only deterministic when all computation paths lead to the same value
theorem parallel_congr_left {S T : wseq (computation α)} {a}
(h1 : ∀ s ∈ S, s ~> a) (H : S.lift_rel equiv T) : parallel S ~ parallel T :=
let h2 := (parallel_congr_lem H).1 h1 in
λ a', ⟨λh, by have aa := parallel_promises h1 h; rw ←aa; rw ←aa at h; exact
let ⟨s, sS, as⟩ := exists_of_mem_parallel h,
⟨t, tT, st⟩ := wseq.exists_of_lift_rel_left H sS,
aT := (st _).1 as in mem_parallel h2 tT aT,
λh, by have aa := parallel_promises h2 h; rw ←aa; rw ←aa at h; exact
let ⟨s, sS, as⟩ := exists_of_mem_parallel h,
⟨t, tT, st⟩ := wseq.exists_of_lift_rel_right H sS,
aT := (st _).2 as in mem_parallel h1 tT aT⟩
theorem parallel_congr_right {S T : wseq (computation α)} {a}
(h2 : ∀ t ∈ T, t ~> a) (H : S.lift_rel equiv T) : parallel S ~ parallel T :=
parallel_congr_left ((parallel_congr_lem H).2 h2) H
end computation
|
4d28025347e88ae91277cd801edace80991c0c23 | 8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3 | /src/linear_algebra/matrix/trace.lean | 1d4ee1067a146fbfb2cdf0161841b3587f0e6163 | [
"Apache-2.0"
] | permissive | troyjlee/mathlib | e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5 | 45e7eb8447555247246e3fe91c87066506c14875 | refs/heads/master | 1,689,248,035,046 | 1,629,470,528,000 | 1,629,470,528,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,338 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import data.matrix.basic
/-!
# Trace of a matrix
This file defines the trace of a matrix, the linear map
sending a matrix to the sum of its diagonal entries.
See also `linear_algebra.trace` for the trace of an endomorphism.
## Tags
matrix, trace, diagonal
-/
open_locale big_operators
open_locale matrix
namespace matrix
section trace
universes u v w
variables {m : Type*} [fintype m] (n : Type*) [fintype n]
variables (R : Type*) (M : Type*) [semiring R] [add_comm_monoid M] [module R M]
/--
The diagonal of a square matrix.
-/
def diag : (matrix n n M) →ₗ[R] n → M :=
{ to_fun := λ A i, A i i,
map_add' := by { intros, ext, refl, },
map_smul' := by { intros, ext, refl, } }
variables {n} {R} {M}
@[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl
@[simp] lemma diag_one [decidable_eq n] :
diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_apply_eq] }
@[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl
variables (n) (R) (M)
/--
The trace of a square matrix.
-/
def trace : (matrix n n M) →ₗ[R] M :=
{ to_fun := λ A, ∑ i, diag n R M A i,
map_add' := by { intros, apply finset.sum_add_distrib, },
map_smul' := by { intros, simp [finset.smul_sum], } }
variables {n} {R} {M}
@[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = ∑ i, diag n R M A i := rfl
lemma trace_apply (A : matrix n n M) : trace n R M A = ∑ i, A i i := rfl
@[simp] lemma trace_one [decidable_eq n] :
trace n R R 1 = fintype.card n :=
have h : trace n R R 1 = ∑ i, diag n R R 1 i := rfl,
by simp_rw [h, diag_one, finset.sum_const, nsmul_one]; refl
@[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl
@[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) :
trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm
lemma trace_mul_comm {S : Type v} [comm_semiring S] (A : matrix m n S) (B : matrix n m S) :
trace n S S (B ⬝ A) = trace m S S (A ⬝ B) :=
by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul]
end trace
end matrix
|
221c250d8e19dad05288fc3fe5f111931737126f | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/simp26.lean | 1bb309a90e1619f9ac81e6e0dfb7c595664fec01 | [
"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 | 472 | lean | rewrite_set simple
add_rewrite eq_id imp_truel imp_truer Nat::add_zeror : simple
variables a b : Nat
variable f : (Nat → Nat) → Nat
(*
local t = parse_lean('λ x, a + 0 = 1 → x > f (λ y, y + a)')
local t2, pr = simplify(t, "simple")
print(t2)
print(pr)
get_environment():type_check(pr)
*)
(*
local t = parse_lean('λ x, a + 0 = 1 → x = 2 → x > f (λ y, y + a + x)')
local t2, pr = simplify(t, "simple")
print(t2)
print(pr)
get_environment():type_check(pr)
*)
|
3782ecf5d311221f212708bfc7130f5453b229e6 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/run/have4.lean | 9d3d899316f575e54f20842a889bcb6d179cf03a | [
"Apache-2.0"
] | permissive | jcarlson23/lean | b00098763291397e0ac76b37a2dd96bc013bd247 | 8de88701247f54d325edd46c0eed57aeacb64baf | refs/heads/master | 1,611,571,813,719 | 1,497,020,963,000 | 1,497,021,515,000 | 93,882,536 | 1 | 0 | null | 1,497,029,896,000 | 1,497,029,896,000 | null | UTF-8 | Lean | false | false | 241 | lean | prelude
definition Prop : Type.{1} := Type.{0}
constants a b c : Prop
axiom Ha : a
axiom Hb : b
axiom Hc : c
#check have H1 : a, from Ha,
then have H2 : a, from H1,
have H3 : a, from H2,
then have H4 : a, from H3,
H4
|
130a96245c0019a312b364d10a8c5dae89b5d4ad | 8e31b9e0d8cec76b5aa1e60a240bbd557d01047c | /src/simplex2.lean | 438875b719625e1b39b3d5d77c1edc5c2f12e9e0 | [] | no_license | ChrisHughes24/LP | 7bdd62cb648461c67246457f3ddcb9518226dd49 | e3ed64c2d1f642696104584e74ae7226d8e916de | refs/heads/master | 1,685,642,642,858 | 1,578,070,602,000 | 1,578,070,602,000 | 195,268,102 | 4 | 3 | null | 1,569,229,518,000 | 1,562,255,287,000 | Lean | UTF-8 | Lean | false | false | 44,302 | lean | import tableau order.lexicographic
open matrix fintype finset function pequiv partition
variables {m n : ℕ}
local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ
local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ
local infix ` ⬝ `:70 := matrix.mul
local postfix `ᵀ` : 1500 := transpose
namespace tableau
def pivot_col (T : tableau m n) (obj : fin m) : option (fin n) :=
option.cases_on
(fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted
∧ c ∉ T.dead))
(((list.fin_range n).filter (λ c : fin n, 0 < T.to_matrix obj c ∧ c ∉ T.dead)).argmin
T.to_partition.colg)
some
def to_lex (T : tableau m n) (c : fin n) (r' : fin m) : lex ℚ (fin (m + n)) :=
(abs (T.const r' 0 / T.to_matrix r' c), T.to_partition.rowg r')
lemma to_lex_le_iff (T : tableau m n) (c : fin n) (i i' : fin m) :
to_lex T c i ≤ to_lex T c i' ↔
abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) ∨
(abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) ∧
T.to_partition.rowg i ≤ T.to_partition.rowg i') :=
prod.lex_def _ _
def pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) :=
let l := (list.fin_range m).filter (λ i : fin m, obj ≠ i ∧ T.to_partition.rowg i ∈ T.restricted
∧ T.to_matrix obj c < 0) in
list.argmin (to_lex T c) l
lemma pivot_col_spec {T : tableau m n} {obj : fin m} {c : fin n} :
c ∈ pivot_col T obj → ((T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted)
∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c ∉ T.dead :=
begin
dsimp only [pivot_col],
cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted
∧ c ∉ T.dead),
{ have := not_and.1 (fin.find_eq_none_iff.1 h c) ∘ ne_of_gt,
simp only [list.argmin_eq_some_iff, option.mem_def, list.mem_filter, list.mem_fin_range, gt]
at * {contextual := tt},
tauto },
{ finish [fin.find_eq_some_iff] }
end
lemma nonpos_of_lt_pivot_col {T : tableau m n} {obj : fin m} {c j : fin n}
(hc : c ∈ pivot_col T obj) (hcres : T.to_partition.colg c ∈ T.restricted)
(hdead : j ∉ T.dead) (hjc : T.to_partition.colg j < T.to_partition.colg c) :
T.to_matrix obj j ≤ 0 :=
begin
rw [pivot_col] at hc,
cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted
∧ c ∉ T.dead),
{ rw h at hc,
refine le_of_not_lt (λ hj0, _),
exact not_le_of_gt hjc ((list.mem_argmin_iff.1 hc).2.1 j
(list.mem_filter.2 (by simp [hj0, hdead]))) },
{ rw h at hc,
simp [*, fin.find_eq_some_iff] at * }
end
lemma pivot_col_eq_none_aux {T : tableau m n} {obj : fin m} (hT : T.feasible) {c : fin n} :
pivot_col T obj = none → c ∉ T.dead →
((T.to_matrix obj c = 0 ∧ T.to_partition.colg c ∉ T.restricted)
∨ (T.to_matrix obj c ≤ 0 ∧ T.to_partition.colg c ∈ T.restricted)) :=
begin
simp only [pivot_col],
cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted
∧ c ∉ T.dead),
{ simp only [list.filter_eq_nil, list.argmin_eq_none, not_and', list.mem_fin_range,
true_implies_iff, not_lt, fin.find_eq_none_iff, and_imp, not_not] at *,
assume hnonneg hdead,
by_cases hres : T.to_partition.colg c ∈ T.restricted; simp * at * },
{ simp }
end
lemma pivot_col_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible)
(h : pivot_col T obj = none) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) :=
is_optimal_of_col_zero hT
(λ j hj, begin
have := pivot_col_eq_none_aux hT h hj,
finish [lt_irrefl]
end)
lemma pivot_row_spec {T : tableau m n} {obj i : fin m} {c : fin n} :
i ∈ pivot_row T obj c →
obj ≠ i ∧ T.to_partition.rowg i ∈ T.restricted ∧
T.to_matrix obj c / T.to_matrix i c < 0 ∧
(∀ i' : fin m, obj ≠ i' → T.to_partition.rowg i' ∈ T.restricted →
T.to_matrix obj c < 0 →
abs (T.const i 0 / T.to_matrix i c) ≤ abs (T.const i' 0 / T.to_matrix i' c)) :=
begin
simp only [list.mem_filter, pivot_row, option.mem_def,
list.argmin_eq_some_iff, list.mem_fin_range, true_and, and_imp],
simp only [to_lex_le_iff],
intros hor hres hr0 h _,
simp only [*, true_and, ne.def, not_false_iff],
intros i' hoi' hres' hi0',
cases h i' hoi' hres' hi0',
{ exact le_of_lt (by assumption) },
{ exact le_of_eq (by tauto) }
end
lemma nonneg_of_lt_pivot_row {T : tableau m n} {obj : fin m} {i i' : fin m} {c : fin n}
(hc0 : 0 < T.to_matrix obj c) (hres : T.to_partition.rowg i' ∈ T.restricted)
(hc : c ∈ pivot_col T obj) (hrow : i ∈ pivot_row T obj c)
(hconst : T.const i' 0 = 0)
(hjc : T.to_partition.rowg i' < T.to_partition.rowg i) :
0 ≤ T.to_matrix i' c :=
if hobj : obj = i' then le_of_lt $ hobj ▸ hc0
else
le_of_not_gt $ λ hic, not_le_of_lt hjc
begin
have := (list.argmin_eq_some_iff.1 hrow).2.1 i'
(list.mem_filter.2 ⟨list.mem_fin_range _, hobj, hres, div_neg_of_pos_of_neg hc0 hic⟩),
simp [hconst, not_lt_of_ge (abs_nonneg _), *, to_lex_le_iff] at *
end
lemma ne_zero_of_mem_pivot_row {T : tableau m n} {obj i : fin m} {c : fin n}
(hrow : i ∈ pivot_row T obj c) : T.to_matrix i c ≠ 0 :=
assume hrc, by simpa [lt_irrefl, hrc] using pivot_row_spec hrow
lemma ne_zero_of_mem_pivot_col {T : tableau m n} {obj : fin m} {c : fin n}
(hc : c ∈ pivot_col T obj) : T.to_matrix obj c ≠ 0 :=
λ h, by simpa [h, lt_irrefl] using pivot_col_spec hc
lemma pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n}
(hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) :
∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix i c :=
by simpa [pivot_row, list.filter_eq_nil] using hrow
lemma pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible)
(hrow : pivot_row T obj c = none) (hs : c ∈ pivot_col T obj) :
T.is_unbounded_above (T.to_partition.rowg obj) :=
have hrow : ∀ i, obj ≠ i → T.to_partition.rowg i ∈ T.restricted →
0 ≤ T.to_matrix obj c / T.to_matrix i c,
from pivot_row_eq_none_aux hrow hs,
have hc : ((T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted)
∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) ∧ c ∉ T.dead,
from pivot_col_spec hs,
have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc,
(lt_or_gt_of_ne hToc).elim
(λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c
(hc.1.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim)) hc.2
(λ i hi, classical.by_cases
(λ hoi : obj = i, le_of_lt (hoi ▸ hToc))
(λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc))
hToc)
(λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c
(λ i hi, classical.by_cases
(λ hoi : obj = i, le_of_lt (hoi ▸ hToc))
(λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc))
hc.2 hToc)
def feasible_of_mem_pivot_row_and_col {T : tableau m n} {obj : fin m} (hT : T.feasible) {c}
(hc : c ∈ pivot_col T obj) {i} (hr : i ∈ pivot_row T obj c) :
feasible (T.pivot i c) :=
begin
have := pivot_col_spec hc,
have := pivot_row_spec hr,
have := @feasible_simplex_pivot _ _ _ obj hT i c,
tauto
end
section blands_rule
local attribute [instance, priority 0] classical.dec
variable (obj : fin m)
def fickle (T T' : tableau m n) (v : fin (m + n)) : Prop :=
T.to_partition.rowp v ≠ T'.to_partition.rowp v ∨
T.to_partition.colp v ≠ T'.to_partition.colp v
lemma fickle_symm {T T' : tableau m n} {v : fin (m + n)} :
fickle T T' v ↔ fickle T' T v :=
by simp [fickle, eq_comm]
lemma fickle_colg_iff_ne {T T' : tableau m n} {j : fin n} :
fickle T T' (T.to_partition.colg j) ↔
T.to_partition.colg j ≠ T'.to_partition.colg j :=
⟨λ h h', h.elim (by rw [rowp_colg_eq_none, h', rowp_colg_eq_none]; simp)
(by rw [colp_colg, h', colp_colg]; simp),
λ h, or.inr $ λ h', h begin
have : T'.to_partition.colp (T.to_partition.colg j) = some j,
{ simpa [eq_comm] using h' },
rwa [← pequiv.eq_some_iff, colp_symm_eq_some_colg, option.some_inj, eq_comm] at this
end⟩
lemma fickle_rowg_iff_ne {T T' : tableau m n} {i : fin m} :
fickle T T' (T.to_partition.rowg i) ↔
T.to_partition.rowg i ≠ T'.to_partition.rowg i :=
⟨λ h h', h.elim (by rw [rowp_rowg, h', rowp_rowg]; simp)
(by rw [colp_rowg_eq_none, h', colp_rowg_eq_none]; simp),
λ h, or.inl $ λ h', h begin
have : T'.to_partition.rowp (T.to_partition.rowg i) = some i,
{ simpa [eq_comm] using h' },
rwa [← pequiv.eq_some_iff, rowp_symm_eq_some_rowg, option.some_inj, eq_comm] at this
end⟩
lemma not_unique_row_and_unique_col {T T' : tableau m n} {i c c'}
(hcobj0 : 0 < T.to_matrix obj c)
(hc'obj0 : 0 < T'.to_matrix obj c')
(hrc0 : T.to_matrix i c < 0)
(hflat : T.flat = T'.flat)
(hs : T.to_partition.rowg i = T'.to_partition.colg c')
(hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj)
(hfickle : ∀ i, (fickle T T' (T.to_partition.rowg i)) → T.const i 0 = 0)
(hobj : T.const obj 0 = T'.const obj 0)
(nonpos_of_colg_eq : ∀ j, j ≠ c' →
T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0)
(unique_col : ∀ j,
(fickle T' T (T'.to_partition.colg j)) → j ≠ c' → T'.to_matrix obj j ≤ 0)
(unique_row : ∀ i' ≠ i, T.const i' 0 = 0 → fickle T T' (T.to_partition.rowg i') →
0 ≤ T.to_matrix i' c) :
false :=
let objr := T.to_partition.rowg obj in
let x := λ y : ℚ, T.of_col (y • (single c 0).to_matrix) in
have hxflatT' : ∀ {y}, x y ∈ flat T', from hflat ▸ λ _, of_col_mem_flat _ _,
have hxrow : ∀ y i, x y (T.to_partition.rowg i) 0 = T.const i 0 + y * T.to_matrix i c,
by simp [x, of_col_single_rowg],
have hxcol : ∀ {y j}, j ≠ c → x y (T.to_partition.colg j) 0 = 0,
from λ y j hjc, by simp [x, of_col_colg, pequiv.to_matrix, single_apply_of_ne hjc.symm],
have hxcolc : ∀ {y}, x y (T.to_partition.colg c) 0 = y, by simp [x, of_col_colg, pequiv.to_matrix],
let c_star : fin (m + n) → ℚ := λ v, option.cases_on (T'.to_partition.colp v) 0
(T'.to_matrix obj) in
have hxobj : ∀ y, x y objr 0 = T.const obj 0 + y * T.to_matrix obj c, from λ y, hxrow _ _,
have hgetr : ∀ {y v}, c_star v * x y v 0 ≠ 0 → (T'.to_partition.colp v).is_some,
from λ y v, by cases h : T'.to_partition.colp v; dsimp [c_star]; rw h; simp,
have c_star_eq_get : ∀ {v} (hv : (T'.to_partition.colp v).is_some),
c_star v = T'.to_matrix obj (option.get hv),
from λ v hv, by dsimp only [c_star]; conv_lhs{rw [← option.some_get hv]}; refl,
have hsummmn : ∀ {y}, sum univ (λ j, T'.to_matrix obj j * x y (T'.to_partition.colg j) 0) =
sum univ (λ v, c_star v * x y v 0),
from λ y, sum_bij_ne_zero (λ j _ _, T'.to_partition.colg j) (λ _ _ _, mem_univ _)
(λ _ _ _ _ _ _ h, T'.to_partition.injective_colg h)
(λ v _ h0, ⟨option.get (hgetr h0), mem_univ _,
by rw [← c_star_eq_get (hgetr h0)]; simpa using h0, by simp⟩)
(λ _ _ h0, by dsimp [c_star]; rw [colp_colg]),
have hgetc : ∀ {y v}, c_star v * x y v 0 ≠ 0 → v ≠ T.to_partition.colg c →
(T.to_partition.rowp v).is_some,
from λ y v, (eq_rowg_or_colg T.to_partition v).elim
(λ ⟨i, hi⟩, by rw [hi, rowp_rowg]; simp)
(λ ⟨j, hj⟩ h0 hvc,
by rw [hj, hxcol (mt (congr_arg T.to_partition.colg) (hvc ∘ hj.trans)), mul_zero] at h0;
exact (h0 rfl).elim),
have hsummmnn : ∀ {y}, (univ.erase (T.to_partition.colg c)).sum (λ v, c_star v * x y v 0) =
univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0),
from λ y, eq.symm $ sum_bij_ne_zero (λ i _ _, T.to_partition.rowg i) (by simp)
(λ _ _ _ _ _ _ h, T.to_partition.injective_rowg h)
(λ v hvc h0, ⟨option.get (hgetc h0 (mem_erase.1 hvc).1), mem_univ _, by simpa using h0⟩)
(by intros; refl),
have hsumm : ∀ {y}, univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0) =
univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) +
y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
from λ y, by simp only [hxrow, mul_add, add_mul, sum_add_distrib, mul_assoc,
mul_left_comm _ y, mul_sum.symm],
have hxobj' : ∀ y, x y objr 0 = univ.sum (λ v, c_star v * x y v 0) + T'.const obj 0,
from λ y, by dsimp [objr]; rw [hrobj, mem_flat_iff.1 hxflatT', hsummmn],
have hy : ∀ {y}, y * T.to_matrix obj c = c_star (T.to_partition.colg c) * y +
univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) +
y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
from λ y, by rw [← add_left_inj (T.const obj 0), ← hxobj, hxobj',
← insert_erase (mem_univ (T.to_partition.colg c)), sum_insert (not_mem_erase _ _),
hsummmnn, hobj, hsumm, hxcolc]; simp,
have hy' : ∀ (y), y * (T.to_matrix obj c - c_star (T.to_partition.colg c) -
univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c)) =
univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0),
from λ y, by rw [mul_sub, mul_sub, hy]; simp [mul_comm, mul_assoc, mul_left_comm],
have h0 : T.to_matrix obj c - c_star (T.to_partition.colg c) -
univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c) = 0,
by rw [← (domain.mul_left_inj (@one_ne_zero ℚ _)), hy', ← hy' 0, zero_mul, mul_zero],
have hcolnec' : T'.to_partition.colp (T.to_partition.colg c) ≠ some c',
from λ h,
by simpa [hs.symm] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd,
have eq_of_roweqc' : ∀ {i'}, T'.to_partition.colp (T.to_partition.rowg i') = some c' → i' = i,
from λ i' h, by simpa [hs.symm, T.to_partition.injective_rowg.eq_iff] using
congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd,
have sumpos : 0 < univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c),
by rw [← sub_eq_zero.1 h0]; exact add_pos_of_pos_of_nonneg hcobj0
(begin
simp only [c_star, neg_nonneg],
cases h : T'.to_partition.colp (T.to_partition.colg c) with j,
{ refl },
{ exact nonpos_of_colg_eq j (mt (congr_arg some) (h ▸ hcolnec'))
(by rw [← (option.eq_some_iff_get_eq.1 h).snd]; simp) }
end),
have hexi : ∃ i', 0 < c_star (T.to_partition.rowg i') * T.to_matrix i' c,
from imp_of_not_imp_not _ _ (by simpa using @sum_nonpos _ _ (@univ (fin m) _)
(λ i', c_star (T.to_partition.rowg i') * T.to_matrix i' c) _ _) sumpos,
let ⟨i', hi'⟩ := hexi in
have hi'0 : T.const i' 0 = 0, from hfickle i'
(fickle_rowg_iff_ne.2 $
λ h, by dsimp [c_star] at hi'; rw [h, colp_rowg_eq_none] at hi'; simpa [lt_irrefl] using hi'),
have hi'_some : (T'.to_partition.colp (T.to_partition.rowg i')).is_some,
from option.ne_none_iff_is_some.1 (λ h, by dsimp only [c_star] at hi'; rw h at hi';
simpa [lt_irrefl] using hi'),
have hi' : 0 < T'.to_matrix obj (option.get hi'_some) * T.to_matrix i' c,
by dsimp only [c_star] at hi'; rwa [← option.some_get hi'_some] at hi',
have hii : i' ≠ i, from λ hir, begin
have : option.get hi'_some = c', from T'.to_partition.injective_colg
(by rw [colg_get_colp_symm, ← hs, hir]),
rw [this, hir] at hi',
exact not_lt_of_gt hi' (mul_neg_of_pos_of_neg hc'obj0 hrc0)
end,
have hnec' : option.get hi'_some ≠ c',
from λ eq_c', hii $ @eq_of_roweqc' i' (eq_c' ▸ by simp),
have hic0 : T.to_matrix i' c < 0,
from neg_of_mul_pos_right hi' (unique_col _
(by rw [fickle_colg_iff_ne]; simp) hnec'),
not_le_of_gt hic0 (unique_row _ hii hi'0
(by rw [fickle_rowg_iff_ne, ← colg_get_colp_symm _ _ hi'_some]; exact colg_ne_rowg _ _ _))
inductive rel : tableau m n → tableau m n → Prop
| pivot : ∀ {T}, feasible T → ∀ {i c}, c ∈ pivot_col T obj →
i ∈ pivot_row T obj c → rel (T.pivot i c) T
| trans_pivot : ∀ {T₁ T₂ i c}, rel T₁ T₂ → c ∈ pivot_col T₁ obj →
i ∈ pivot_row T₁ obj c → rel (T₁.pivot i c) T₂
lemma feasible_of_rel_right {T T' : tableau m n} (h : rel obj T' T) : T.feasible :=
rel.rec_on h (by tauto) (by tauto)
lemma feasible_of_rel_left {T T' : tableau m n} (h : rel obj T' T) : T'.feasible :=
rel.rec_on h (λ _ hT _ _ hc hr, feasible_of_mem_pivot_row_and_col hT hc hr)
(λ _ _ _ _ _ hc hr hT, feasible_of_mem_pivot_row_and_col hT hc hr)
/-- Slightly stronger recursor than the default recursor -/
@[elab_as_eliminator]
lemma rel.rec_on' {obj : fin m} {C : tableau m n → tableau m n → Prop} {T T' : tableau m n}
(hrel : rel obj T T')
(hpivot : ∀ {T : tableau m n} {i : fin m} {c : fin n},
feasible T → c ∈ pivot_col T obj → i ∈ pivot_row T obj c → C (pivot T i c) T)
(hpivot_trans : ∀ {T₁ T₂ : tableau m n} {i : fin m} {c : fin n},
rel obj (T₁.pivot i c) T₁ → rel obj T₁ T₂ →
c ∈ pivot_col T₁ obj →
i ∈ pivot_row T₁ obj c → C (T₁.pivot i c) T₁ → C T₁ T₂ → C (pivot T₁ i c) T₂) :
C T T' :=
rel.rec_on hrel (λ T hT i c hc hr, hpivot hT hc hr) (λ T₁ T₂ i c hrelT₁₂ hc hr ih, hpivot_trans
(rel.pivot (feasible_of_rel_left obj hrelT₁₂) hc hr) hrelT₁₂ hc hr
(hpivot (feasible_of_rel_left obj hrelT₁₂) hc hr) ih)
lemma rel.trans {obj : fin m} {T₁ T₂ T₃ : tableau m n} (h₁₂ : rel obj T₁ T₂) :
rel obj T₂ T₃ → rel obj T₁ T₃ :=
rel.rec_on h₁₂
(λ T i c hT hc hr hrelT, rel.trans_pivot hrelT hc hr)
(λ T₁ T₂ i c hrelT₁₂ hc hr ih hrelT₂₃, rel.trans_pivot (ih hrelT₂₃) hc hr)
instance : is_trans (tableau m n) (rel obj) := ⟨@rel.trans _ _ obj⟩
lemma flat_eq_of_rel {T T' : tableau m n} (h : rel obj T' T) : flat T' = flat T :=
rel.rec_on' h (λ _ _ _ _ _ hr, flat_pivot (ne_zero_of_mem_pivot_row hr))
(λ _ _ _ _ _ _ _ _, eq.trans)
lemma rowg_obj_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.to_partition.rowg obj =
T'.to_partition.rowg obj :=
rel.rec_on' h (λ T i c hfT hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1])
(λ _ _ _ _ _ _ _ _, eq.trans)
lemma restricted_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.restricted = T'.restricted :=
rel.rec_on' h (λ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _ _, eq.trans)
lemma dead_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.dead = T'.dead :=
rel.rec_on' h (λ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _ _, eq.trans)
lemma dead_eq_of_rel_or_eq {T T' : tableau m n} (h : T = T' ∨ rel obj T T') : T.dead = T'.dead :=
h.elim (congr_arg _) $ dead_eq_of_rel _
lemma exists_mem_pivot_row_col_of_rel {T T' : tableau m n} (h : rel obj T' T) :
∃ i c, c ∈ pivot_col T obj ∧ i ∈ pivot_row T obj c :=
rel.rec_on' h (λ _ i c _ hc hr, ⟨i, c, hc, hr⟩) (λ _ _ _ _ _ _ _ _ _, id)
lemma exists_mem_pivot_row_of_rel {T T' : tableau m n} (h : rel obj T' T) {c : fin n}
(hc : c ∈ pivot_col T obj) : ∃ i, i ∈ pivot_row T obj c :=
let ⟨i, c', hc', hr⟩ := exists_mem_pivot_row_col_of_rel obj h in ⟨i, by simp * at *⟩
lemma exists_mem_pivot_col_of_fickle {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) {c : fin n} :
fickle T₁ T₂ (T₁.to_partition.colg c) →
∃ T₃, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧
T₃.to_partition.colg c = T₁.to_partition.colg c ∧
c ∈ pivot_col T₃ obj :=
rel.rec_on' h begin
assume T i c' hT hc' hr,
rw fickle_colg_iff_ne,
by_cases hcc : c = c',
{ subst hcc,
exact λ _, ⟨T, or.inl rfl, rel.pivot hT hc' hr, rfl, hc'⟩ },
{ simp [colg_swap_of_ne _ hcc] }
end
(λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂,
(imp_iff_not_or.1 ih₁₂).elim
(λ ih₁₂, (imp_iff_not_or.1 ihp₁).elim
(λ ihp₁ hf, (fickle_colg_iff_ne.1 hf (by simp [*, fickle_colg_iff_ne] at *)).elim)
(λ ⟨T₃, hT₃⟩ hf, ⟨T₃,
hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂) (λ h, or.inr $ h.trans hrel₁₂),
hT₃.2.1, hT₃.2.2.1.trans (by simpa [eq_comm, fickle_colg_iff_ne] using ih₁₂), hT₃.2.2.2⟩))
(λ ⟨T₃, hT₃⟩ hf, ⟨T₃, hT₃.1, hrelp₁.trans hT₃.2.1, hT₃.2.2⟩))
lemma exists_mem_pivot_row_of_fickle {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) (i : fin m) :
fickle T₁ T₂ (T₁.to_partition.rowg i) →
∃ (T₃ : tableau m n) c, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧
T₃.to_partition.rowg i = T₁.to_partition.rowg i ∧
c ∈ pivot_col T₃ obj ∧ i ∈ pivot_row T₃ obj c :=
rel.rec_on' h
begin
assume T i' c hT hc hi',
rw fickle_rowg_iff_ne,
by_cases hii : i = i',
{ subst hii,
exact λ _, ⟨T, c, or.inl rfl, rel.pivot hT hc hi', rfl, hc, hi'⟩ },
{ simp [rowg_swap_of_ne _ hii] }
end
(λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hrow ihp₁ ih₁₂,
(imp_iff_not_or.1 ih₁₂).elim
(λ ih₁₂, (imp_iff_not_or.1 ihp₁).elim
(λ ihp₁ hf, (fickle_rowg_iff_ne.1 hf (by simp [*, fickle_rowg_iff_ne] at *)).elim)
(λ ⟨T₃, c', hT₃⟩ hf, ⟨T₃, c', hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂)
(λ h, or.inr $ h.trans hrel₁₂),
hT₃.2.1,
hT₃.2.2.1.trans (by simpa [eq_comm, fickle_rowg_iff_ne] using ih₁₂),
by clear_aux_decl; tauto⟩))
(λ ⟨T₃, c', hT₃⟩ _, ⟨T₃, c', hT₃.1,
(rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hrow).trans hT₃.2.1, hT₃.2.2⟩))
lemma eq_or_rel_pivot_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) : ∀ {i j}
(hcol : j ∈ pivot_col T₂ obj) (hrow : i ∈ pivot_row T₂ obj j),
T₁ = T₂.pivot i j ∨ rel obj T₁ (T₂.pivot i j) :=
rel.rec_on' h (λ T i c hT hc hr r' c' hc' hr', by simp * at *)
(λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ r' c' hc' hr',
(ih₁₂ hc' hr').elim
(λ ih₁₂, or.inr $ ih₁₂ ▸ rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr)
(λ ih₁₂, or.inr $ (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans ih₁₂))
lemma exists_mem_pivot_col_of_mem_pivot_row {T : tableau m n} (hrelTT : rel obj T T)
{i c} (hc : c ∈ pivot_col T obj) (hrow : i ∈ pivot_row T obj c) :
∃ (T' : tableau m n), c ∈ pivot_col T' obj ∧ T'.to_partition.colg c =
T.to_partition.rowg i ∧ rel obj T' T ∧ rel obj T T' :=
have hrelTTp : rel obj T (T.pivot i c),
from (eq_or_rel_pivot_of_rel _ hrelTT hc hrow).elim (λ h, h ▸ hrelTT ) id,
let ⟨T', hT'⟩ := exists_mem_pivot_col_of_fickle obj hrelTTp $ fickle_colg_iff_ne.2 $
(show (T.pivot i c).to_partition.colg c ≠ T.to_partition.colg c, by simp) in
⟨T', hT'.2.2.2, by simp [hT'.2.2.1], hT'.1.elim
(λ h, h.symm ▸ rel.pivot (feasible_of_rel_left _ hrelTT) hc hrow)
(λ h, h.trans $ rel.pivot (feasible_of_rel_left _ hrelTT) hc hrow), hT'.2.1⟩
lemma exists_mem_pivot_col_of_fickle_row {T T' : tableau m n} (hrelTT' : rel obj T T') {i : fin m}
(hrelT'T : rel obj T' T) (hrow : fickle T T' (T.to_partition.rowg i)) :
∃ (T₃ : tableau m n) c, c ∈ pivot_col T₃ obj ∧ T₃.to_partition.colg c =
T.to_partition.rowg i ∧ rel obj T₃ T ∧ rel obj T T₃ :=
let ⟨T₃, c, hT₃, hrelT₃T, hrow₃, hc, hr⟩ :=
exists_mem_pivot_row_of_fickle obj hrelT'T _ hrow in
let ⟨T₄, hT₄⟩ := exists_mem_pivot_col_of_mem_pivot_row obj
(show rel obj T₃ T₃, from hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T)
(λ h, h.trans $ hrelTT'.trans hrelT₃T)) hc hr in
⟨T₄, c, hT₄.1, hT₄.2.1.trans hrow₃, hT₄.2.2.1.trans $ hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T)
(λ h, h.trans $ hrelTT'.trans hrelT'T), hrelTT'.trans (hrelT₃T.trans hT₄.2.2.2)⟩
lemma const_obj_le_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) :
T₂.const obj 0 ≤ T₁.const obj 0 :=
rel.rec_on' h (λ T i c hT hc hr,
have hr' : _ := pivot_row_spec hr,
simplex_const_obj_le hT (by tauto) (by tauto))
(λ _ _ _ _ _ _ _ _ h₁ h₂, le_trans h₂ h₁)
lemma const_obj_eq_of_rel_of_rel {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂)
(h₂₁ : rel obj T₂ T₁) : T₁.const obj 0 = T₂.const obj 0 :=
le_antisymm (const_obj_le_of_rel _ h₂₁) (const_obj_le_of_rel _ h₁₂)
lemma const_eq_const_of_const_obj_eq {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂) :
∀ (hobj : T₁.const obj 0 = T₂.const obj 0) (i : fin m), T₁.const i 0 = T₂.const i 0 :=
rel.rec_on' h₁₂
(λ T i c hfT hc hrow hobj i',
have hr0 : T.const i 0 = 0, from const_eq_zero_of_const_obj_eq hfT
(ne_zero_of_mem_pivot_col hc) (ne_zero_of_mem_pivot_row hrow)
(pivot_row_spec hrow).1 hobj,
if hii : i' = i
then by simp [hii, hr0]
else by simp [const_pivot_of_ne _ hii, hr0])
(λ T₁ T₂ i c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ hobj i',
have hobjp : (pivot T₁ i c).const obj 0 = T₁.const obj 0,
from le_antisymm (hobj.symm ▸ const_obj_le_of_rel _ hrel₁₂)
(const_obj_le_of_rel _ hrelp₁),
by rw [ihp₁ hobjp, ih₁₂ (hobjp.symm.trans hobj)])
lemma const_eq_zero_of_fickle_of_rel_self {T T' : tableau m n} (hrelTT' : rel obj T T')
(hrelT'T : rel obj T' T) (i : fin m) (hrow : fickle T T' (T.to_partition.rowg i)) :
T.const i 0 = 0 :=
let ⟨T₃, c, hT₃₁, hT'₃, hrow₃, hc, hi⟩ := exists_mem_pivot_row_of_fickle obj hrelT'T _ hrow in
have T₃.const i 0 = 0, from const_eq_zero_of_const_obj_eq
(feasible_of_rel_right _ hT'₃) (ne_zero_of_mem_pivot_col hc)
(ne_zero_of_mem_pivot_row hi) (pivot_row_spec hi).1
(const_obj_eq_of_rel_of_rel _ (rel.pivot (feasible_of_rel_right _ hT'₃) hc hi)
((eq_or_rel_pivot_of_rel _ hT'₃ hc hi).elim
(λ h, h ▸ hT₃₁.elim (λ h, h.symm ▸ hrelTT') (λ h, h.trans hrelTT'))
(λ hrelT'p, hT₃₁.elim (λ h, h.symm ▸ hrelTT'.trans (h ▸ hrelT'p))
(λ h, h.trans $ hrelTT'.trans hrelT'p)))),
have hobj : T₃.const obj 0 = T.const obj 0,
from hT₃₁.elim (λ h, h ▸ rfl) (λ h, const_obj_eq_of_rel_of_rel _ h (hrelTT'.trans hT'₃)),
hT₃₁.elim (λ h, h ▸ this) (λ h, const_eq_const_of_const_obj_eq obj h hobj i ▸ this)
lemma colg_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T)
{c} (hc : c ∈ pivot_col T obj) : T.to_partition.colg c ∈ T.restricted :=
let ⟨i, hrow⟩ := exists_mem_pivot_row_of_rel obj hrelTT hc in
let ⟨T', c', hT', hrelTT', hrowcol, _, hi'⟩ := exists_mem_pivot_row_of_fickle obj
((eq_or_rel_pivot_of_rel _ hrelTT hc hrow).elim
(λ h, show rel obj T (T.pivot i c), from h ▸ hrelTT) id) _
(fickle_rowg_iff_ne.2 $
show (T.pivot i c).to_partition.rowg i ≠ T.to_partition.rowg i, by simp) in
(restricted_eq_of_rel _ hrelTT').symm ▸ by convert (pivot_row_spec hi').2.1; simp [hrowcol]
lemma eq_zero_of_not_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T)
{j} (hjres : T.to_partition.colg j ∉ T.restricted) (hdead : j ∉ T.dead) : T.to_matrix obj j = 0 :=
let ⟨r, c, hc, hr⟩ := exists_mem_pivot_row_col_of_rel obj hrelTT in
have hcres : T.to_partition.colg c ∈ T.restricted,
from colg_mem_restricted_of_rel_self obj hrelTT hc,
by_contradiction $ λ h0,
begin
simp [pivot_col] at hc,
cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted
∧ c ∉ T.dead),
{ simp [*, fin.find_eq_none_iff] at * },
{ rw h at hc, clear_aux_decl,
have := (fin.find_eq_some_iff.1 h).1,
simp * at * }
end
lemma rel.irrefl {obj : fin m} : ∀ (T : tableau m n), ¬ rel obj T T :=
λ T1 hrelT1,
let ⟨iT1 , cT1, hrT1, hcT1⟩ := exists_mem_pivot_row_col_of_rel obj hrelT1 in
let ⟨t, ht⟩ := finset.max_of_mem
(show T1.to_partition.colg cT1 ∈ univ.filter (λ v, ∃ (T' : tableau m n) (c : fin n),
rel obj T' T' ∧ c ∈ pivot_col T' obj ∧ T'.to_partition.colg c = v),
by simp only [true_and, mem_filter, mem_univ, exists_and_distrib_left];
exact ⟨T1, hrelT1, cT1, hrT1, rfl⟩) in
let ⟨_, T', c', hrelTT'', hcT', hct⟩ := finset.mem_filter.1 (finset.mem_of_max ht) in
have htmax : ∀ (s : fin (m + n)) (T : tableau m n),
rel obj T T → ∀ (j : fin n), pivot_col T obj = some j →
T.to_partition.colg j = s → s ≤ t,
by simpa using λ s (h : s ∈ _), finset.le_max_of_mem h ht,
let ⟨i, hiT'⟩ := exists_mem_pivot_row_of_rel obj hrelTT'' hcT' in
have hrelTT''p : rel obj T' (T'.pivot i c'),
from (eq_or_rel_pivot_of_rel obj hrelTT'' hcT' hiT').elim (λ h, h ▸ hrelTT'') id,
let ⟨T, c, hTT', hrelT'T, hT'Tr, hc, hr⟩ := exists_mem_pivot_row_of_fickle obj
hrelTT''p i (by rw fickle_symm; simp [fickle_colg_iff_ne]) in
have hfT' : feasible T', from feasible_of_rel_left _ hrelTT'',
have hfT : feasible T, from feasible_of_rel_right _ hrelT'T,
have hrelT'pT' : rel obj (T'.pivot i c') T', from rel.pivot hfT' hcT' hiT',
have hrelTT' : rel obj T T', from hTT'.elim (λ h, h.symm ▸ hrelT'pT') (λ h, h.trans hrelT'pT'),
have hrelTT : rel obj T T, from hrelTT'.trans hrelT'T,
have hc't : T.to_partition.colg c ≤ t, from htmax _ T hrelTT _ hc rfl,
have hoT'T : T'.const obj 0 = T.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelT'T hrelTT',
have hfickle : ∀ i, fickle T T' (T.to_partition.rowg i) → T.const i 0 = 0,
from const_eq_zero_of_fickle_of_rel_self obj hrelTT' hrelT'T,
have hobj : T.const obj 0 = T'.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelTT' hrelT'T,
have hflat : T.flat = T'.flat, from flat_eq_of_rel obj hrelTT',
have hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj, from rowg_obj_eq_of_rel _ hrelTT',
have hs : T.to_partition.rowg i = T'.to_partition.colg c', by simpa using hT'Tr,
have hc'res : T'.to_partition.colg c' ∈ T'.restricted,
from hs ▸ restricted_eq_of_rel _ hrelTT' ▸ (pivot_row_spec hr).2.1,
have hc'obj0 : 0 < T'.to_matrix obj c' ∧ c' ∉ T'.dead,
by simpa [hc'res] using pivot_col_spec hcT',
have hcres : T.to_partition.colg c ∈ T.restricted,
from colg_mem_restricted_of_rel_self obj hrelTT hc,
have hcobj0 : 0 < to_matrix T obj c ∧ c ∉ T.dead,
by simpa [hcres] using pivot_col_spec hc,
have hrc0 : T.to_matrix i c < 0,
from inv_neg'.1 $ neg_of_mul_neg_left (pivot_row_spec hr).2.2.1 (le_of_lt hcobj0.1),
have nonpos_of_colg_ne : ∀ j, (fickle T' T (T'.to_partition.colg j)) → j ≠ c' →
T'.to_matrix obj j ≤ 0,
from λ j hj hjc',
let ⟨T₃, hT₃⟩ := exists_mem_pivot_col_of_fickle obj hrelTT' hj in
nonpos_of_lt_pivot_col hcT' hc'res
(dead_eq_of_rel_or_eq obj hT₃.1 ▸ (pivot_col_spec hT₃.2.2.2).2)
(lt_of_le_of_ne
(hct.symm ▸ hT₃.2.2.1 ▸ htmax _ T₃ (hT₃.1.elim (λ h, h.symm ▸ hrelTT'')
(λ h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl)
(by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])),
have nonpos_of_colg_eq : ∀ j, j ≠ c' →
T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0,
from λ j hjc' hj,
if hjc : j = c
then by clear_aux_decl; subst hjc;
exact nonpos_of_lt_pivot_col hcT' hc'res
(by rw [dead_eq_of_rel obj hrelT'T]; tauto)
(lt_of_le_of_ne (hj.symm ▸ hct.symm ▸ hc't) (by simpa))
else nonpos_of_colg_ne _ (fickle_colg_iff_ne.2 $ by simpa [hj, eq_comm] using hjc) hjc',
have unique_row : ∀ i' ≠ i, T.const i' 0 = 0 → fickle T T' (T.to_partition.rowg i') →
0 ≤ T.to_matrix i' c,
from λ i' hii hi0 hrow,
let ⟨T₃, c₃, hc₃, hrow₃, hrelT₃T, hrelTT₃⟩ :=
exists_mem_pivot_col_of_fickle_row _ hrelTT' hrelT'T hrow in
have hrelT₃T₃ : rel obj T₃ T₃, from hrelT₃T.trans hrelTT₃,
nonneg_of_lt_pivot_row (by exact hcobj0.1)
(by rw [← hrow₃, ← restricted_eq_of_rel _ hrelT₃T];
exact colg_mem_restricted_of_rel_self _ hrelT₃T₃ hc₃) hc hr hi0
(lt_of_le_of_ne (by rw [hs, hct, ← hrow₃]; exact htmax _ _ hrelT₃T₃ _ hc₃ rfl)
(by simpa [fickle_rowg_iff_ne] using hrow)),
not_unique_row_and_unique_col obj hcobj0.1 hc'obj0.1 hrc0 hflat hs hrobj hfickle hobj
nonpos_of_colg_eq nonpos_of_colg_ne unique_row
noncomputable instance fintype_rel (T : tableau m n) : fintype {T' | rel obj T' T} :=
fintype.of_injective (λ T', T'.val.to_partition)
(λ T₁ T₂ h, subtype.eq $ tableau.ext
(by rw [flat_eq_of_rel _ T₁.2, flat_eq_of_rel _ T₂.2]) h
(by rw [dead_eq_of_rel _ T₁.2, dead_eq_of_rel _ T₂.2])
(by rw [restricted_eq_of_rel _ T₁.2, restricted_eq_of_rel _ T₂.2]))
lemma rel_wf (m n : ℕ) (obj : fin m): well_founded (@rel m n obj) :=
subrelation.wf
(show subrelation (@rel m n obj) (measure (λ T, fintype.card {T' | rel obj T' T})),
from assume T₁ T₂ h,
set.card_lt_card (set.ssubset_iff_subset_not_subset.2 ⟨λ T' hT', hT'.trans h,
not_forall_of_exists_not ⟨T₁, λ h', rel.irrefl _ (h' h)⟩⟩))
(measure_wf (λ T, fintype.card {T' | rel obj T' T}))
end blands_rule
inductive termination (n : ℕ) : Type
| while {} : termination
| unbounded (c : fin n) : termination
| optimal {} : termination
namespace termination
lemma injective_unbounded : function.injective (@unbounded n) :=
λ _ _ h, by injection h
@[simp] lemma unbounded_inj {c c' : fin n} : unbounded c = unbounded c' ↔ c = c' :=
injective_unbounded.eq_iff
end termination
open termination
instance {n : ℕ} : has_repr $ termination n :=
⟨λ t, termination.cases_on t
"while"
(λ c, "unbounded " ++ repr c)
"optimal"⟩
open termination
/-- The simplex algorithm -/
def simplex (w : tableau m n → bool) (obj : fin m) : Π (T : tableau m n) (hT : feasible T),
tableau m n × termination n
| T := λ hT, cond (w T)
(match pivot_col T obj, @feasible_of_mem_pivot_row_and_col _ _ _ obj hT,
@rel.pivot m n obj _ hT with
| none, hc, hrel := (T, optimal)
| some j, hc, hrel :=
match pivot_row T obj j, @hc _ rfl, (λ i, @hrel i j rfl) with
| none, hrow, hrel := (T, unbounded j)
| some i, hrow, hrel := have wf : rel obj (pivot T i j) T, from hrel _ rfl,
simplex (T.pivot i j) (hrow rfl)
end
end)
(T, while)
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩],
dec_tac := tactic.assumption}
lemma simplex_pivot {w : tableau m n → bool} {T : tableau m n} (hT : feasible T)
(hw : w T = tt) {obj : fin m} {i : fin m} {c : fin n}
(hc : c ∈ pivot_col T obj) (hr : i ∈ pivot_row T obj c) :
(T.pivot i c).simplex w obj (feasible_of_mem_pivot_row_and_col hT hc hr) =
T.simplex w obj hT :=
by conv_rhs { rw simplex };
simp [hw, show _ = _, from hr, show _ = _, from hc, simplex._match_1, simplex._match_2]
lemma simplex_spec_aux (w : tableau m n → bool) (obj : fin m) :
Π (T : tableau m n) (hT : feasible T),
((T.simplex w obj hT).2 = while ∧ w (T.simplex w obj hT).1 = ff) ∨
((T.simplex w obj hT).2 = optimal ∧ w (T.simplex w obj hT).1 = tt ∧
pivot_col (T.simplex w obj hT).1 obj = none) ∨
∃ c, ((T.simplex w obj hT).2 = unbounded c ∧ w (T.simplex w obj hT).1 = tt ∧
c ∈ pivot_col (T.simplex w obj hT).1 obj ∧
pivot_row (T.simplex w obj hT).1 obj c = none)
| T := λ hT,
begin
cases hw : w T,
{ rw simplex, simp [hw] },
{ cases hc : pivot_col T obj with c,
{ rw simplex, simp [hc, hw, simplex._match_1] },
{ cases hrow : pivot_row T obj c with i,
{ rw simplex,
simp [hrow, hc, hw, simplex._match_1, simplex._match_2] },
{ rw [← simplex_pivot hT hw hc hrow],
exact have wf : rel obj (T.pivot i c) T, from rel.pivot hT hc hrow,
simplex_spec_aux _ _ } } }
end
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩],
dec_tac := tactic.assumption}
lemma simplex_while_eq_ff {w : tableau m n → bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} (hw : w T = ff) : T.simplex w obj hT = (T, while) :=
by rw [simplex, hw]; refl
lemma simplex_pivot_col_eq_none {w : tableau m n → bool} {T : tableau m n} {hT : feasible T}
(hw : w T = tt) {obj : fin m} (hc : pivot_col T obj = none) :
T.simplex w obj hT = (T, optimal) :=
by rw simplex; simp [hc, hw, simplex._match_1]
lemma simplex_pivot_row_eq_none {w : tableau m n → bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} (hw : w T = tt) {c} (hc : c ∈ pivot_col T obj)
(hr : pivot_row T obj c = none) : T.simplex w obj hT = (T, unbounded c) :=
by rw simplex; simp [hw, show _ = _, from hc, hr, simplex._match_1, simplex._match_2]
lemma simplex_induction (P : tableau m n → Prop) (w : tableau m n → bool) (obj : fin m):
Π {T : tableau m n} (hT : feasible T) (h0 : P T)
(hpivot : ∀ {T' i c}, w T' = tt → c ∈ pivot_col T' obj → i ∈ pivot_row T' obj c
→ feasible T' → P T' → P (T'.pivot i c)),
P (T.simplex w obj hT).1
| T := λ hT h0 hpivot,
begin
cases hw : w T,
{ rwa [simplex_while_eq_ff hw] },
{ cases hc : pivot_col T obj with c,
{ rwa [simplex_pivot_col_eq_none hw hc] },
{ cases hrow : pivot_row T obj c with i,
{ rwa simplex_pivot_row_eq_none hw hc hrow },
{ rw [← simplex_pivot _ hw hc hrow],
exact have wf : rel obj (pivot T i c) T, from rel.pivot hT hc hrow,
simplex_induction (feasible_of_mem_pivot_row_and_col hT hc hrow)
(hpivot hw hc hrow hT h0) @hpivot } } }
end
using_well_founded {rel_tac := λ _ _, `[exact ⟨_, rel_wf m n obj⟩],
dec_tac := `[tauto]}
@[simp] lemma feasible_simplex {w : tableau m n → bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} : feasible (T.simplex w obj hT).1 :=
simplex_induction feasible _ _ hT hT
(λ _ _ _ _ hc hr _ hT', feasible_of_mem_pivot_row_and_col hT' hc hr)
@[simp] lemma simplex_simplex {w : tableau m n → bool} {T : tableau m n} {hT : feasible T}
{obj : fin m} : (T.simplex w obj hT).1.simplex w obj feasible_simplex = T.simplex w obj hT :=
simplex_induction (λ T', ∀ (hT' : feasible T'), T'.simplex w obj hT' = T.simplex w obj hT) w _ _
(λ _, rfl) (λ T' i c hw hc hr hT' ih hpivot, by rw [simplex_pivot hT' hw hc hr, ih]) _
/-- `simplex` does not move the row variable it is trying to maximise. -/
@[simp] lemma rowg_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.to_partition.rowg obj = T.to_partition.rowg obj :=
simplex_induction (λ T', T'.to_partition.rowg obj = T.to_partition.rowg obj) _ _ _ rfl
(λ T' i c hw hc hr, by simp [rowg_swap_of_ne _ (pivot_row_spec hr).1])
@[simp] lemma flat_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.flat = T.flat :=
simplex_induction (λ T', T'.flat = T.flat) w obj _ rfl
(λ T' i c hw hc hr hT' ih,
have T'.to_matrix i c ≠ 0,
from λ h, by simpa [h, lt_irrefl] using pivot_row_spec hr,
by rw [flat_pivot this, ih])
@[simp] lemma restricted_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.restricted = T.restricted :=
simplex_induction (λ T', T'.restricted = T.restricted) _ _ _ rfl (by simp { contextual := tt })
@[simp] lemma dead_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.dead = T.dead :=
simplex_induction (λ T', T'.dead = T.dead) _ _ _ rfl (by simp { contextual := tt })
@[simp] lemma res_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.res_set = T.res_set :=
simplex_induction (λ T', T'.res_set = T.res_set) w obj _ rfl
(λ T' i c hw hc hr, by simp [res_set_pivot (ne_zero_of_mem_pivot_row hr)] {contextual := tt})
@[simp] lemma dead_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.dead_set = T.dead_set :=
simplex_induction (λ T', T'.dead_set = T.dead_set) w obj _ rfl
(λ T' i c hw hc hr,
by simp [dead_set_pivot (ne_zero_of_mem_pivot_row hr) (pivot_col_spec hc).2] {contextual := tt})
@[simp] lemma sol_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool)
(obj : fin m) : (T.simplex w obj hT).1.sol_set = T.sol_set :=
by simp [sol_set_eq_res_set_inter_dead_set]
@[simp] lemma of_col_simplex_zero_mem_sol_set {w : tableau m n → bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.of_col 0 ∈ sol_set T :=
by rw [← sol_set_simplex, of_col_zero_mem_sol_set_iff]; exact feasible_simplex
@[simp] lemma of_col_simplex_rowg {w : tableau m n → bool} {T : tableau m n}
{hT : feasible T} {obj : fin m} (x : cvec n) :
(T.simplex w obj hT).1.of_col x (T.to_partition.rowg obj) =
((T.simplex w obj hT).1.to_matrix ⬝ x + (T.simplex w obj hT).1.const) obj :=
by rw [← of_col_rowg (T.simplex w obj hT).1 x obj, rowg_simplex]
@[simp] lemma is_unbounded_above_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool}
{obj : fin m} {v : fin (m + n)} : is_unbounded_above (T.simplex w obj hT).1 v ↔
is_unbounded_above T v := by simp [is_unbounded_above]
@[simp] lemma is_optimal_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool}
{obj : fin m} {x : cvec (m + n)} {v : fin (m + n)} : is_optimal (T.simplex w obj hT).1 x v ↔
is_optimal T x v := by simp [is_optimal]
lemma termination_eq_while_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool}
{obj : fin m} : (T.simplex w obj hT).2 = while ↔ w (T.simplex w obj hT).1 = ff :=
by have := simplex_spec_aux w obj T hT; finish
lemma termination_eq_optimal_iff_pivot_col_eq_none {T : tableau m n}
{hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔
w (T.simplex w obj hT).1 = tt ∧ pivot_col (T.simplex w obj hT).1 obj = none :=
by rcases simplex_spec_aux w obj T hT with _ | ⟨_, _, _⟩ | ⟨⟨_, _⟩, _, _, _, _⟩; simp * at *
lemma termination_eq_unbounded_iff_pivot_row_eq_none {T : tableau m n} {hT : feasible T}
{w : tableau m n → bool} {obj : fin m} {c : fin n} :
(T.simplex w obj hT).2 = unbounded c ↔
w (T.simplex w obj hT).1 = tt ∧ c ∈ pivot_col (T.simplex w obj hT).1 obj ∧
pivot_row (T.simplex w obj hT).1 obj c = none :=
by split; intros; rcases simplex_spec_aux w obj T hT with
_ | ⟨_, _, _⟩ | ⟨⟨⟨_, _⟩, _⟩, _, _, _, _⟩; simp * at *
lemma unbounded_of_termination_eq_unbounded {T : tableau m n} {hT : feasible T}
{w : tableau m n → bool} {obj : fin m} {c : fin n} : (T.simplex w obj hT).2 = unbounded c →
w (T.simplex w obj hT).1 = tt ∧
is_unbounded_above T (T.to_partition.rowg obj) :=
begin
rw termination_eq_unbounded_iff_pivot_row_eq_none,
rintros ⟨_, hc⟩,
simpa * using pivot_row_eq_none feasible_simplex hc.2 hc.1
end
lemma termination_eq_optimal_iff {T : tableau m n} {hT : feasible T}
{w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔
w (T.simplex w obj hT).1 = tt ∧
is_optimal T ((T.simplex w obj hT).1.of_col 0) (T.to_partition.rowg obj) :=
begin
rw [termination_eq_optimal_iff_pivot_col_eq_none],
split,
{ rintros ⟨_, hc⟩,
simpa * using pivot_col_eq_none feasible_simplex hc },
{ cases ht : (T.simplex w obj hT).2,
{ simp [*, termination_eq_while_iff] at * },
{ cases unbounded_of_termination_eq_unbounded ht,
simp [*, not_optimal_of_unbounded_above right] },
{ simp [*, termination_eq_optimal_iff_pivot_col_eq_none] at * } }
end
lemma termination_eq_unbounded_iff {T : tableau m n} {hT : feasible T}
{w : tableau m n → bool} {obj : fin m} {c : fin n}: (T.simplex w obj hT).2 = unbounded c ↔
w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj)
∧ c ∈ pivot_col (T.simplex w obj hT).1 obj :=
⟨λ hc, and.assoc.1 $ ⟨unbounded_of_termination_eq_unbounded hc,
(termination_eq_unbounded_iff_pivot_row_eq_none.1 hc).2.1⟩,
begin
have := @not_optimal_of_unbounded_above m n (T.simplex w obj hT).1 (T.to_partition.rowg obj)
((T.simplex w obj hT).1.of_col 0),
cases ht : (T.simplex w obj hT).2;
simp [termination_eq_optimal_iff, termination_eq_while_iff,
termination_eq_unbounded_iff_pivot_row_eq_none, *] at *
end⟩
end tableau
|
0c9903868800f64b2f0840d4a46446541ce7f3de | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/hom/equiv/units/group_with_zero.lean | e0144e693d766d4b6c9dca3e2855f0ed6d40804b | [
"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,336 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Callum Sutton, Yury Kudryashov
-/
import algebra.hom.equiv.units.basic
import algebra.group_with_zero.units.basic
/-!
# Multiplication by a nonzero element in a `group_with_zero` is a permutation.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {G : Type*}
namespace equiv
section group_with_zero
variables [group_with_zero G]
/-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the
underlying type. -/
@[simps {fully_applied := ff}]
protected def mul_left₀ (a : G) (ha : a ≠ 0) : perm G :=
(units.mk0 a ha).mul_left
lemma _root_.mul_left_bijective₀ (a : G) (ha : a ≠ 0) :
function.bijective ((*) a : G → G) :=
(equiv.mul_left₀ a ha).bijective
/-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the
underlying type. -/
@[simps {fully_applied := ff}]
protected def mul_right₀ (a : G) (ha : a ≠ 0) : perm G :=
(units.mk0 a ha).mul_right
lemma _root_.mul_right_bijective₀ (a : G) (ha : a ≠ 0) :
function.bijective ((* a) : G → G) :=
(equiv.mul_right₀ a ha).bijective
end group_with_zero
end equiv
|
e50c7ba9883e58d064209ca503ee531b7760fed9 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/ring/order_synonym.lean | a10d6672f5c8090aee569dcef221069415f4a907 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,983 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Yaël Dillies
-/
import algebra.ring.defs
import algebra.group.order_synonym
/-!
# Ring structure on the order type synonyms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Transfer algebraic instances from `α` to `αᵒᵈ` and `lex α`.
-/
variables {α : Type*}
/-! ### Order dual -/
instance [h : distrib α] : distrib αᵒᵈ := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class αᵒᵈ := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class αᵒᵈ := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵒᵈ := h
instance [h : non_unital_semiring α] : non_unital_semiring αᵒᵈ := h
instance [h : non_assoc_semiring α] : non_assoc_semiring αᵒᵈ := h
instance [h : semiring α] : semiring αᵒᵈ := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring αᵒᵈ := h
instance [h : comm_semiring α] : comm_semiring αᵒᵈ := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg αᵒᵈ := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵒᵈ := h
instance [h : non_unital_ring α] : non_unital_ring αᵒᵈ := h
instance [h : non_assoc_ring α] : non_assoc_ring αᵒᵈ := h
instance [h : ring α] : ring αᵒᵈ := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring αᵒᵈ := h
instance [h : comm_ring α] : comm_ring αᵒᵈ := h
instance [ring α] [h : is_domain α] : is_domain αᵒᵈ := h
/-! ### Lexicographical order -/
instance [h : distrib α] : distrib (lex α) := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class (lex α) := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class (lex α) := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (lex α) := h
instance [h : non_unital_semiring α] : non_unital_semiring (lex α) := h
instance [h : non_assoc_semiring α] : non_assoc_semiring (lex α) := h
instance [h : semiring α] : semiring (lex α) := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring (lex α) := h
instance [h : comm_semiring α] : comm_semiring (lex α) := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg (lex α) := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (lex α) := h
instance [h : non_unital_ring α] : non_unital_ring (lex α) := h
instance [h : non_assoc_ring α] : non_assoc_ring (lex α) := h
instance [h : ring α] : ring (lex α) := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring (lex α) := h
instance [h : comm_ring α] : comm_ring (lex α) := h
instance [ring α] [h : is_domain α] : is_domain (lex α) := h
|
d57aeea114b6c4236c8fac171864b29331b1a70d | c777c32c8e484e195053731103c5e52af26a25d1 | /src/data/mv_polynomial/basic.lean | 269d6e815638762f11a00e76ff825dfe9034c9d7 | [
"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 | 52,662 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro
-/
import algebra.algebra.tower
import algebra.monoid_algebra.support
import data.finsupp.antidiagonal
import order.symm_diff
import ring_theory.adjoin.basic
/-!
# Multivariate polynomials
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines polynomial rings over a base ring (or even semiring),
with variables from a general type `σ` (which could be infinite).
## Important definitions
Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary
type. This file creates the type `mv_polynomial σ R`, which mathematicians
might denote $R[X_i : i \in σ]$. It is the type of multivariate
(a.k.a. multivariable) polynomials, with variables
corresponding to the terms in `σ`, and coefficients in `R`.
### Notation
In the definitions below, we use the following notation:
+ `σ : Type*` (indexing the variables)
+ `R : Type*` `[comm_semiring R]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : R`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ R`
### Definitions
* `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients
in the commutative semiring `R`
* `monomial s a` : the monomial which mathematically would be denoted `a * X^s`
* `C a` : the constant polynomial with value `a`
* `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`.
* `coeff s p` : the coefficient of `s` in `p`.
* `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another
semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`.
Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested
that sticking to `eval` and `map` might make the code less brittle.
* `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation,
returning a term of type `R`
* `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of
coefficient semiring corresponding to `f`
## Implementation notes
Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite
support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`.
The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all
monomials in the variables, and the function to `R` sends a monomial to its coefficient in
the polynomial being represented.
## Tags
polynomial, multivariate polynomial, multivariable polynomial
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x}
/-- Multivariate polynomial, where `σ` is the index set of the variables and
`R` is the coefficient ring -/
def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ)
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section comm_semiring
section instances
instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] :
decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq
instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring
instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩
instance [monoid R] [comm_semiring S₁] [distrib_mul_action R S₁] :
distrib_mul_action R (mv_polynomial σ S₁) :=
add_monoid_algebra.distrib_mul_action
instance [comm_semiring S₁] [smul_zero_class R S₁] : smul_zero_class R (mv_polynomial σ S₁) :=
add_monoid_algebra.smul_zero_class
instance [comm_semiring S₁] [smul_zero_class R S₁] [has_faithful_smul R S₁] :
has_faithful_smul R (mv_polynomial σ S₁) :=
add_monoid_algebra.has_faithful_smul
instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) :=
add_monoid_algebra.module
instance [comm_semiring S₂]
[has_smul R S₁] [smul_zero_class R S₂] [smul_zero_class S₁ S₂] [is_scalar_tower R S₁ S₂] :
is_scalar_tower R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.is_scalar_tower
instance [comm_semiring S₂]
[smul_zero_class R S₂] [smul_zero_class S₁ S₂] [smul_comm_class R S₁ S₂] :
smul_comm_class R S₁ (mv_polynomial σ S₂) :=
add_monoid_algebra.smul_comm_class
instance [comm_semiring S₁] [smul_zero_class R S₁] [smul_zero_class Rᵐᵒᵖ S₁]
[is_central_scalar R S₁] :
is_central_scalar R (mv_polynomial σ S₁) :=
add_monoid_algebra.is_central_scalar
instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) :=
add_monoid_algebra.algebra
-- Register with high priority to avoid timeout in `data.mv_polynomial.pderiv`
instance is_scalar_tower' [comm_semiring R] [comm_semiring S₁] [algebra R S₁] :
is_scalar_tower R (mv_polynomial σ S₁) (mv_polynomial σ S₁) :=
is_scalar_tower.right
/-- If `R` is a subsingleton, then `mv_polynomial σ R` has a unique element -/
instance unique [comm_semiring R] [subsingleton R] : unique (mv_polynomial σ R) :=
add_monoid_algebra.unique
end instances
variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R}
/-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/
def monomial (s : σ →₀ ℕ) : R →ₗ[R] mv_polynomial σ R := lsingle s
lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl
lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl
/-- `C a` is the constant polynomial with value `a` -/
def C : R →+* mv_polynomial σ R :=
{ to_fun := monomial 0, ..single_zero_ring_hom }
variables (R σ)
theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl
variables {R σ}
/-- `X n` is the degree `1` monomial $X_n$. -/
def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1
lemma monomial_left_injective {r : R} (hr : r ≠ 0) :
function.injective (λ s : σ →₀ ℕ, monomial s r) :=
finsupp.single_left_injective hr
@[simp] lemma monomial_left_inj {s t : σ →₀ ℕ} {r : R} (hr : r ≠ 0) :
monomial s r = monomial t r ↔ s = t :=
finsupp.single_left_inj hr
lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl
@[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial]
@[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl
lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') :=
by simp [C_apply, monomial, single_mul_single]
@[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add _ _ _
@[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm
@[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n :=
by induction n; simp [pow_succ, *]
lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] :
function.injective (C : R → mv_polynomial σ R) :=
finsupp.single_injective _
lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) [is_empty σ] :
function.surjective (C : R → mv_polynomial σ R) :=
begin
refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩,
simpa [(finsupp.ext is_empty_elim : a = 0), C_apply, monomial],
end
@[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) :
(C r : mv_polynomial σ R) = C s ↔ r = s :=
(C_injective σ R).eq_iff
instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective C (C_injective _ _)
instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R]
[nontrivial R] :
infinite (mv_polynomial σ R) :=
infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $
(monomial_left_injective one_ne_zero).comp (finsupp.single_injective _)
lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n :=
by induction n; simp [nat.succ_eq_add_one, *]
theorem C_mul' : mv_polynomial.C a * p = a • p :=
(algebra.smul_def a p).symm
lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm
lemma C_eq_smul_one : (C a : mv_polynomial σ R) = a • 1 :=
by rw [← C_mul', mul_one]
lemma smul_monomial {S₁ : Type*} [smul_zero_class S₁ R] (r : S₁) :
r • monomial s a = monomial s (r • a) := finsupp.smul_single _ _ _
lemma X_injective [nontrivial R] : function.injective (X : σ → mv_polynomial σ R) :=
(monomial_left_injective one_ne_zero).comp (finsupp.single_left_injective one_ne_zero)
@[simp] lemma X_inj [nontrivial R] (m n : σ) : X m = (X n : mv_polynomial σ R) ↔ m = n :=
X_injective.eq_iff
lemma monomial_pow : monomial s a ^ e = monomial (e • s) (a ^ e) :=
add_monoid_algebra.single_pow e
@[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} :
monomial s a * monomial s' b = monomial (s + s') (a * b) :=
add_monoid_algebra.single_mul_single
variables (σ R)
/-- `λ s, monomial s 1` as a homomorphism. -/
def monomial_one_hom : multiplicative (σ →₀ ℕ) →* mv_polynomial σ R :=
add_monoid_algebra.of _ _
variables {σ R}
@[simp] lemma monomial_one_hom_apply :
monomial_one_hom R σ s = (monomial s 1 : mv_polynomial σ R) := rfl
lemma X_pow_eq_monomial : X n ^ e = monomial (single n e) (1 : R) := by simp [X, monomial_pow]
lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) :=
by rw [X_pow_eq_monomial, monomial_mul, mul_one]
lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) :=
by rw [X_pow_eq_monomial, monomial_mul, one_mul]
lemma C_mul_X_pow_eq_monomial {s : σ} {a : R} {n : ℕ} : C a * X s ^ n = monomial (single s n) a :=
by rw [← zero_add (single s n), monomial_add_single, C_apply]
lemma C_mul_X_eq_monomial {s : σ} {a : R} : C a * X s = monomial (single s 1) a :=
by rw [← C_mul_X_pow_eq_monomial, pow_one]
@[simp] lemma monomial_zero {s : σ →₀ ℕ} : monomial s (0 : R) = 0 := single_zero _
@[simp] lemma monomial_zero' : (monomial (0 : σ →₀ ℕ) : R → mv_polynomial σ R) = C := rfl
@[simp] lemma monomial_eq_zero {s : σ →₀ ℕ} {b : R} : monomial s b = 0 ↔ b = 0 :=
finsupp.single_eq_zero
@[simp] lemma sum_monomial_eq {A : Type*} [add_comm_monoid A]
{u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) :
sum (monomial u r) b = b u r :=
sum_single_index w
@[simp] lemma sum_C {A : Type*} [add_comm_monoid A]
{b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) :
sum (C a) b = b 0 a :=
sum_monomial_eq w
lemma monomial_sum_one {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) :
(monomial (∑ i in s, f i) 1 : mv_polynomial σ R) = ∏ i in s, monomial (f i) 1 :=
(monomial_one_hom R σ).map_prod (λ i, multiplicative.of_add (f i)) s
lemma monomial_sum_index {α : Type*} (s : finset α) (f : α → (σ →₀ ℕ)) (a : R) :
(monomial (∑ i in s, f i) a) = C a * ∏ i in s, monomial (f i) 1 :=
by rw [← monomial_sum_one, C_mul', ← (monomial _).map_smul, smul_eq_mul, mul_one]
lemma monomial_finsupp_sum_index {α β : Type*} [has_zero β] (f : α →₀ β)
(g : α → β → (σ →₀ ℕ)) (a : R) :
(monomial (f.sum g) a) = C a * f.prod (λ a b, monomial (g a b) 1) :=
monomial_sum_index _ _ _
lemma monomial_eq_monomial_iff {α : Type*} (a₁ a₂ : α →₀ ℕ) (b₁ b₂ : R) :
monomial a₁ b₁ = monomial a₂ b₂ ↔ a₁ = a₂ ∧ b₁ = b₂ ∨ b₁ = 0 ∧ b₂ = 0 :=
finsupp.single_eq_single_iff _ _ _ _
lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp only [X_pow_eq_monomial, ← monomial_finsupp_sum_index, finsupp.sum_single]
lemma induction_on_monomial {M : mv_polynomial σ R → Prop} (h_C : ∀ a, M (C a))
(h_X : ∀ p n, M p → M (p * X n)) : ∀ s a, M (monomial s a) :=
begin
assume s a,
apply @finsupp.induction σ ℕ _ _ s,
{ show M (monomial 0 a), from h_C a, },
{ assume n e p hpn he ih,
have : ∀e:ℕ, M (monomial p a * X n ^ e),
{ intro e,
induction e,
{ simp [ih] },
{ simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } },
simp [add_comm, monomial_add_single, this] }
end
/-- Analog of `polynomial.induction_on'`.
To prove something about mv_polynomials,
it suffices to show the condition is closed under taking sums,
and it holds for monomials. -/
attribute [elab_as_eliminator]
theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a))
(h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p :=
finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this,
show P (monomial 0 0), from h1 0 0)
(λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf)
/-- Similar to `mv_polynomial.induction_on` but only a weak form of `h_add` is required.-/
lemma induction_on''' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b + f)) : M p :=
finsupp.induction p (C_0.rec $ h_C 0) h_add_weak
/-- Similar to `mv_polynomial.induction_on` but only a yet weaker form of `h_add` is required.-/
lemma induction_on'' {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀ a, M (C a))
(h_add_weak : ∀ (a : σ →₀ ℕ) (b : R) (f : (σ →₀ ℕ) →₀ R),
a ∉ f.support → b ≠ 0 → M f → M (monomial a b) → M (monomial a b + f))
(h_X : ∀ (p : mv_polynomial σ R) (n : σ), M p → M (p * mv_polynomial.X n)): M p :=
induction_on''' p h_C (λ a b f ha hb hf,
h_add_weak a b f ha hb hf $ induction_on_monomial h_C h_X a b)
/-- Analog of `polynomial.induction_on`.-/
@[recursor 5]
lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R)
(h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) :
M p :=
induction_on'' p h_C (λ a b f ha hb hf hm, h_add (monomial a b) f hm hf) h_X
lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
by { ext, exacts [hC _, hX _] }
/-- See note [partially-applied ext lemmas]. -/
@[ext] lemma ring_hom_ext' {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A}
(hC : f.comp C = g.comp C) (hX : ∀ i, f (X i) = g (X i)) :
f = g :=
ring_hom_ext (ring_hom.ext_iff.1 hC) hX
lemma hom_eq_hom [semiring S₂]
(f g : mv_polynomial σ R →+* S₂)
(hC : f.comp C = g.comp C) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) :
f p = g p :=
ring_hom.congr_fun (ring_hom_ext' hC hX) p
lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R)
(hC : f.comp C = C) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) :
f p = p :=
hom_eq_hom f (ring_hom.id _) hC hX p
@[ext] lemma alg_hom_ext' {A B : Type*} [comm_semiring A] [comm_semiring B]
[algebra R A] [algebra R B] {f g : mv_polynomial σ A →ₐ[R] B}
(h₁ : f.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)) =
g.comp (is_scalar_tower.to_alg_hom R A (mv_polynomial σ A)))
(h₂ : ∀ i, f (X i) = g (X i)) : f = g :=
alg_hom.coe_ring_hom_injective (mv_polynomial.ring_hom_ext'
(congr_arg alg_hom.to_ring_hom h₁) h₂)
@[ext] lemma alg_hom_ext {A : Type*} [semiring A] [algebra R A]
{f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) :
f = g :=
add_monoid_algebra.alg_hom_ext' (mul_hom_ext' (λ (x : σ), monoid_hom.ext_mnat (hf x)))
@[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) :
f (C r) = C r :=
f.commutes r
@[simp] lemma adjoin_range_X : algebra.adjoin R (range (X : σ → mv_polynomial σ R)) = ⊤ :=
begin
set S := algebra.adjoin R (range (X : σ → mv_polynomial σ R)),
refine top_unique (λ p hp, _), clear hp,
induction p using mv_polynomial.induction_on,
case h_C : { exact S.algebra_map_mem _ },
case h_add : p q hp hq { exact S.add_mem hp hq },
case h_X : p i hp { exact S.mul_mem hp (algebra.subset_adjoin $ mem_range_self _) }
end
@[ext] lemma linear_map_ext {M : Type*} [add_comm_monoid M] [module R M]
{f g : mv_polynomial σ R →ₗ[R] M} (h : ∀ s, f ∘ₗ monomial s = g ∘ₗ monomial s) :
f = g :=
finsupp.lhom_ext' h
section support
/--
The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient.
-/
def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) :=
p.support
lemma finsupp_support_eq_support (p : mv_polynomial σ R) : finsupp.support p = p.support := rfl
lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} :=
by convert rfl
lemma support_monomial_subset : (monomial s a).support ⊆ {s} :=
support_single_subset
lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add
lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} :=
by rw [X, support_monomial, if_neg]; exact one_ne_zero
lemma support_X_pow [nontrivial R] (s : σ) (n : ℕ) :
(X s ^ n : mv_polynomial σ R).support = {finsupp.single s n} :=
by rw [X_pow_eq_monomial, support_monomial, if_neg (one_ne_zero' R)]
@[simp] lemma support_zero : (0 : mv_polynomial σ R).support = ∅ := rfl
lemma support_smul {S₁ : Type*} [smul_zero_class S₁ R] {a : S₁} {f : mv_polynomial σ R} :
(a • f).support ⊆ f.support :=
finsupp.support_smul
lemma support_sum {α : Type*} {s : finset α} {f : α → mv_polynomial σ R} :
(∑ x in s, f x).support ⊆ s.bUnion (λ x, (f x).support) := finsupp.support_finset_sum
end support
section coeff
/-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/
def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R :=
@coe_fn _ _ (monoid_algebra.has_coe_to_fun _ _) p m
@[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∈ p.support ↔ p.coeff m ≠ 0 :=
by simp [support, coeff]
lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} :
m ∉ p.support ↔ p.coeff m = 0 :=
by simp
lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} :
p.sum b = ∑ m in p.support, b m (p.coeff m) :=
by simp [support, finsupp.sum, coeff]
lemma support_mul (p q : mv_polynomial σ R) :
(p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) :=
by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl
@[ext] lemma ext (p q : mv_polynomial σ R) :
(∀ m, coeff m p = coeff m q) → p = q := ext
lemma ext_iff (p q : mv_polynomial σ R) :
p = q ↔ (∀ m, coeff m p = coeff m q) :=
⟨ λ h m, by rw h, ext p q⟩
@[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) :
coeff m (p + q) = coeff m p + coeff m q := add_apply p q m
@[simp] lemma coeff_smul {S₁ : Type*} [smul_zero_class S₁ R]
(m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) :
coeff m (c • p) = c • coeff m p := smul_apply c p m
@[simp] lemma coeff_zero (m : σ →₀ ℕ) :
coeff m (0 : mv_polynomial σ R) = 0 := rfl
@[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 :=
single_eq_of_ne (λ h, by cases single_eq_zero.1 h)
/-- `mv_polynomial.coeff m` but promoted to an `add_monoid_hom`. -/
@[simps] def coeff_add_monoid_hom (m : σ →₀ ℕ) : mv_polynomial σ R →+ R :=
{ to_fun := coeff m,
map_zero' := coeff_zero m,
map_add' := coeff_add m }
lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) :
coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) :=
(@coeff_add_monoid_hom R σ _ _).map_sum _ s
lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) :=
by simp [monomial_eq]
@[simp] lemma coeff_monomial [decidable_eq σ] (m n) (a) :
coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 :=
single_apply
@[simp] lemma coeff_C [decidable_eq σ] (m) (a) :
coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 :=
single_apply
lemma coeff_one [decidable_eq σ] (m) :
coeff m (1 : mv_polynomial σ R) = if 0 = m then 1 else 0 :=
coeff_C m 1
@[simp] lemma coeff_zero_C (a) : coeff 0 (C a : mv_polynomial σ R) = a :=
single_eq_same
@[simp] lemma coeff_zero_one : coeff 0 (1 : mv_polynomial σ R) = 1 :=
coeff_zero_C 1
lemma coeff_X_pow [decidable_eq σ] (i : σ) (m) (k : ℕ) :
coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 :=
begin
have := coeff_monomial m (finsupp.single i k) (1:R),
rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _,
C_1, one_mul, finsupp.prod_single_index] at this,
exact pow_zero _
end
lemma coeff_X' [decidable_eq σ] (i : σ) (m) :
coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 :=
by rw [← coeff_X_pow, pow_one]
@[simp] lemma coeff_X (i : σ) :
coeff (single i 1) (X i : mv_polynomial σ R) = 1 :=
by rw [coeff_X', if_pos rfl]
@[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) :
coeff m (C a * p) = a * coeff m p :=
begin
rw [mul_def, sum_C],
{ simp [sum_def, coeff_sum] {contextual := tt} },
simp
end
lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) :
coeff n (p * q) = ∑ x in antidiagonal n, coeff x.1 p * coeff x.2 q :=
add_monoid_algebra.mul_apply_antidiagonal p q _ _ $ λ p, mem_antidiagonal
@[simp] lemma coeff_mul_monomial (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (m + s) (p * monomial s r) = coeff m p * r :=
(add_monoid_algebra.mul_single_apply_aux p _ _ _ _ (λ a, add_left_inj _))
@[simp] lemma coeff_monomial_mul (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff (s + m) (monomial s r * p) = r * coeff m p :=
(add_monoid_algebra.single_mul_apply_aux p _ _ _ _ (λ a, add_right_inj _))
@[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) :
coeff (m + single s 1) (p * X s) = coeff m p :=
(coeff_mul_monomial _ _ _ _).trans (mul_one _)
@[simp] lemma coeff_X_mul (m) (s : σ) (p : mv_polynomial σ R) :
coeff (single s 1 + m) (X s * p) = coeff m p :=
(coeff_monomial_mul _ _ _ _).trans (one_mul _)
@[simp] lemma support_mul_X (s : σ) (p : mv_polynomial σ R) :
(p * X s).support = p.support.map (add_right_embedding (single s 1)) :=
add_monoid_algebra.support_mul_single p _ (by simp) _
@[simp] lemma support_X_mul (s : σ) (p : mv_polynomial σ R) :
(X s * p).support = p.support.map (add_left_embedding (single s 1)) :=
add_monoid_algebra.support_single_mul p _ (by simp) _
@[simp] lemma support_smul_eq {S₁ : Type*} [semiring S₁] [module S₁ R] [no_zero_smul_divisors S₁ R]
{a : S₁} (h : a ≠ 0) (p : mv_polynomial σ R) : (a • p).support = p.support :=
finsupp.support_smul_eq h
lemma support_sdiff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support \ q.support ⊆ (p + q).support :=
begin
intros m hm,
simp only [not_not, mem_support_iff, finset.mem_sdiff, ne.def] at hm,
simp [hm.2, hm.1],
end
lemma support_symm_diff_support_subset_support_add [decidable_eq σ] (p q : mv_polynomial σ R) :
p.support ∆ q.support ⊆ (p + q).support :=
begin
rw [symm_diff_def, finset.sup_eq_union],
apply finset.union_subset,
{ exact support_sdiff_support_subset_support_add p q, },
{ rw add_comm,
exact support_sdiff_support_subset_support_add q p, },
end
lemma coeff_mul_monomial' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (p * monomial s r) = if s ≤ m then coeff (m - s) p * r else 0 :=
begin
obtain rfl | hr := eq_or_ne r 0,
{ simp only [monomial_zero, coeff_zero, mul_zero, if_t_t], },
haveI : nontrivial R := nontrivial_of_ne _ _ hr,
split_ifs with h h,
{ conv_rhs {rw ← coeff_mul_monomial _ s},
congr' with t,
rw tsub_add_cancel_of_le h, },
{ rw ← not_mem_support_iff, intro hm, apply h,
have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H,
rcases H with ⟨j, hj, i', hi', H⟩,
rw [support_monomial, if_neg hr, finset.mem_singleton] at hi', subst i',
rw finset.mem_singleton at H, subst m,
exact le_add_left le_rfl, }
end
lemma coeff_monomial_mul' (m) (s : σ →₀ ℕ) (r : R) (p : mv_polynomial σ R) :
coeff m (monomial s r * p) = if s ≤ m then r * coeff (m - s) p else 0 :=
begin
-- note that if we allow `R` to be non-commutative we will have to duplicate the proof above.
rw [mul_comm, mul_comm r],
exact coeff_mul_monomial' _ _ _ _
end
lemma coeff_mul_X' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_mul_monomial' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
mul_one],
end
lemma coeff_X_mul' [decidable_eq σ] (m) (s : σ) (p : mv_polynomial σ R) :
coeff m (X s * p) = if s ∈ m.support then coeff (m - single s 1) p else 0 :=
begin
refine (coeff_monomial_mul' _ _ _ _).trans _,
simp_rw [finsupp.single_le_iff, finsupp.mem_support_iff, nat.succ_le_iff, pos_iff_ne_zero,
one_mul],
end
lemma eq_zero_iff {p : mv_polynomial σ R} :
p = 0 ↔ ∀ d, coeff d p = 0 :=
by { rw ext_iff, simp only [coeff_zero], }
lemma ne_zero_iff {p : mv_polynomial σ R} :
p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 :=
by { rw [ne.def, eq_zero_iff], push_neg, }
@[simp] lemma support_eq_empty {p : mv_polynomial σ R} : p.support = ∅ ↔ p = 0 :=
finsupp.support_eq_empty
lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) :
∃ d, coeff d p ≠ 0 :=
ne_zero_iff.mp h
lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) :
C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i :=
begin
split,
{ rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right },
{ intro h,
choose c hc using h,
classical,
let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0,
let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i),
use ψ,
apply mv_polynomial.ext, intro i,
simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'],
split_ifs with hi hi,
{ rw hc },
{ rw not_mem_support_iff at hi, rwa mul_zero } },
end
end coeff
section constant_coeff
/--
`constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`.
This is a ring homomorphism.
-/
def constant_coeff : mv_polynomial σ R →+* R :=
{ to_fun := coeff 0,
map_one' := by simp [coeff, add_monoid_algebra.one_def],
map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero],
map_zero' := coeff_zero _,
map_add' := coeff_add _ }
lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl
variables (σ)
@[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r :=
by simp [constant_coeff_eq]
variables {σ}
variables (R)
@[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 :=
by simp [constant_coeff_eq]
variables {R}
@[simp] lemma constant_coeff_smul {R : Type*} [smul_zero_class R S₁]
(a : R) (f : mv_polynomial σ S₁) :
constant_coeff (a • f) = a • constant_coeff f := rfl
lemma constant_coeff_monomial [decidable_eq σ] (d : σ →₀ ℕ) (r : R) :
constant_coeff (monomial d r) = if d = 0 then r else 0 :=
by rw [constant_coeff_eq, coeff_monomial]
variables (σ R)
@[simp] lemma constant_coeff_comp_C :
constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R :=
by { ext x, exact constant_coeff_C σ x }
@[simp] lemma constant_coeff_comp_algebra_map :
constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R :=
constant_coeff_comp_C _ _
end constant_coeff
section as_sum
@[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) :
∑ v in p.support, monomial v (coeff v p) = p :=
finsupp.sum_single p
lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) :=
(support_sum_monomial_coeff p).symm
end as_sum
section eval₂
variables (f : R →+* S₁) (g : σ → S₁)
/-- Evaluate a polynomial `p` given a valuation `g` of all the variables
and a ring hom `f` from the scalar ring to the target -/
def eval₂ (p : mv_polynomial σ R) : S₁ :=
p.sum (λs a, f a * s.prod (λn e, g n ^ e))
lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) :
f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i :=
by { simp only [eval₂_eq, ← finsupp.prod_pow], refl }
@[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 :=
finsupp.sum_zero_index
section
@[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g :=
finsupp.sum_add_index
(by simp [f.map_zero])
(by simp [add_mul, f.map_add])
@[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) :=
finsupp.sum_single_index (by simp [f.map_zero])
@[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a :=
by rw [C_apply, eval₂_monomial, prod_zero_index, mul_one]
@[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 :=
(eval₂_C _ _ _).trans f.map_one
@[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n :=
by simp [eval₂_monomial, f.map_one, X, prod_single_index, pow_one]
lemma eval₂_mul_monomial :
∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) :=
begin
apply mv_polynomial.induction_on p,
{ assume a' s a,
simp [C_mul_monomial, eval₂_monomial, f.map_mul] },
{ assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] },
{ assume p n ih s a,
from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g :
by rw [monomial_single_add, pow_one, mul_assoc]
... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) :
by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm,
f.map_one, -add_comm] }
end
lemma eval₂_mul_C : (p * C a).eval₂ f g = p.eval₂ f g * f a :=
(eval₂_mul_monomial _ _).trans $ by simp
@[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g :=
begin
apply mv_polynomial.induction_on q,
{ simp [eval₂_C, eval₂_mul_C] },
{ simp [mul_add, eval₂_add] {contextual := tt} },
{ simp [X, eval₂_monomial, eval₂_mul_monomial, ← mul_assoc] { contextual := tt} }
end
@[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n
| 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ }
| (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow]
/-- `mv_polynomial.eval₂` as a `ring_hom`. -/
def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ :=
{ to_fun := eval₂ f g,
map_one' := eval₂_one _ _,
map_mul' := λ p q, eval₂_mul _ _,
map_zero' := eval₂_zero _ _,
map_add' := λ p q, eval₂_add _ _ }
@[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) :
⇑(eval₂_hom f g) = eval₂ f g := rfl
lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} :
f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ :=
by rintros rfl rfl rfl; refl
end
@[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) :
eval₂_hom f g (C r) = f r := eval₂_C f g r
@[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) :
eval₂_hom f g (X i) = g i := eval₂_X f g i
@[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) :
φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) :=
begin
apply mv_polynomial.ring_hom_ext,
{ intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] },
{ intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] }
end
lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) :=
by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod,
ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X']
section
lemma eval₂_comp_left {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p :=
by apply mv_polynomial.induction_on p; simp [
eval₂_add, k.map_add,
eval₂_mul, k.map_mul] {contextual := tt}
end
@[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p :=
by apply mv_polynomial.induction_on p;
simp [eval₂_add, eval₂_mul] {contextual := tt}
lemma eval₂_congr (g₁ g₂ : σ → S₁)
(h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) :
p.eval₂ f g₁ = p.eval₂ f g₂ :=
begin
apply finset.sum_congr rfl,
intros c hc, dsimp, congr' 1,
apply finset.prod_congr rfl,
intros i hi, dsimp, congr' 1,
apply h hi,
rwa finsupp.mem_support_iff at hc
end
@[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_prod _ s
@[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) :
eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) :=
(eval₂_hom f g).map_sum _ s
attribute [to_additive] eval₂_prod
lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) :
eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) :=
begin
show _ = eval₂_hom f g (eval₂ C q p),
rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp,
end
end eval₂
section eval
variables {f : σ → R}
/-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/
def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f
lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i :=
rfl
lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) :
eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i :=
eval₂_eq' (ring_hom.id R) x f
lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) :=
eval₂_monomial _ _
@[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _
@[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _
@[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p :=
by rw [smul_eq_C_mul, (eval x).map_mul, eval_C]
lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) :=
(eval g).map_sum _ _
@[to_additive]
lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) :
eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) :=
(eval g).map_prod _ _
theorem eval_assoc {τ}
(f : σ → mv_polynomial τ R) (g : τ → R)
(p : mv_polynomial σ R) :
eval (eval g ∘ f) p = eval g (eval₂ C f p) :=
begin
rw eval₂_comp_left (eval g),
unfold eval, simp only [coe_eval₂_hom],
congr' with a, simp
end
@[simp]
theorem eval₂_id (p : mv_polynomial σ R) (g : σ → R) : eval₂ (ring_hom.id _) g p = eval g p :=
rfl
theorem eval_eval₂ {τ : Type*} (f : R →+* mv_polynomial τ S₁) (g : σ → mv_polynomial τ S₁)
(p : mv_polynomial σ R) (x : τ → S₁) :
eval x (eval₂ f g p) = eval₂ ((eval x).comp f) (λ s, eval x (g s)) p :=
begin
apply induction_on p,
{ simp, },
{ intros p q hp hq,
simp [hp, hq] },
{ intros p n hp,
simp [hp] }
end
end eval
section map
variables (f : R →+* S₁)
/-- `map f p` maps a polynomial `p` across a ring hom `f` -/
def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X
@[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) :=
(eval₂_monomial _ _).trans monomial_eq.symm
@[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _
@[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _
theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta
theorem map_map [comm_semiring S₂]
(g : S₁ →+* S₂)
(p : mv_polynomial σ R) :
map g (map f p) = map (g.comp f) p :=
(eval₂_comp_left (map g) (C.comp f) X p).trans $
begin
congr,
{ ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], },
{ ext1 n, simp only [map_X, comp_app], }
end
theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) :
p.eval₂ f g = eval g (map f p) :=
begin
unfold map eval, simp only [coe_eval₂_hom],
have h := eval₂_comp_left (eval₂_hom _ g),
dsimp at h,
rw h,
congr,
{ ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], },
{ ext1 n, simp only [comp_app, eval₂_X], },
end
lemma eval₂_comp_right {S₂} [comm_semiring S₂]
(k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁)
(p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] },
{ intros p s hp,
rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] }
end
lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) :
map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) :=
begin
apply mv_polynomial.induction_on p,
{ intro r, rw [eval₂_C, map_C, map_C, eval₂_C] },
{ intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] },
{ intros p s hp,
rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] }
end
lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) :=
begin
apply mv_polynomial.induction_on p; clear p,
{ intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero },
{ intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add },
{ intros p i hp m, simp only [hp, (map f).map_mul, map_X],
simp only [hp, mem_support_iff, coeff_mul_X'],
split_ifs, {refl},
rw f.map_zero }
end
lemma map_injective (hf : function.injective f) :
function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
begin
intros p q h,
simp only [ext_iff, coeff_map] at h ⊢,
intro m,
exact hf (h m),
end
lemma map_surjective (hf : function.surjective f) :
function.surjective (map f : mv_polynomial σ R → mv_polynomial σ S₁) :=
λ p, begin
induction p using mv_polynomial.induction_on' with i fr a b ha hb,
{ obtain ⟨r, rfl⟩ := hf fr,
exact ⟨monomial i r, map_monomial _ _ _⟩, },
{ obtain ⟨a, rfl⟩ := ha,
obtain ⟨b, rfl⟩ := hb,
exact ⟨a + b, ring_hom.map_add _ _ _⟩ },
end
/-- If `f` is a left-inverse of `g` then `map f` is a left-inverse of `map g`. -/
lemma map_left_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.left_inverse f g) :
function.left_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
λ x, by rw [map_map, (ring_hom.ext hf : f.comp g = ring_hom.id _), map_id]
/-- If `f` is a right-inverse of `g` then `map f` is a right-inverse of `map g`. -/
lemma map_right_inverse {f : R →+* S₁} {g : S₁ →+* R} (hf : function.right_inverse f g) :
function.right_inverse (map f : mv_polynomial σ R → mv_polynomial σ S₁) (map g) :=
(map_left_inverse hf.left_inverse).right_inverse
@[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) :
eval g (map f p) = eval₂ f g p :=
by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } }
@[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂ φ g (map f p) = eval₂ (φ.comp f) g p :=
by { rw [← eval_map, ← eval_map, map_map], }
@[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂)
(p : mv_polynomial σ R) :
eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p :=
eval₂_map f g φ p
@[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) :
constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) :=
coeff_map f φ 0
lemma constant_coeff_comp_map (f : R →+* S₁) :
(constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff :=
by { ext; simp }
lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support :=
begin
intro x,
simp only [mem_support_iff],
contrapose!,
change p.coeff x = 0 → (map f p).coeff x = 0,
rw coeff_map,
intro hx,
rw hx,
exact ring_hom.map_zero f
end
lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) :
(map f p).support = p.support :=
begin
apply finset.subset.antisymm,
{ exact mv_polynomial.support_map_subset _ _ },
intros x hx,
rw mem_support_iff,
contrapose! hx,
simp only [not_not, mem_support_iff],
change (map f p).coeff x = 0 at hx,
rw [coeff_map, ← f.map_zero] at hx,
exact hf hx
end
lemma C_dvd_iff_map_hom_eq_zero
(q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r')
(φ : mv_polynomial σ R) :
C r ∣ φ ↔ map q φ = 0 :=
begin
rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff],
simp only [coeff_map, coeff_zero, hr],
end
lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) :
map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ :=
begin
rw mv_polynomial.ext_iff,
apply forall_congr, intro m,
rw [coeff_map],
apply eq_iff_eq_cancel_right.mpr,
refl
end
/-- If `f : S₁ →ₐ[R] S₂` is a morphism of `R`-algebras, then so is `mv_polynomial.map f`. -/
@[simps]
def map_alg_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂] (f : S₁ →ₐ[R] S₂) :
mv_polynomial σ S₁ →ₐ[R] mv_polynomial σ S₂ :=
{ to_fun := map ↑f,
commutes' := λ r, begin
have h₁ : algebra_map R (mv_polynomial σ S₁) r = C (algebra_map R S₁ r) := rfl,
have h₂ : algebra_map R (mv_polynomial σ S₂) r = C (algebra_map R S₂ r) := rfl,
rw [h₁, h₂, map, eval₂_hom_C, ring_hom.comp_apply, alg_hom.coe_to_ring_hom, alg_hom.commutes],
end,
..map ↑f }
@[simp] lemma map_alg_hom_id [algebra R S₁] :
map_alg_hom (alg_hom.id R S₁) = alg_hom.id R (mv_polynomial σ S₁) :=
alg_hom.ext map_id
@[simp] lemma map_alg_hom_coe_ring_hom [comm_semiring S₂] [algebra R S₁] [algebra R S₂]
(f : S₁ →ₐ[R] S₂) :
↑(map_alg_hom f : _ →ₐ[R] mv_polynomial σ S₂) =
(map ↑f : mv_polynomial σ S₁ →+* mv_polynomial σ S₂) :=
ring_hom.mk_coe _ _ _ _ _
end map
section aeval
/-! ### The algebra of multivariate polynomials -/
variables [algebra R S₁] [comm_semiring S₂]
variables (f : σ → S₁)
lemma algebra_map_apply (r : R) :
algebra_map R (mv_polynomial σ S₁) r = C (algebra_map R S₁ r) := rfl
/-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism
from multivariate polynomials over `σ` to `S₁`. -/
def aeval : mv_polynomial σ R →ₐ[R] S₁ :=
{ commutes' := λ r, eval₂_C _ _ _
.. eval₂_hom (algebra_map R S₁) f }
theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl
lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) :
aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl
@[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _
@[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _
theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) :
φ = aeval (φ ∘ X) :=
by { ext i, simp }
lemma aeval_X_left : aeval X = alg_hom.id R (mv_polynomial σ R) :=
(aeval_unique (alg_hom.id R _)).symm
lemma aeval_X_left_apply (p : mv_polynomial σ R) : aeval X p = p :=
alg_hom.congr_fun aeval_X_left p
lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B]
(φ : S₁ →ₐ[R] B) :
φ.comp (aeval f) = aeval (λ i, φ (f i)) :=
by { ext i, simp }
@[simp] lemma map_aeval {B : Type*} [comm_semiring B]
(g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) :
φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) :=
by { rw ← comp_eval₂_hom, refl }
@[simp] lemma eval₂_hom_zero (f : R →+* S₂) :
eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff :=
by { ext; simp }
@[simp] lemma eval₂_hom_zero' (f : R →+* S₂) :
eval₂_hom f (λ _, 0 : σ → S₂) = f.comp constant_coeff :=
eval₂_hom_zero f
lemma eval₂_hom_zero_apply (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) :=
ring_hom.congr_fun (eval₂_hom_zero f) p
lemma eval₂_hom_zero'_apply (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero_apply f p
@[simp] lemma eval₂_zero_apply (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂ f (0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_hom_zero_apply _ _
@[simp] lemma eval₂_zero'_apply (f : R →+* S₂) (p : mv_polynomial σ R) :
eval₂ f (λ _, 0 : σ → S₂) p = f (constant_coeff p) :=
eval₂_zero_apply f p
@[simp] lemma aeval_zero (p : mv_polynomial σ R) :
aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
eval₂_hom_zero_apply (algebra_map R S₁) p
@[simp] lemma aeval_zero' (p : mv_polynomial σ R) :
aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) :=
aeval_zero p
@[simp] lemma eval_zero : eval (0 : σ → R) = constant_coeff :=
eval₂_hom_zero _
@[simp] lemma eval_zero' : eval (λ _, 0 : σ → R) = constant_coeff :=
eval₂_hom_zero _
lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) :
aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) :=
eval₂_hom_monomial _ _ _ _
lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) :
eval₂_hom f g φ = 0 :=
begin
rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero],
intros d hd,
obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd),
rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero],
rw [hgi, zero_pow],
rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff]
end
lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R)
(h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) :
aeval f φ = 0 :=
eval₂_hom_eq_zero _ _ _ h
lemma aeval_sum {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∑ i in s, φ i) = ∑ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_sum _ _
@[to_additive]
lemma aeval_prod {ι : Type*} (s : finset ι) (φ : ι → mv_polynomial σ R) :
aeval f (∏ i in s, φ i) = ∏ i in s, aeval f (φ i) :=
(mv_polynomial.aeval f).map_prod _ _
variable (R)
lemma _root_.algebra.adjoin_range_eq_range_aeval :
algebra.adjoin R (set.range f) = (mv_polynomial.aeval f).range :=
by simp only [← algebra.map_top, ← mv_polynomial.adjoin_range_X, alg_hom.map_adjoin,
← set.range_comp, (∘), mv_polynomial.aeval_X]
theorem _root_.algebra.adjoin_eq_range (s : set S₁) :
algebra.adjoin R s = (mv_polynomial.aeval (coe : s → S₁)).range :=
by rw [← algebra.adjoin_range_eq_range_aeval, subtype.range_coe]
end aeval
section aeval_tower
variables {S A B : Type*} [comm_semiring S] [comm_semiring A] [comm_semiring B]
variables [algebra S R] [algebra S A] [algebra S B]
/-- Version of `aeval` for defining algebra homs out of `mv_polynomial σ R` over a smaller base ring
than `R`. -/
def aeval_tower (f : R →ₐ[S] A) (x : σ → A) : mv_polynomial σ R →ₐ[S] A :=
{ commutes' := λ r,
by simp [is_scalar_tower.algebra_map_eq S R (mv_polynomial σ R), algebra_map_eq],
..eval₂_hom ↑f x }
variables (g : R →ₐ[S] A) (y : σ → A)
@[simp] lemma aeval_tower_X (i : σ): aeval_tower g y (X i) = y i := eval₂_X _ _ _
@[simp] lemma aeval_tower_C (x : R) : aeval_tower g y (C x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_C : ((aeval_tower g y : mv_polynomial σ R →+* A).comp C) = g :=
ring_hom.ext $ aeval_tower_C _ _
@[simp] lemma aeval_tower_algebra_map (x : R) :
aeval_tower g y (algebra_map R (mv_polynomial σ R) x) = g x := eval₂_C _ _ _
@[simp] lemma aeval_tower_comp_algebra_map :
(aeval_tower g y : mv_polynomial σ R →+* A).comp (algebra_map R (mv_polynomial σ R)) = g :=
aeval_tower_comp_C _ _
lemma aeval_tower_to_alg_hom (x : R) :
aeval_tower g y (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R) x) = g x :=
aeval_tower_algebra_map _ _ _
@[simp] lemma aeval_tower_comp_to_alg_hom :
(aeval_tower g y).comp (is_scalar_tower.to_alg_hom S R (mv_polynomial σ R)) = g :=
alg_hom.coe_ring_hom_injective $ aeval_tower_comp_algebra_map _ _
@[simp] lemma aeval_tower_id : aeval_tower (alg_hom.id S S) =
(aeval : (σ → S) → (mv_polynomial σ S →ₐ[S] S)) :=
by { ext, simp only [aeval_tower_X, aeval_X] }
@[simp] lemma aeval_tower_of_id : aeval_tower (algebra.of_id S A) =
(aeval : (σ → A) → (mv_polynomial σ S →ₐ[S] A)) :=
by { ext, simp only [aeval_X, aeval_tower_X] }
end aeval_tower
section eval_mem
variables {S subS : Type*} [comm_semiring S] [set_like subS S] [subsemiring_class subS S]
theorem eval₂_mem {f : R →+* S}
{p : mv_polynomial σ R} {s : subS}
(hs : ∀ i ∈ p.support, f (p.coeff i) ∈ s) {v : σ → S} (hv : ∀ i, v i ∈ s) :
mv_polynomial.eval₂ f v p ∈ s :=
begin
classical,
replace hs : ∀ i, f (p.coeff i) ∈ s,
{ intro i,
by_cases hi : i ∈ p.support,
{ exact hs i hi },
{ rw [mv_polynomial.not_mem_support_iff.1 hi, f.map_zero],
exact zero_mem s } },
induction p using mv_polynomial.induction_on''' with a a b f ha hb0 ih generalizing hs,
{ simpa using hs 0 },
rw [eval₂_add, eval₂_monomial],
refine add_mem (mul_mem _ $ prod_mem $ λ i hi, pow_mem (hv _) _) (ih $ λ i, _),
{ simpa only [coeff_add, coeff_monomial, if_pos rfl,
mv_polynomial.not_mem_support_iff.1 ha, add_zero] using hs a },
have := hs i,
rw [coeff_add, coeff_monomial] at this,
split_ifs at this with h h,
{ subst h,
rw [mv_polynomial.not_mem_support_iff.1 ha, map_zero],
exact zero_mem _ },
{ rwa zero_add at this }
end
theorem eval_mem {p : mv_polynomial σ S} {s : subS}
(hs : ∀ i ∈ p.support, p.coeff i ∈ s) {v : σ → S} (hv : ∀ i, v i ∈ s) :
mv_polynomial.eval v p ∈ s :=
eval₂_mem hs hv
end eval_mem
end comm_semiring
end mv_polynomial
|
9c8dd254c5d63375a07716ce0ec3d68d582b4655 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/algebra/module/pid.lean | fe80596510b4af0b422a79b88203826387c119d2 | [
"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 | 13,723 | lean | /-
Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pierre-Alexandre Bazin
-/
import algebra.module.dedekind_domain
import linear_algebra.free_module.pid
import algebra.module.projective
import algebra.category.Module.biproducts
/-!
# Structure of finitely generated modules over a PID
## Main statements
* `module.equiv_direct_sum_of_is_torsion` : A finitely generated torsion module over a PID is
isomorphic to a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.
* `module.equiv_free_prod_direct_sum` : A finitely generated module over a PID is isomorphic to the
product of a free module (its torsion free part) and a direct sum of the form above (its torsion
submodule).
## Notation
* `R` is a PID and `M` is a (finitely generated for main statements) `R`-module, with additional
torsion hypotheses in the intermediate lemmas.
* `N` is a `R`-module lying over a higher type universe than `R`. This assumption is needed on the
final statement for technical reasons.
* `p` is an irreducible element of `R` or a tuple of these.
## Implementation details
We first prove (`submodule.is_internal_prime_power_torsion_of_pid`) that a finitely generated
torsion module is the internal direct sum of its `p i ^ e i`-torsion submodules for some
(finitely many) prime powers `p i ^ e i`. This is proved in more generality for a Dedekind domain
at `submodule.is_internal_prime_power_torsion`.
Then we treat the case of a `p ^ ∞`-torsion module (that is, a module where all elements are
cancelled by scalar multiplication by some power of `p`) and apply it to the `p i ^ e i`-torsion
submodules (that are `p i ^ ∞`-torsion) to get the result for torsion modules.
Then we get the general result using that a torsion free module is free (which has been proved at
`module.free_of_finite_type_torsion_free'` at `linear_algebra/free_module/pid.lean`.)
## Tags
Finitely generated module, principal ideal domain, classification, structure theorem
-/
universes u v
open_locale big_operators classical
variables {R : Type u} [comm_ring R] [is_domain R] [is_principal_ideal_ring R]
variables {M : Type v} [add_comm_group M] [module R M]
variables {N : Type (max u v)} [add_comm_group N] [module R N]
open_locale direct_sum
open submodule
open unique_factorization_monoid
/--A finitely generated torsion module over a PID is an internal direct sum of its
`p i ^ e i`-torsion submodules for some primes `p i` and numbers `e i`.-/
theorem submodule.is_internal_prime_power_torsion_of_pid
[module.finite R M] (hM : module.is_torsion R M) :
direct_sum.is_internal (λ p : (factors (⊤ : submodule R M).annihilator).to_finset,
torsion_by R M
(is_principal.generator (p : ideal R)
^ (factors (⊤ : submodule R M).annihilator).count p)) :=
begin
convert is_internal_prime_power_torsion hM,
ext p : 1,
rw [← torsion_by_span_singleton_eq, ideal.submodule_span_eq, ← ideal.span_singleton_pow,
ideal.span_singleton_generator],
end
/--A finitely generated torsion module over a PID is an internal direct sum of its
`p i ^ e i`-torsion submodules for some primes `p i` and numbers `e i`.-/
theorem submodule.exists_is_internal_prime_power_torsion_of_pid
[module.finite R M] (hM : module.is_torsion R M) :
∃ (ι : Type u) [fintype ι] [decidable_eq ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ),
by exactI direct_sum.is_internal (λ i, torsion_by R M $ p i ^ e i) :=
begin
refine ⟨_, _, _, _, _, _, submodule.is_internal_prime_power_torsion_of_pid hM⟩,
exact finset.fintype_coe_sort _,
{ rintro ⟨p, hp⟩,
have hP := prime_of_factor p (multiset.mem_to_finset.mp hp),
haveI := ideal.is_prime_of_prime hP,
exact (is_principal.prime_generator_of_is_prime p hP.ne_zero).irreducible },
end
namespace module
section p_torsion
variables {p : R} (hp : irreducible p) (hM : module.is_torsion' M (submonoid.powers p))
variables [dec : Π x : M, decidable (x = 0)]
open ideal submodule.is_principal
include dec
include hp hM
lemma _root_.ideal.torsion_of_eq_span_pow_p_order (x : M) :
torsion_of R M x = span {p ^ p_order hM x} :=
begin
dunfold p_order,
rw [← (torsion_of R M x).span_singleton_generator, ideal.span_singleton_eq_span_singleton,
← associates.mk_eq_mk_iff_associated, associates.mk_pow],
have prop : (λ n : ℕ, p ^ n • x = 0) =
λ n : ℕ, (associates.mk $ generator $ torsion_of R M x) ∣ associates.mk p ^ n,
{ ext n, rw [← associates.mk_pow, associates.mk_dvd_mk, ← mem_iff_generator_dvd], refl },
have := (is_torsion'_powers_iff p).mp hM x, rw prop at this,
classical,
convert associates.eq_pow_find_of_dvd_irreducible_pow ((associates.irreducible_mk p).mpr hp)
this.some_spec,
end
lemma p_pow_smul_lift {x y : M} {k : ℕ} (hM' : module.is_torsion_by R M (p ^ p_order hM y))
(h : p ^ k • x ∈ R ∙ y) : ∃ a : R, p ^ k • x = p ^ k • a • y :=
begin
by_cases hk : k ≤ p_order hM y,
{ let f := ((R ∙ p ^ (p_order hM y - k) * p ^ k).quot_equiv_of_eq _ _).trans
(quot_torsion_of_equiv_span_singleton R M y),
have : f.symm ⟨p ^ k • x, h⟩ ∈
R ∙ ideal.quotient.mk (R ∙ p ^ (p_order hM y - k) * p ^ k) (p ^ k),
{ rw [← quotient.torsion_by_eq_span_singleton, mem_torsion_by_iff, ← f.symm.map_smul],
convert f.symm.map_zero, ext,
rw [coe_smul_of_tower, coe_mk, coe_zero, smul_smul, ← pow_add, nat.sub_add_cancel hk, @hM' x],
{ exact mem_non_zero_divisors_of_ne_zero (pow_ne_zero _ hp.ne_zero) } },
rw submodule.mem_span_singleton at this, obtain ⟨a, ha⟩ := this, use a,
rw [f.eq_symm_apply, ← ideal.quotient.mk_eq_mk, ← quotient.mk_smul] at ha,
dsimp only [smul_eq_mul, f, linear_equiv.trans_apply, submodule.quot_equiv_of_eq_mk,
quot_torsion_of_equiv_span_singleton_apply_mk] at ha,
rw [smul_smul, mul_comm], exact congr_arg coe ha.symm,
{ symmetry, convert ideal.torsion_of_eq_span_pow_p_order hp hM y,
rw [← pow_add, nat.sub_add_cancel hk] } },
{ use 0, rw [zero_smul, smul_zero, ← nat.sub_add_cancel (le_of_not_le hk),
pow_add, mul_smul, hM', smul_zero] }
end
open submodule.quotient
lemma exists_smul_eq_zero_and_mk_eq {z : M} (hz : module.is_torsion_by R M (p ^ p_order hM z))
{k : ℕ} (f : (R ⧸ R ∙ p ^ k) →ₗ[R] M ⧸ R ∙ z) :
∃ x : M, p ^ k • x = 0 ∧ submodule.quotient.mk x = f 1 :=
begin
have f1 := mk_surjective (R ∙ z) (f 1),
have : p ^ k • f1.some ∈ R ∙ z,
{ rw [← quotient.mk_eq_zero, mk_smul, f1.some_spec, ← f.map_smul],
convert f.map_zero, change _ • submodule.quotient.mk _ = _,
rw [← mk_smul, quotient.mk_eq_zero, algebra.id.smul_eq_mul, mul_one],
exact submodule.mem_span_singleton_self _ },
obtain ⟨a, ha⟩ := p_pow_smul_lift hp hM hz this,
refine ⟨f1.some - a • z, by rw [smul_sub, sub_eq_zero, ha], _⟩,
rw [mk_sub, mk_smul, (quotient.mk_eq_zero _).mpr $ submodule.mem_span_singleton_self _,
smul_zero, sub_zero, f1.some_spec]
end
open finset multiset
omit dec hM
/--A finitely generated `p ^ ∞`-torsion module over a PID is isomorphic to a direct sum of some
`R ⧸ R ∙ (p ^ e i)` for some `e i`.-/
theorem torsion_by_prime_power_decomposition (hN : module.is_torsion' N (submonoid.powers p))
[h' : module.finite R N] :
∃ (d : ℕ) (k : fin d → ℕ), nonempty $ N ≃ₗ[R] ⨁ (i : fin d), R ⧸ R ∙ (p ^ (k i : ℕ)) :=
begin
obtain ⟨d, s, hs⟩ := @module.finite.exists_fin _ _ _ _ _ h', use d, clear h',
unfreezingI { induction d with d IH generalizing N },
{ use λ i, fin_zero_elim i,
rw [set.range_eq_empty, submodule.span_empty] at hs,
haveI : unique N := ⟨⟨0⟩, λ x, by { rw [← mem_bot _, hs], trivial }⟩,
exact ⟨0⟩ },
{ haveI : Π x : N, decidable (x = 0), classical, apply_instance,
obtain ⟨j, hj⟩ := exists_is_torsion_by hN d.succ d.succ_ne_zero s hs,
let s' : fin d → N ⧸ R ∙ s j := submodule.quotient.mk ∘ s ∘ j.succ_above,
obtain ⟨k, ⟨f⟩⟩ := IH _ s' _; clear IH,
{ have : ∀ i : fin d, ∃ x : N,
p ^ k i • x = 0 ∧ f (submodule.quotient.mk x) = direct_sum.lof R _ _ i 1,
{ intro i,
let fi := f.symm.to_linear_map.comp (direct_sum.lof _ _ _ i),
obtain ⟨x, h0, h1⟩ := exists_smul_eq_zero_and_mk_eq hp hN hj fi, refine ⟨x, h0, _⟩, rw h1,
simp only [linear_map.coe_comp, f.symm.coe_to_linear_map, f.apply_symm_apply] },
refine ⟨_, ⟨(((
@lequiv_prod_of_right_split_exact _ _ _ _ _ _ _ _ _ _ _ _
((f.trans ulift.module_equiv.{u u v}.symm).to_linear_map.comp $ mkq _)
((direct_sum.to_module _ _ _ $ λ i, (liftq_span_singleton.{u u} (p ^ k i)
(linear_map.to_span_singleton _ _ _) (this i).some_spec.left : R ⧸ _ →ₗ[R] _)).comp
ulift.module_equiv.to_linear_map)
(R ∙ s j).injective_subtype _ _).symm.trans $
((quot_torsion_of_equiv_span_singleton _ _ _).symm.trans $
quot_equiv_of_eq _ _ $ ideal.torsion_of_eq_span_pow_p_order hp hN _).prod $
ulift.module_equiv).trans $
(@direct_sum.lequiv_prod_direct_sum R _ _ _
(λ i, R ⧸ R ∙ p ^ @option.rec _ (λ _, ℕ) (p_order hN $ s j) k i) _ _).symm).trans $
direct_sum.lequiv_congr_left R (fin_succ_equiv d).symm⟩⟩,
{ rw [range_subtype, linear_equiv.to_linear_map_eq_coe, linear_equiv.ker_comp, ker_mkq] },
{ rw [linear_equiv.to_linear_map_eq_coe, ← f.comp_coe, linear_map.comp_assoc,
linear_map.comp_assoc, ← linear_equiv.to_linear_map_eq_coe,
linear_equiv.to_linear_map_symm_comp_eq, linear_map.comp_id,
← linear_map.comp_assoc, ← linear_map.comp_assoc],
suffices : (f.to_linear_map.comp (R ∙ s j).mkq).comp _ = linear_map.id,
{ rw [← f.to_linear_map_eq_coe, this, linear_map.id_comp] },
ext i : 3,
simp only [linear_map.coe_comp, function.comp_app, mkq_apply],
rw [linear_equiv.coe_to_linear_map, linear_map.id_apply, direct_sum.to_module_lof,
liftq_span_singleton_apply, linear_map.to_span_singleton_one,
ideal.quotient.mk_eq_mk, map_one, (this i).some_spec.right] } },
{ exact (mk_surjective _).forall.mpr
(λ x, ⟨(@hN x).some, by rw [← quotient.mk_smul, (@hN x).some_spec, quotient.mk_zero]⟩) },
{ have hs' := congr_arg (submodule.map $ mkq $ R ∙ s j) hs,
rw [submodule.map_span, submodule.map_top, range_mkq] at hs', simp only [mkq_apply] at hs',
simp only [s'], rw [set.range_comp (_ ∘ s), fin.range_succ_above],
rw [← set.range_comp, ← set.insert_image_compl_eq_range _ j, function.comp_apply,
(quotient.mk_eq_zero _).mpr (submodule.mem_span_singleton_self _), span_insert_zero] at hs',
exact hs' } }
end
end p_torsion
/--A finitely generated torsion module over a PID is isomorphic to a direct sum of some
`R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/
theorem equiv_direct_sum_of_is_torsion [h' : module.finite R N] (hN : module.is_torsion R N) :
∃ (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ),
nonempty $ N ≃ₗ[R] ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) :=
begin
obtain ⟨I, fI, _, p, hp, e, h⟩ := submodule.exists_is_internal_prime_power_torsion_of_pid hN,
haveI := fI,
have : ∀ i, ∃ (d : ℕ) (k : fin d → ℕ),
nonempty $ torsion_by R N (p i ^ e i) ≃ₗ[R] ⨁ j, R ⧸ R ∙ (p i ^ k j),
{ haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'),
haveI := λ i, is_noetherian_submodule' (torsion_by R N $ p i ^ e i),
exact λ i, torsion_by_prime_power_decomposition (hp i)
((is_torsion'_powers_iff $ p i).mpr $ λ x, ⟨e i, smul_torsion_by _ _⟩) },
classical,
refine ⟨Σ i, fin (this i).some, infer_instance,
λ ⟨i, j⟩, p i, λ ⟨i, j⟩, hp i, λ ⟨i, j⟩, (this i).some_spec.some j,
⟨(linear_equiv.of_bijective (direct_sum.coe_linear_map _) h).symm.trans $
(dfinsupp.map_range.linear_equiv $ λ i, (this i).some_spec.some_spec.some).trans $
(direct_sum.sigma_lcurry_equiv R).symm.trans
(dfinsupp.map_range.linear_equiv $ λ i, quot_equiv_of_eq _ _ _)⟩⟩,
cases i with i j, simp only
end
/--**Structure theorem of finitely generated modules over a PID** : A finitely generated
module over a PID is isomorphic to the product of a free module and a direct sum of some
`R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/
theorem equiv_free_prod_direct_sum [h' : module.finite R N] :
∃ (n : ℕ) (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ),
nonempty $ N ≃ₗ[R] (fin n →₀ R) × ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) :=
begin
haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'),
haveI := is_noetherian_submodule' (torsion R N),
haveI := module.finite.of_surjective _ (torsion R N).mkq_surjective,
obtain ⟨I, fI, p, hp, e, ⟨h⟩⟩ := equiv_direct_sum_of_is_torsion (@torsion_is_torsion R N _ _ _),
obtain ⟨n, ⟨g⟩⟩ := @module.basis_of_finite_type_torsion_free' R _ _ _ (N ⧸ torsion R N) _ _ _ _,
haveI : module.projective R (N ⧸ torsion R N) := module.projective_of_basis ⟨g⟩,
obtain ⟨f, hf⟩ := module.projective_lifting_property _ linear_map.id (torsion R N).mkq_surjective,
refine ⟨n, I, fI, p, hp, e,
⟨(lequiv_prod_of_right_split_exact (torsion R N).injective_subtype _ hf).symm.trans $
(h.prod g).trans $ linear_equiv.prod_comm R _ _⟩⟩,
rw [range_subtype, ker_mkq]
end
end module
|
a9ee028d07bd7c56dce7c7a9cd4903720dded2b6 | 1abd1ed12aa68b375cdef28959f39531c6e95b84 | /src/category_theory/sites/pretopology.lean | 267b5b235b547a5232093c7e99c6ac0084d72a81 | [
"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 | 7,267 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.grothendieck
/-!
# Grothendieck pretopologies
Definition and lemmas about Grothendieck pretopologies.
A Grothendieck pretopology for a category `C` is a set of families of morphisms with fixed codomain,
satisfying certain closure conditions.
We show that a pretopology generates a genuine Grothendieck topology, and every topology has
a maximal pretopology which generates it.
The pretopology associated to a topological space is defined in `spaces.lean`.
## Tags
coverage, pretopology, site
## References
* [https://ncatlab.org/nlab/show/Grothendieck+pretopology][nlab]
* [S. MacLane, I. Moerdijk, *Sheaves in Geometry and Logic*][MM92]
* [https://stacks.math.columbia.edu/tag/00VG][Stacks]
-/
universes v u
noncomputable theory
namespace category_theory
open category_theory category limits presieve
variables {C : Type u} [category.{v} C] [has_pullbacks C]
variables (C)
/--
A (Grothendieck) pretopology on `C` consists of a collection of families of morphisms with a fixed
target `X` for every object `X` in `C`, called "coverings" of `X`, which satisfies the following
three axioms:
1. Every family consisting of a single isomorphism is a covering family.
2. The collection of covering families is stable under pullback.
3. Given a covering family, and a covering family on each domain of the former, the composition
is a covering family.
In some sense, a pretopology can be seen as Grothendieck topology with weaker saturation conditions,
in that each covering is not necessarily downward closed.
See: https://ncatlab.org/nlab/show/Grothendieck+pretopology, or
https://stacks.math.columbia.edu/tag/00VH, or [MM92] Chapter III, Section 2, Definition 2.
Note that Stacks calls a category together with a pretopology a site, and [MM92] calls this
a basis for a topology.
-/
@[ext]
structure pretopology :=
(coverings : Π (X : C), set (presieve X))
(has_isos : ∀ ⦃X Y⦄ (f : Y ⟶ X) [is_iso f], presieve.singleton f ∈ coverings X)
(pullbacks : ∀ ⦃X Y⦄ (f : Y ⟶ X) S, S ∈ coverings X → pullback_arrows f S ∈ coverings Y)
(transitive : ∀ ⦃X : C⦄ (S : presieve X)
(Ti : Π ⦃Y⦄ (f : Y ⟶ X), S f → presieve Y), S ∈ coverings X →
(∀ ⦃Y⦄ f (H : S f), Ti f H ∈ coverings Y) → S.bind Ti ∈ coverings X)
namespace pretopology
instance : has_coe_to_fun (pretopology C) (λ _, Π X : C, set (presieve X)) := ⟨coverings⟩
instance : partial_order (pretopology C) :=
{ le := λ K₁ K₂, (K₁ : Π (X : C), set _) ≤ K₂,
le_refl := λ K, le_refl _,
le_trans := λ K₁ K₂ K₃ h₁₂ h₂₃, le_trans h₁₂ h₂₃,
le_antisymm := λ K₁ K₂ h₁₂ h₂₁, pretopology.ext _ _ (le_antisymm h₁₂ h₂₁) }
instance : order_top (pretopology C) :=
{ top :=
{ coverings := λ _, set.univ,
has_isos := λ _ _ _ _, set.mem_univ _,
pullbacks := λ _ _ _ _ _, set.mem_univ _,
transitive := λ _ _ _ _ _, set.mem_univ _ },
le_top := λ K X S hS, set.mem_univ _,
..pretopology.partial_order C }
instance : inhabited (pretopology C) := ⟨⊤⟩
/--
A pretopology `K` can be completed to a Grothendieck topology `J` by declaring a sieve to be
`J`-covering if it contains a family in `K`.
See https://stacks.math.columbia.edu/tag/00ZC, or [MM92] Chapter III, Section 2, Equation (2).
-/
def to_grothendieck (K : pretopology C) : grothendieck_topology C :=
{ sieves := λ X S, ∃ R ∈ K X, R ≤ (S : presieve _),
top_mem' := λ X, ⟨presieve.singleton (𝟙 _), K.has_isos _, λ _ _ _, ⟨⟩⟩,
pullback_stable' := λ X Y S g,
begin
rintro ⟨R, hR, RS⟩,
refine ⟨_, K.pullbacks g _ hR, _⟩,
rw [← sieve.sets_iff_generate, sieve.pullback_arrows_comm],
apply sieve.pullback_monotone,
rwa sieve.gi_generate.gc,
end,
transitive' :=
begin
rintro X S ⟨R', hR', RS⟩ R t,
choose t₁ t₂ t₃ using t,
refine ⟨_, K.transitive _ _ hR' (λ _ f hf, t₂ (RS _ hf)), _⟩,
rintro Y _ ⟨Z, g, f, hg, hf, rfl⟩,
apply t₃ (RS _ hg) _ hf,
end }
lemma mem_to_grothendieck (K : pretopology C) (X S) :
S ∈ to_grothendieck C K X ↔ ∃ R ∈ K X, R ≤ (S : presieve X) :=
iff.rfl
/--
The largest pretopology generating the given Grothendieck topology.
See [MM92] Chapter III, Section 2, Equations (3,4).
-/
def of_grothendieck (J : grothendieck_topology C) : pretopology C :=
{ coverings := λ X R, sieve.generate R ∈ J X,
has_isos := λ X Y f i, by exactI J.covering_of_eq_top (by simp),
pullbacks := λ X Y f R hR,
begin
rw [set.mem_def, sieve.pullback_arrows_comm],
apply J.pullback_stable f hR,
end,
transitive := λ X S Ti hS hTi,
begin
apply J.transitive hS,
intros Y f,
rintros ⟨Z, g, f, hf, rfl⟩,
rw sieve.pullback_comp,
apply J.pullback_stable g,
apply J.superset_covering _ (hTi _ hf),
rintro Y g ⟨W, h, g, hg, rfl⟩,
exact ⟨_, h, _, ⟨_, _, _, hf, hg, rfl⟩, by simp⟩,
end }
/-- We have a galois insertion from pretopologies to Grothendieck topologies. -/
def gi : galois_insertion (to_grothendieck C) (of_grothendieck C) :=
{ gc :=
λ K J,
begin
split,
{ intros h X R hR,
exact h _ ⟨_, hR, sieve.le_generate R⟩ },
{ rintro h X S ⟨R, hR, RS⟩,
apply J.superset_covering _ (h _ hR),
rwa sieve.gi_generate.gc }
end,
le_l_u := λ J X S hS, ⟨S, J.superset_covering S.le_generate hS, le_refl _⟩,
choice := λ x hx, to_grothendieck C x,
choice_eq := λ _ _, rfl }
/--
The trivial pretopology, in which the coverings are exactly singleton isomorphisms. This topology is
also known as the indiscrete, coarse, or chaotic topology.
See https://stacks.math.columbia.edu/tag/07GE
-/
def trivial : pretopology C :=
{ coverings := λ X S, ∃ Y (f : Y ⟶ X) (h : is_iso f), S = presieve.singleton f,
has_isos := λ X Y f i, ⟨_, _, i, rfl⟩,
pullbacks := λ X Y f S,
begin
rintro ⟨Z, g, i, rfl⟩,
refine ⟨pullback g f, pullback.snd, _, _⟩,
{ resetI, refine ⟨⟨pullback.lift (f ≫ inv g) (𝟙 _) (by simp), ⟨_, by tidy⟩⟩⟩,
apply pullback.hom_ext,
{ rw [assoc, pullback.lift_fst, ←pullback.condition_assoc],
simp },
{ simp } },
{ apply pullback_singleton },
end,
transitive :=
begin
rintro X S Ti ⟨Z, g, i, rfl⟩ hS,
rcases hS g (singleton_self g) with ⟨Y, f, i, hTi⟩,
refine ⟨_, f ≫ g, _, _⟩,
{ resetI, apply_instance },
ext W k,
split,
{ rintro ⟨V, h, k, ⟨_⟩, hh, rfl⟩,
rw hTi at hh,
cases hh,
apply singleton.mk },
{ rintro ⟨_⟩,
refine bind_comp g presieve.singleton.mk _,
rw hTi,
apply presieve.singleton.mk }
end }
instance : order_bot (pretopology C) :=
{ bot := trivial C,
bot_le := λ K X R,
begin
rintro ⟨Y, f, hf, rfl⟩,
exactI K.has_isos f,
end,
..pretopology.partial_order C }
/-- The trivial pretopology induces the trivial grothendieck topology. -/
lemma to_grothendieck_bot : to_grothendieck C ⊥ = ⊥ :=
(gi C).gc.l_bot
end pretopology
end category_theory
|
766b1e9a8e592f5d2cfe14bd206f5c1f51769eb0 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /library/init/category/transformers.lean | 842d9cd55302457c4cd5f1aa5cafbc975ff05813 | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 1,620 | lean | /-
Copyright (c) 2016 Gabriel Ebner. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner
-/
prelude
import init.category.state init.function init.coe
namespace monad
class monad_transformer (transformer : ∀m [monad m], Type → Type) :=
(is_monad : ∀m [monad m], monad (transformer m))
(monad_lift : ∀m [monad m] α, m α → transformer m α)
instance transformed_monad (m t) [monad_transformer t] [monad m] : monad (t m) :=
monad_transformer.is_monad t m
class has_monad_lift (m n : Type → Type) :=
(monad_lift : ∀α, m α → n α)
instance monad_transformer_lift (t m) [monad_transformer t] [monad m] : has_monad_lift m (t m) :=
⟨monad_transformer.monad_lift t m⟩
class has_monad_lift_t (m n : Type → Type) :=
(monad_lift : ∀α, m α → n α)
def monad_lift {m n} [has_monad_lift_t m n] {α} : m α → n α :=
has_monad_lift_t.monad_lift n α
@[reducible] def has_monad_lift_to_has_coe {m n} [has_monad_lift_t m n] {α} : has_coe (m α) (n α) :=
⟨monad_lift⟩
instance has_monad_lift_t_trans (m n o) [has_monad_lift n o] [has_monad_lift_t m n] : has_monad_lift_t m o :=
⟨ λα (ma : m α), has_monad_lift.monad_lift o α $ has_monad_lift_t.monad_lift n α ma ⟩
instance has_monad_lift_t_refl (m) [monad m] : has_monad_lift_t m m :=
⟨ λα, id ⟩
end monad
namespace state_t
def state_t_monad_lift (S) (m) [monad m] (α) (f : m α) : state_t S m α :=
assume state, do res ← f, return (res, state)
instance (S) : monad.monad_transformer (state_t S) :=
⟨ state_t.monad S, state_t_monad_lift S ⟩
end state_t
|
34f35255d6a3bb2e16c022f6da414c0c80e20cf6 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/ring/opposite.lean | 7363824c72da6ae50549436e355402467a91aa8e | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 11,454 | 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 algebra.group.opposite
import algebra.hom.ring
/-!
# Ring structures on the multiplicative opposite
-/
universes u v
variables (α : Type u)
namespace mul_opposite
instance [distrib α] : distrib αᵐᵒᵖ :=
{ left_distrib := λ x y z, unop_injective $ add_mul (unop y) (unop z) (unop x),
right_distrib := λ x y z, unop_injective $ mul_add (unop z) (unop x) (unop y),
.. mul_opposite.has_add α, .. mul_opposite.has_mul α }
instance [mul_zero_class α] : mul_zero_class αᵐᵒᵖ :=
{ zero := 0,
mul := (*),
zero_mul := λ x, unop_injective $ mul_zero $ unop x,
mul_zero := λ x, unop_injective $ zero_mul $ unop x }
instance [mul_zero_one_class α] : mul_zero_one_class αᵐᵒᵖ :=
{ .. mul_opposite.mul_zero_class α, .. mul_opposite.mul_one_class α }
instance [semigroup_with_zero α] : semigroup_with_zero αᵐᵒᵖ :=
{ .. mul_opposite.semigroup α, .. mul_opposite.mul_zero_class α }
instance [monoid_with_zero α] : monoid_with_zero αᵐᵒᵖ :=
{ .. mul_opposite.monoid α, .. mul_opposite.mul_zero_one_class α }
instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵐᵒᵖ :=
{ .. mul_opposite.add_comm_monoid α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α }
instance [non_unital_semiring α] : non_unital_semiring αᵐᵒᵖ :=
{ .. mul_opposite.semigroup_with_zero α, .. mul_opposite.non_unital_non_assoc_semiring α }
instance [non_assoc_semiring α] : non_assoc_semiring αᵐᵒᵖ :=
{ .. mul_opposite.add_monoid_with_one α, .. mul_opposite.mul_zero_one_class α,
.. mul_opposite.non_unital_non_assoc_semiring α }
instance [semiring α] : semiring αᵐᵒᵖ :=
{ .. mul_opposite.non_unital_semiring α, .. mul_opposite.non_assoc_semiring α,
.. mul_opposite.monoid_with_zero α }
instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵐᵒᵖ :=
{ .. mul_opposite.non_unital_semiring α, .. mul_opposite.comm_semigroup α }
instance [comm_semiring α] : comm_semiring αᵐᵒᵖ :=
{ .. mul_opposite.semiring α, .. mul_opposite.comm_semigroup α }
instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵐᵒᵖ :=
{ .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_class α, .. mul_opposite.distrib α}
instance [non_unital_ring α] : non_unital_ring αᵐᵒᵖ :=
{ .. mul_opposite.add_comm_group α, .. mul_opposite.semigroup_with_zero α,
.. mul_opposite.distrib α}
instance [non_assoc_ring α] : non_assoc_ring αᵐᵒᵖ :=
{ .. mul_opposite.add_comm_group α, .. mul_opposite.mul_zero_one_class α, .. mul_opposite.distrib α,
.. mul_opposite.add_group_with_one α }
instance [ring α] : ring αᵐᵒᵖ :=
{ .. mul_opposite.monoid α, .. mul_opposite.non_assoc_ring α }
instance [non_unital_comm_ring α] : non_unital_comm_ring αᵐᵒᵖ :=
{ .. mul_opposite.non_unital_ring α, .. mul_opposite.non_unital_comm_semiring α }
instance [comm_ring α] : comm_ring αᵐᵒᵖ :=
{ .. mul_opposite.ring α, .. mul_opposite.comm_semiring α }
instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵐᵒᵖ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)),
or.cases_on (eq_zero_or_eq_zero_of_mul_eq_zero $ op_injective H)
(λ hy, or.inr $ unop_injective $ hy) (λ hx, or.inl $ unop_injective $ hx), }
instance [ring α] [is_domain α] : is_domain αᵐᵒᵖ :=
{ .. mul_opposite.no_zero_divisors α, .. mul_opposite.ring α, .. mul_opposite.nontrivial α }
instance [group_with_zero α] : group_with_zero αᵐᵒᵖ :=
{ mul_inv_cancel := λ x hx, unop_injective $ inv_mul_cancel $ unop_injective.ne hx,
inv_zero := unop_injective inv_zero,
.. mul_opposite.monoid_with_zero α, .. mul_opposite.div_inv_monoid α,
.. mul_opposite.nontrivial α }
end mul_opposite
namespace add_opposite
instance [distrib α] : distrib αᵃᵒᵖ :=
{ left_distrib := λ x y z, unop_injective $ @mul_add α _ _ _ x z y,
right_distrib := λ x y z, unop_injective $ @add_mul α _ _ _ y x z,
.. add_opposite.has_add α, .. @add_opposite.has_mul α _}
instance [mul_zero_class α] : mul_zero_class αᵃᵒᵖ :=
{ zero := 0,
mul := (*),
zero_mul := λ x, unop_injective $ zero_mul $ unop x,
mul_zero := λ x, unop_injective $ mul_zero $ unop x }
instance [mul_zero_one_class α] : mul_zero_one_class αᵃᵒᵖ :=
{ .. add_opposite.mul_zero_class α, .. add_opposite.mul_one_class α }
instance [semigroup_with_zero α] : semigroup_with_zero αᵃᵒᵖ :=
{ .. add_opposite.semigroup α, .. add_opposite.mul_zero_class α }
instance [monoid_with_zero α] : monoid_with_zero αᵃᵒᵖ :=
{ .. add_opposite.monoid α, .. add_opposite.mul_zero_one_class α }
instance [non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵃᵒᵖ :=
{ .. add_opposite.add_comm_monoid α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α }
instance [non_unital_semiring α] : non_unital_semiring αᵃᵒᵖ :=
{ .. add_opposite.semigroup_with_zero α, .. add_opposite.non_unital_non_assoc_semiring α }
instance [non_assoc_semiring α] : non_assoc_semiring αᵃᵒᵖ :=
{ .. add_opposite.mul_zero_one_class α, .. add_opposite.non_unital_non_assoc_semiring α }
instance [semiring α] : semiring αᵃᵒᵖ :=
{ .. add_opposite.non_unital_semiring α, .. add_opposite.non_assoc_semiring α,
.. add_opposite.monoid_with_zero α }
instance [non_unital_comm_semiring α] : non_unital_comm_semiring αᵃᵒᵖ :=
{ .. add_opposite.non_unital_semiring α, .. add_opposite.comm_semigroup α }
instance [comm_semiring α] : comm_semiring αᵃᵒᵖ :=
{ .. add_opposite.semiring α, .. add_opposite.comm_semigroup α }
instance [non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵃᵒᵖ :=
{ .. add_opposite.add_comm_group α, .. add_opposite.mul_zero_class α, .. add_opposite.distrib α}
instance [non_unital_ring α] : non_unital_ring αᵃᵒᵖ :=
{ .. add_opposite.add_comm_group α, .. add_opposite.semigroup_with_zero α,
.. add_opposite.distrib α}
instance [non_assoc_ring α] : non_assoc_ring αᵃᵒᵖ :=
{ .. add_opposite.add_comm_group α, .. add_opposite.mul_zero_one_class α, .. add_opposite.distrib α}
instance [ring α] : ring αᵃᵒᵖ :=
{ .. add_opposite.add_comm_group α, .. add_opposite.monoid α, .. add_opposite.semiring α }
instance [non_unital_comm_ring α] : non_unital_comm_ring αᵃᵒᵖ :=
{ .. add_opposite.non_unital_ring α, .. add_opposite.non_unital_comm_semiring α }
instance [comm_ring α] : comm_ring αᵃᵒᵖ :=
{ .. add_opposite.ring α, .. add_opposite.comm_semiring α }
instance [has_zero α] [has_mul α] [no_zero_divisors α] : no_zero_divisors αᵃᵒᵖ :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ x y (H : op (_ * _) = op (0:α)),
or.imp (λ hx, unop_injective hx) (λ hy, unop_injective hy)
((@eq_zero_or_eq_zero_of_mul_eq_zero α _ _ _ _ _) $ op_injective H) }
instance [ring α] [is_domain α] : is_domain αᵃᵒᵖ :=
{ .. add_opposite.no_zero_divisors α, .. add_opposite.ring α, .. add_opposite.nontrivial α }
instance [group_with_zero α] : group_with_zero αᵃᵒᵖ :=
{ mul_inv_cancel := λ x hx, unop_injective $ mul_inv_cancel $ unop_injective.ne hx,
inv_zero := unop_injective inv_zero,
.. add_opposite.monoid_with_zero α, .. add_opposite.div_inv_monoid α,
.. add_opposite.nontrivial α }
end add_opposite
open mul_opposite
/-- A non-unital ring homomorphism `f : R →ₙ+* S` such that `f x` commutes with `f y` for all `x, y`
defines a non-unital ring homomorphism to `Sᵐᵒᵖ`. -/
@[simps {fully_applied := ff}]
def non_unital_ring_hom.to_opposite {R S : Type*} [non_unital_non_assoc_semiring R]
[non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) :
R →ₙ+* Sᵐᵒᵖ :=
{ to_fun := mul_opposite.op ∘ f,
.. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ),
.. f.to_mul_hom.to_opposite hf }
/-- A non-unital ring homomorphism `f : R →ₙ* S` such that `f x` commutes with `f y` for all `x, y`
defines a non-unital ring homomorphism from `Rᵐᵒᵖ`. -/
@[simps {fully_applied := ff}]
def non_unital_ring_hom.from_opposite {R S : Type*} [non_unital_non_assoc_semiring R]
[non_unital_non_assoc_semiring S] (f : R →ₙ+* S) (hf : ∀ x y, commute (f x) (f y)) :
Rᵐᵒᵖ →ₙ+* S :=
{ to_fun := f ∘ mul_opposite.unop,
.. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S),
.. f.to_mul_hom.from_opposite hf }
/-- A non-unital ring hom `α →ₙ+* β` can equivalently be viewed as a non-unital ring hom
`αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/
@[simps]
def non_unital_ring_hom.op {α β} [non_unital_non_assoc_semiring α]
[non_unital_non_assoc_semiring β] : (α →ₙ+* β) ≃ (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) :=
{ to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_mul_hom.op },
inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_mul_hom.unop },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of a non-unital ring hom `αᵐᵒᵖ →ₙ+* βᵐᵒᵖ`. Inverse to
`non_unital_ring_hom.op`. -/
@[simp] def non_unital_ring_hom.unop {α β} [non_unital_non_assoc_semiring α]
[non_unital_non_assoc_semiring β] : (αᵐᵒᵖ →ₙ+* βᵐᵒᵖ) ≃ (α →ₙ+* β) := non_unital_ring_hom.op.symm
/-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines
a ring homomorphism to `Sᵐᵒᵖ`. -/
@[simps {fully_applied := ff}]
def ring_hom.to_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S)
(hf : ∀ x y, commute (f x) (f y)) : R →+* Sᵐᵒᵖ :=
{ to_fun := mul_opposite.op ∘ f,
.. ((op_add_equiv : S ≃+ Sᵐᵒᵖ).to_add_monoid_hom.comp ↑f : R →+ Sᵐᵒᵖ),
.. f.to_monoid_hom.to_opposite hf }
/-- A ring homomorphism `f : R →+* S` such that `f x` commutes with `f y` for all `x, y` defines
a ring homomorphism from `Rᵐᵒᵖ`. -/
@[simps {fully_applied := ff}]
def ring_hom.from_opposite {R S : Type*} [semiring R] [semiring S] (f : R →+* S)
(hf : ∀ x y, commute (f x) (f y)) : Rᵐᵒᵖ →+* S :=
{ to_fun := f ∘ mul_opposite.unop,
.. (f.to_add_monoid_hom.comp (op_add_equiv : R ≃+ Rᵐᵒᵖ).symm.to_add_monoid_hom : Rᵐᵒᵖ →+ S),
.. f.to_monoid_hom.from_opposite hf }
/-- A ring hom `α →+* β` can equivalently be viewed as a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. This is the
action of the (fully faithful) `ᵐᵒᵖ`-functor on morphisms. -/
@[simps]
def ring_hom.op {α β} [non_assoc_semiring α] [non_assoc_semiring β] :
(α →+* β) ≃ (αᵐᵒᵖ →+* βᵐᵒᵖ) :=
{ to_fun := λ f, { ..f.to_add_monoid_hom.mul_op, ..f.to_monoid_hom.op },
inv_fun := λ f, { ..f.to_add_monoid_hom.mul_unop, ..f.to_monoid_hom.unop },
left_inv := λ f, by { ext, refl },
right_inv := λ f, by { ext, simp } }
/-- The 'unopposite' of a ring hom `αᵐᵒᵖ →+* βᵐᵒᵖ`. Inverse to `ring_hom.op`. -/
@[simp] def ring_hom.unop {α β} [non_assoc_semiring α] [non_assoc_semiring β] :
(αᵐᵒᵖ →+* βᵐᵒᵖ) ≃ (α →+* β) := ring_hom.op.symm
|
9b305dc86fab2c01fb0daffef9e73c57401ba70a | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Lean/Data/Position.lean | f0d0746d0f7af291f4cce972fa43e9af2c36966e | [
"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 | 2,762 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Data.Nat
import Init.Data.RBMap
import Init.Lean.Data.Format
namespace Lean
structure Position :=
(line : Nat)
(column : Nat)
namespace Position
instance : DecidableEq Position :=
fun ⟨l₁, c₁⟩ ⟨l₂, c₂⟩ =>
if h₁ : l₁ = l₂ then
if h₂ : c₁ = c₂ then isTrue (Eq.recOn h₁ (Eq.recOn h₂ rfl))
else isFalse (fun contra => Position.noConfusion contra (fun e₁ e₂ => absurd e₂ h₂))
else isFalse (fun contra => Position.noConfusion contra (fun e₁ e₂ => absurd e₁ h₁))
protected def lt : Position → Position → Bool
| ⟨l₁, c₁⟩, ⟨l₂, c₂⟩ => (l₁, c₁) < (l₂, c₂)
instance : HasFormat Position :=
⟨fun ⟨l, c⟩ => "⟨" ++ fmt l ++ ", " ++ fmt c ++ "⟩"⟩
instance : HasToString Position :=
⟨fun ⟨l, c⟩ => "⟨" ++ toString l ++ ", " ++ toString c ++ "⟩"⟩
instance : Inhabited Position := ⟨⟨1, 0⟩⟩
end Position
structure FileMap :=
(source : String)
(positions : Array String.Pos)
(lines : Array Nat)
namespace FileMap
instance : Inhabited FileMap :=
⟨{ source := "", positions := #[], lines := #[] }⟩
private partial def ofStringAux (s : String) : String.Pos → Nat → Array String.Pos → Array Nat → FileMap
| i, line, ps, lines =>
if s.atEnd i then { source := s, positions := ps.push i, lines := lines.push line }
else
let c := s.get i;
let i := s.next i;
if c == '\n' then ofStringAux i (line+1) (ps.push i) (lines.push (line+1))
else ofStringAux i line ps lines
def ofString (s : String) : FileMap :=
ofStringAux s 0 1 (#[0]) (#[1])
private partial def toColumnAux (str : String) (lineBeginPos : String.Pos) (pos : String.Pos) : String.Pos → Nat → Nat
| i, c =>
if i == pos || str.atEnd i then c
else toColumnAux (str.next i) (c+1)
/- Remark: `pos` is in `[ps.get b, ps.get e]` and `b < e` -/
private partial def toPositionAux (str : String) (ps : Array Nat) (lines : Array Nat) (pos : String.Pos) : Nat → Nat → Position
| b, e =>
let posB := ps.get! b;
if e == b + 1 then { line := lines.get! b, column := toColumnAux str posB pos posB 0 }
else
let m := (b + e) / 2;
let posM := ps.get! m;
if pos == posM then { line := lines.get! m, column := 0 }
else if pos > posM then toPositionAux m e
else toPositionAux b m
def toPosition : FileMap → String.Pos → Position
| { source := str, positions := ps, lines := lines }, pos => toPositionAux str ps lines pos 0 (ps.size-1)
end FileMap
end Lean
def String.toFileMap (s : String) : Lean.FileMap :=
Lean.FileMap.ofString s
|
00c7cc71d7f8d225a23d417e820cd75a788a0ef9 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/int/cast.lean | dd553a423cb9f75ad4101419cfee22870a0e6b83 | [
"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 | 9,930 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.int.basic
import data.nat.cast
import tactic.pi_instances
import data.sum.basic
/-!
# Cast of integers (additional theorems)
This file proves additional properties about the *canonical* homomorphism from
the integers into an additive group with a one (`int.cast`).
## Main declarations
* `cast_add_hom`: `cast` bundled as an `add_monoid_hom`.
* `cast_ring_hom`: `cast` bundled as a `ring_hom`.
-/
open nat
namespace int
/-- Coercion `ℕ → ℤ` as a `ring_hom`. -/
def of_nat_hom : ℕ →+* ℤ := ⟨coe, rfl, int.of_nat_mul, rfl, int.of_nat_add⟩
section cast
variables {α : Type*}
@[simp, norm_cast] theorem cast_mul [non_assoc_ring α] : ∀ m n, ((m * n : ℤ) : α) = m * n :=
λ m, int.induction_on' m 0 (by simp) (λ k _ ih n, by simp [add_mul, ih])
(λ k _ ih n, by simp [sub_mul, ih])
@[simp, norm_cast] theorem cast_ite [add_group_with_one α] (P : Prop) [decidable P] (m n : ℤ) :
((ite P m n : ℤ) : α) = ite P m n :=
apply_ite _ _ _ _
/-- `coe : ℤ → α` as an `add_monoid_hom`. -/
def cast_add_hom (α : Type*) [add_group_with_one α] : ℤ →+ α := ⟨coe, cast_zero, cast_add⟩
@[simp] lemma coe_cast_add_hom [add_group_with_one α] : ⇑(cast_add_hom α) = coe := rfl
/-- `coe : ℤ → α` as a `ring_hom`. -/
def cast_ring_hom (α : Type*) [non_assoc_ring α] : ℤ →+* α :=
⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩
@[simp] lemma coe_cast_ring_hom [non_assoc_ring α] : ⇑(cast_ring_hom α) = coe := rfl
lemma cast_commute [non_assoc_ring α] : ∀ (m : ℤ) (x : α), commute ↑m x
| (n : ℕ) x := by simpa using n.cast_commute x
| -[1+ n] x := by simpa only [cast_neg_succ_of_nat, commute.neg_left_iff, commute.neg_right_iff]
using (n + 1).cast_commute (-x)
lemma cast_comm [non_assoc_ring α] (m : ℤ) (x : α) : (m : α) * x = x * m :=
(cast_commute m x).eq
lemma commute_cast [non_assoc_ring α] (x : α) (m : ℤ) : commute x m :=
(m.cast_commute x).symm
theorem cast_mono [ordered_ring α] : monotone (coe : ℤ → α) :=
begin
intros m n h,
rw ← sub_nonneg at h,
lift n - m to ℕ using h with k,
rw [← sub_nonneg, ← cast_sub, ← h_1, cast_coe_nat],
exact k.cast_nonneg
end
@[simp] theorem cast_nonneg [ordered_ring α] [nontrivial α] : ∀ {n : ℤ}, (0 : α) ≤ n ↔ 0 ≤ n
| (n : ℕ) := by simp
| -[1+ n] := have -(n:α) < 1, from lt_of_le_of_lt (by simp) zero_lt_one,
by simpa [(neg_succ_lt_zero n).not_le, ← sub_eq_add_neg, le_neg] using this.not_le
@[simp, norm_cast] theorem cast_le [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) ≤ n ↔ m ≤ n :=
by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg]
theorem cast_strict_mono [ordered_ring α] [nontrivial α] : strict_mono (coe : ℤ → α) :=
strict_mono_of_le_iff_le $ λ m n, cast_le.symm
@[simp, norm_cast] theorem cast_lt [ordered_ring α] [nontrivial α] {m n : ℤ} :
(m : α) < n ↔ m < n :=
cast_strict_mono.lt_iff_lt
@[simp] theorem cast_nonpos [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) ≤ 0 ↔ n ≤ 0 :=
by rw [← cast_zero, cast_le]
@[simp] theorem cast_pos [ordered_ring α] [nontrivial α] {n : ℤ} : (0 : α) < n ↔ 0 < n :=
by rw [← cast_zero, cast_lt]
@[simp] theorem cast_lt_zero [ordered_ring α] [nontrivial α] {n : ℤ} : (n : α) < 0 ↔ n < 0 :=
by rw [← cast_zero, cast_lt]
section linear_ordered_ring
variables [linear_ordered_ring α] {a b : ℤ} (n : ℤ)
@[simp, norm_cast] theorem cast_min : (↑(min a b) : α) = min a b :=
monotone.map_min cast_mono
@[simp, norm_cast] theorem cast_max : (↑(max a b) : α) = max a b :=
monotone.map_max cast_mono
@[simp, norm_cast] theorem cast_abs : ((|a| : ℤ) : α) = |a| :=
by simp [abs_eq_max_neg]
lemma cast_one_le_of_pos (h : 0 < a) : (1 : α) ≤ a :=
by exact_mod_cast int.add_one_le_of_lt h
lemma cast_le_neg_one_of_neg (h : a < 0) : (a : α) ≤ -1 :=
begin
rw [← int.cast_one, ← int.cast_neg, cast_le],
exact int.le_sub_one_of_lt h,
end
lemma nneg_mul_add_sq_of_abs_le_one {x : α} (hx : |x| ≤ 1) :
(0 : α) ≤ n * x + n * n :=
begin
have hnx : 0 < n → 0 ≤ x + n := λ hn, by
{ convert add_le_add (neg_le_of_abs_le hx) (cast_one_le_of_pos hn),
rw add_left_neg, },
have hnx' : n < 0 → x + n ≤ 0 := λ hn, by
{ convert add_le_add (le_of_abs_le hx) (cast_le_neg_one_of_neg hn),
rw add_right_neg, },
rw [← mul_add, mul_nonneg_iff],
rcases lt_trichotomy n 0 with h | rfl | h,
{ exact or.inr ⟨by exact_mod_cast h.le, hnx' h⟩, },
{ simp [le_total 0 x], },
{ exact or.inl ⟨by exact_mod_cast h.le, hnx h⟩, },
end
lemma cast_nat_abs : (n.nat_abs : α) = |n| :=
begin
cases n,
{ simp, },
{ simp only [int.nat_abs, int.cast_neg_succ_of_nat, abs_neg, ← nat.cast_succ, nat.abs_cast], },
end
end linear_ordered_ring
lemma coe_int_dvd [comm_ring α] (m n : ℤ) (h : m ∣ n) :
(m : α) ∣ (n : α) :=
ring_hom.map_dvd (int.cast_ring_hom α) h
end cast
end int
namespace prod
variables {α : Type*} {β : Type*} [add_group_with_one α] [add_group_with_one β]
instance : add_group_with_one (α × β) :=
{ int_cast := λ n, (n, n),
int_cast_of_nat := λ _, by simp; refl,
int_cast_neg_succ_of_nat := λ _, by simp; refl,
.. prod.add_monoid_with_one, .. prod.add_group }
@[simp] lemma fst_int_cast (n : ℤ) : (n : α × β).fst = n := rfl
@[simp] lemma snd_int_cast (n : ℤ) : (n : α × β).snd = n := rfl
end prod
open int
namespace add_monoid_hom
variables {A : Type*}
/-- Two additive monoid homomorphisms `f`, `g` from `ℤ` to an additive monoid are equal
if `f 1 = g 1`. -/
@[ext] theorem ext_int [add_monoid A] {f g : ℤ →+ A} (h1 : f 1 = g 1) : f = g :=
have f.comp (int.of_nat_hom : ℕ →+ ℤ) = g.comp (int.of_nat_hom : ℕ →+ ℤ) := ext_nat' _ _ h1,
have ∀ n : ℕ, f n = g n := ext_iff.1 this,
ext $ λ n, int.cases_on n this $ λ n, eq_on_neg (this $ n + 1)
variables [add_group_with_one A]
theorem eq_int_cast_hom (f : ℤ →+ A) (h1 : f 1 = 1) : f = int.cast_add_hom A :=
ext_int $ by simp [h1]
theorem eq_int_cast (f : ℤ →+ A) (h1 : f 1 = 1) : ∀ n : ℤ, f n = n :=
ext_iff.1 (f.eq_int_cast_hom h1)
end add_monoid_hom
@[simp] lemma int.cast_add_hom_int : int.cast_add_hom ℤ = add_monoid_hom.id ℤ :=
((add_monoid_hom.id ℤ).eq_int_cast_hom rfl).symm
namespace monoid_hom
variables {M : Type*} [monoid M]
open multiplicative
@[ext] theorem ext_mint {f g : multiplicative ℤ →* M} (h1 : f (of_add 1) = g (of_add 1)) : f = g :=
monoid_hom.ext $ add_monoid_hom.ext_iff.mp $
@add_monoid_hom.ext_int _ _ f.to_additive g.to_additive h1
/-- If two `monoid_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] theorem ext_int {f g : ℤ →* M}
(h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_hom = g.comp int.of_nat_hom.to_monoid_hom) :
f = g :=
begin
ext (x | x),
{ exact (monoid_hom.congr_fun h_nat x : _), },
{ rw [int.neg_succ_of_nat_eq, ← neg_one_mul, f.map_mul, g.map_mul],
congr' 1,
exact_mod_cast (monoid_hom.congr_fun h_nat (x + 1) : _), }
end
end monoid_hom
namespace monoid_with_zero_hom
variables {M : Type*} [monoid_with_zero M]
/-- If two `monoid_with_zero_hom`s agree on `-1` and the naturals then they are equal. -/
@[ext] lemma ext_int {f g : ℤ →*₀ M} (h_neg_one : f (-1) = g (-1))
(h_nat : f.comp int.of_nat_hom.to_monoid_with_zero_hom =
g.comp int.of_nat_hom.to_monoid_with_zero_hom) :
f = g :=
to_monoid_hom_injective $ monoid_hom.ext_int h_neg_one $ monoid_hom.ext (congr_fun h_nat : _)
/-- If two `monoid_with_zero_hom`s agree on `-1` and the _positive_ naturals then they are equal. -/
lemma ext_int' {φ₁ φ₂ : ℤ →*₀ M} (h_neg_one : φ₁ (-1) = φ₂ (-1))
(h_pos : ∀ n : ℕ, 0 < n → φ₁ n = φ₂ n) : φ₁ = φ₂ :=
ext_int h_neg_one $ ext_nat h_pos
end monoid_with_zero_hom
namespace ring_hom
variables {α : Type*} {β : Type*} [non_assoc_ring α] [non_assoc_ring β]
@[simp] lemma eq_int_cast (f : ℤ →+* α) (n : ℤ) : f n = n :=
f.to_add_monoid_hom.eq_int_cast f.map_one n
lemma eq_int_cast' (f : ℤ →+* α) : f = int.cast_ring_hom α :=
ring_hom.ext f.eq_int_cast
@[simp] lemma map_int_cast (f : α →+* β) (n : ℤ) : f n = n :=
(f.comp (int.cast_ring_hom α)).eq_int_cast n
lemma ext_int {R : Type*} [non_assoc_semiring R] (f g : ℤ →+* R) : f = g :=
coe_add_monoid_hom_injective $ add_monoid_hom.ext_int $ f.map_one.trans g.map_one.symm
instance int.subsingleton_ring_hom {R : Type*} [non_assoc_semiring R] : subsingleton (ℤ →+* R) :=
⟨ring_hom.ext_int⟩
end ring_hom
@[simp, norm_cast] theorem int.cast_id (n : ℤ) : ↑n = n :=
((ring_hom.id ℤ).eq_int_cast n).symm
@[simp] lemma int.cast_ring_hom_int : int.cast_ring_hom ℤ = ring_hom.id ℤ :=
(ring_hom.id ℤ).eq_int_cast'.symm
namespace pi
variables {α : Type*} {β : α → Type*} [∀ a, has_int_cast (β a)]
instance : has_int_cast (∀ a, β a) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
lemma int_apply (n : ℤ) (a : α) : (n : ∀ a, β a) a = n := rfl
@[simp] lemma coe_int (n : ℤ) : (n : ∀ a, β a) = λ _, n := rfl
end pi
lemma sum.elim_int_cast_int_cast {α β γ : Type*} [has_int_cast γ] (n : ℤ) :
sum.elim (n : α → γ) (n : β → γ) = n :=
@sum.elim_lam_const_lam_const α β γ n
namespace pi
variables {α : Type*} {β : α → Type*} [∀ a, add_group_with_one (β a)]
instance : add_group_with_one (∀ a, β a) :=
by refine_struct { .. }; tactic.pi_instance_derive_field
end pi
namespace mul_opposite
variables {α : Type*} [add_group_with_one α]
@[simp, norm_cast] lemma op_int_cast (z : ℤ) : op (z : α) = z := rfl
@[simp, norm_cast] lemma unop_int_cast (n : ℤ) : unop (n : αᵐᵒᵖ) = n := rfl
end mul_opposite
|
155b524c258d2102a48d83f8657f1871faf1862a | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /∧.lean | 87fc494b242cbff9879f739c206d91c5d08c7b63 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 482 | lean | import data.prod
namespace hide
open prod
constant and : Prop → Prop → Prop
constant Proof : Prop → Type
constant and_intro : Π (p q : Prop), (Proof p) -> (Proof q) -> (Proof (and p q))
constant and_break : Π (p q : Prop), (Proof (and p q)) -> (Proof p) × (Proof q)
constants a b : Prop
constant anb : Proof (and a b)
definition first_step := and_break a b anb
definition second_step := and_intro b a (pr2 first_step) (pr1 first_step)
check second_step
end hide
|
5bb26570773c00d4a8f0914dadae9a92e9e16784 | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /test/ring.lean | 25541abac7cdffe0750a1eb7e6347043a83c984c | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 542 | lean | import tactic.ring data.real.basic
example (x y : ℕ) : x + y = y + x := by ring
example (x y : ℕ) : x + y + y = 2 * y + x := by ring
example {α} [comm_ring α] (x y : α) : x + y + y - x = 2 * y := by ring
example (x y : ℚ) : x / 2 + x / 2 = x := by ring
example (x y : ℚ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example (x y : ℝ) : (x + y) ^ 3 = x ^ 3 + y ^ 3 + 3 * (x * y ^ 2 + x ^ 2 * y) := by ring
example {α} [comm_semiring α] (x : α) : (x + 1) ^ 6 = (1 + x) ^ 6 := by try_for 15000 {ring}
|
1c2d9b71f0d462e972404216aff0fef67ddc5eb9 | 618003631150032a5676f229d13a079ac875ff77 | /src/order/liminf_limsup.lean | 995b4a1325de6c75d3048693e1f37af58f69b04c | [
"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 | 19,851 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Johannes Hölzl
-/
import order.filter
/-!
# liminfs and limsups of functions and filters
Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with
respect to an arbitrary filter.
We define `f.Limsup` (`f.Liminf`) where `f` is a filter taking values in a conditionally complete
lattice. `f.Limsup` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for
`f.Liminf`). To work with the Limsup along a function `u` use `(f.map u).Limsup`.
Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter.
For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity
decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible
that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then
there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is
not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not
use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less
tractable definition.
In conditionally complete lattices, the definition is only useful for filters which are eventually
bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and
which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the
space either). We start with definitions of these concepts for arbitrary filters, before turning to
the definitions of Limsup and Liminf.
In complete lattices, however, it coincides with the `Inf Sup` definition.
-/
open filter set
variables {α : Type*} {β : Type*}
namespace filter
section relation
/-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e.
eventually, it is bounded by some uniform bound.
`r` will be usually instantiated with `≤` or `≥`. -/
def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b
/-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t.
the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/
def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_bounded r
variables {r : α → α → Prop} {f g : filter α}
/-- `f` is eventually bounded if and only if, there exists an admissible set on which it is
bounded. -/
lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) :=
iff.intro
(assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩)
(assume ⟨s, hs, b, hb⟩, ⟨b, mem_sets_of_superset hs hb⟩)
/-- A bounded function `u` is in particular eventually bounded. -/
lemma is_bounded_under_of {f : filter β} {u : β → α} :
(∃b, ∀x, r (u x) b) → f.is_bounded_under r u
| ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall _ hb⟩
lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α :=
by simp [is_bounded, exists_true_iff_nonempty]
lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) :=
by simp [is_bounded, eq_univ_iff_forall]
lemma is_bounded_principal (s : set α) : is_bounded r (principal s) ↔ (∃t, ∀x∈s, r x t) :=
by simp [is_bounded, subset_def]
lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) :
is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g)
| ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in
⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩
lemma is_bounded_of_le (h : f ≤ g) : is_bounded r g → is_bounded r f
| ⟨b, hb⟩ := ⟨b, h hb⟩
lemma is_bounded_under_of_is_bounded {q : β → β → Prop} {u : α → β}
(hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u
| ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩
/-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is
also called frequently bounded. Will be usually instantiated with `≤` or `≥`.
There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of
complete lattices. This will be relevant to deduce theorems on complete lattices from their
versions on conditionally complete lattices with additional assumptions. We have to be careful in
the edge case of the trivial filter containing the empty set: the other natural definition
`¬ ∀ a, ∀ᶠ n in f, a ≤ n`
would not work as well in this case.
-/
def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a
/-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not
tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated
with `≤` or `≥`. -/
def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (f.map u).is_cobounded r
/-- To check that a filter is frequently bounded, it suffices to have a witness
which bounds `f` at some point for every admissible set.
This is only an implication, as the other direction is wrong for the trivial filter.-/
lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r :=
⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩
/-- A filter which is eventually bounded is in particular frequently bounded (in the opposite
direction). At least if the filter is not trivial. -/
lemma is_cobounded_of_is_bounded [is_trans α r] (hf : f ≠ ⊥) :
f.is_bounded r → f.is_cobounded (flip r)
| ⟨a, ha⟩ := ⟨a, assume b hb,
have ∀ᶠ x in f, r x a ∧ r b x, from ha.and hb,
let ⟨x, rxa, rbx⟩ := nonempty_of_mem_sets hf this in
show r b a, from trans rbx rxa⟩
lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) :=
by simp [is_cobounded]
lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α :=
by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt}
lemma is_cobounded_principal (s : set α) :
(principal s).is_cobounded r↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) :=
by simp [is_cobounded, subset_def]
lemma is_cobounded_of_le (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r
| ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩
end relation
instance is_trans_le [preorder α] : is_trans α (≤) := ⟨assume a b c, le_trans⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
instance is_trans_ge [preorder α] : is_trans α (≥) := ⟨assume a b c h₁ h₂, le_trans h₂ h₁⟩
lemma is_cobounded_le_of_bot [order_bot α] {f : filter α} : f.is_cobounded (≤) :=
⟨⊥, assume a h, bot_le⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_cobounded_ge_of_top [order_top α] {f : filter α} : f.is_cobounded (≥) :=
⟨⊤, assume a h, le_top⟩
lemma is_bounded_le_of_top [order_top α] {f : filter α} : f.is_bounded (≤) :=
⟨⊤, eventually_of_forall _ $ λ _, le_top⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_ge_of_bot [order_bot α] {f : filter α} : f.is_bounded (≥) :=
⟨⊥, eventually_of_forall _ $ λ _, bot_le⟩
lemma is_bounded_under_sup [semilattice_sup α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ :=
⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv,
by filter_upwards [hu, hv] assume x, sup_le_sup⟩
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma is_bounded_under_inf [semilattice_inf α] {f : filter β} {u v : β → α} :
f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a)
| ⟨bu, (hu : ∀ᶠ x in f, u x ≥ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≥ bv)⟩ :=
⟨bu ⊓ bv, show ∀ᶠ x in f, u x ⊓ v x ≥ bu ⊓ bv,
by filter_upwards [hu, hv] assume x, inf_le_inf⟩
/-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements
in complete and conditionally complete lattices but let automation fill automatically the
boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements,
in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/
meta def is_bounded_default : tactic unit :=
tactic.applyc ``is_cobounded_le_of_bot <|>
tactic.applyc ``is_cobounded_ge_of_top <|>
tactic.applyc ``is_bounded_le_of_top <|>
tactic.applyc ``is_bounded_ge_of_bot
section conditionally_complete_lattice
variables [conditionally_complete_lattice α]
/-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`,
holds `x ≤ a`. -/
def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a }
/-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`,
holds `x ≥ a`. -/
def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n }
/-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that,
eventually for `f`, holds `u x ≤ a`. -/
def limsup (f : filter β) (u : β → α) : α := (f.map u).Limsup
/-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that,
eventually for `f`, holds `u x ≥ a`. -/
def liminf (f : filter β) (u : β → α) : α := (f.map u).Liminf
section
variables {f : filter β} {u : β → α}
theorem limsup_eq : f.limsup u = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl
theorem liminf_eq : f.liminf u = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl
end
theorem Limsup_le_of_le {f : filter α} {a}
(hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ a :=
cInf_le hf h
theorem le_Liminf_of_le {f : filter α} {a}
(hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ f.Liminf :=
le_cSup hf h
theorem le_Limsup_of_le {f : filter α} {a}
(hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) :
a ≤ f.Limsup :=
le_cInf hf h
theorem Liminf_le_of_le {f : filter α} {a}
(hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) :
f.Liminf ≤ a :=
cSup_le hf h
theorem Liminf_le_Limsup {f : filter α} (hf : f ≠ ⊥)
(h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) :
f.Liminf ≤ f.Limsup :=
Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁, show a₀ ≤ a₁, from
have ∀ᶠ b in f, a₀ ≤ b ∧ b ≤ a₁, from ha₀.and ha₁,
let ⟨b, hb₀, hb₁⟩ := nonempty_of_mem_sets hf this in
le_trans hb₀ hb₁
lemma Liminf_le_Liminf {f g : filter α}
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : f.Liminf ≤ g.Liminf :=
cSup_le_cSup hg hf h
lemma Limsup_le_Limsup {f g : filter α}
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default)
(h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : f.Limsup ≤ g.Limsup :=
cInf_le_cInf hf hg h
lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g)
(hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) :
f.Limsup ≤ g.Limsup :=
Limsup_le_Limsup hf hg (assume a ha, h ha)
lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f)
(hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) :
f.Liminf ≤ g.Liminf :=
Liminf_le_Liminf hf hg (assume a ha, h ha)
lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a ≤ v a)
(hu : f.is_cobounded_under (≤) u . is_bounded_default)
(hv : f.is_bounded_under (≤) v . is_bounded_default) :
f.limsup u ≤ f.limsup v :=
Limsup_le_Limsup hu hv $ assume b (hb : ∀ᶠ a in f, v a ≤ b), show ∀ᶠ a in f, u a ≤ b,
by filter_upwards [h, hb] assume a, le_trans
lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a ≤ v a)
(hu : f.is_bounded_under (≥) u . is_bounded_default)
(hv : f.is_cobounded_under (≥) v . is_bounded_default) :
f.liminf u ≤ f.liminf v :=
Liminf_le_Liminf hu hv $ assume b (hb : ∀ᶠ a in f, b ≤ u a), show ∀ᶠ a in f, b ≤ v a,
by filter_upwards [hb, h] assume a, le_trans
theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) :
(principal s).Limsup = Sup s :=
by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs
theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) :
(principal s).Liminf = Inf s :=
by simp [Liminf]; exact cSup_lower_bounds_eq_cInf h hs
lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : limsup f u = limsup f v :=
begin
rw limsup_eq,
congr,
ext b,
exact eventually_congr (h.mono $ λ x hx, by simp [hx])
end
lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β}
(h : ∀ᶠ a in f, u a = v a) : liminf f u = liminf f v :=
begin
rw liminf_eq,
congr,
ext b,
exact eventually_congr (h.mono $ λ x hx, by simp [hx])
end
lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} (hf : f ≠ ⊥)
(b : β) : limsup f (λ x, b) = b :=
begin
rw limsup_eq,
apply le_antisymm,
{ refine cInf_le ⟨b, λ a ha, _⟩ (by simp [le_refl]),
obtain ⟨n, hn⟩ : ∃ n, b ≤ a := eventually.exists ha hf,
exact hn },
{ refine le_cInf ⟨b, by simp [le_refl]⟩ (λ a ha, _),
obtain ⟨n, hn⟩ : ∃ n, b ≤ a := eventually.exists ha hf,
exact hn }
end
lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} (hf : f ≠ ⊥)
(b : β) : liminf f (λ x, b) = b :=
begin
rw liminf_eq,
apply le_antisymm,
{ refine cSup_le ⟨b, by simp [le_refl]⟩ (λ a ha, _),
obtain ⟨n, hn⟩ : ∃ n, a ≤ b := eventually.exists ha hf,
exact hn },
{ refine le_cSup ⟨b, λ a ha, _⟩ (by simp [le_refl]),
obtain ⟨n, hn⟩ : ∃ n, a ≤ b := eventually.exists ha hf,
exact hn }
end
end conditionally_complete_lattice
section complete_lattice
variables [complete_lattice α]
@[simp] theorem Limsup_bot : (⊥ : filter α).Limsup = ⊥ :=
bot_unique $ Inf_le $ by simp
@[simp] theorem Liminf_bot : (⊥ : filter α).Liminf = ⊤ :=
top_unique $ le_Sup $ by simp
@[simp] theorem Limsup_top : (⊤ : filter α).Limsup = ⊤ :=
top_unique $ le_Inf $
by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _)
@[simp] theorem Liminf_top : (⊤ : filter α).Liminf = ⊥ :=
bot_unique $ Sup_le $
by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _)
lemma liminf_le_limsup {f : filter β} (hf : f ≠ ⊥) {u : β → α} : liminf f u ≤ limsup f u :=
Liminf_le_Limsup (map_ne_bot hf) is_bounded_le_of_top is_bounded_ge_of_bot
theorem Limsup_eq_infi_Sup {f : filter α} : f.Limsup = ⨅ s ∈ f, Sup s :=
le_antisymm
(le_infi $ assume s, le_infi $ assume hs, Inf_le $ show ∀ᶠ n in f, n ≤ Sup s,
by filter_upwards [hs] assume a, le_Sup)
(le_Inf $ assume a (ha : ∀ᶠ n in f, n ≤ a),
infi_le_of_le _ $ infi_le_of_le ha $ Sup_le $ assume b, id)
/-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : f.limsup u = ⨅ s ∈ f, ⨆ a ∈ s, u a :=
calc f.limsup u = ⨅ s ∈ (f.map u), Sup s : Limsup_eq_infi_Sup
... = ⨅ s ∈ f, ⨆ a ∈ s, u a :
le_antisymm
(le_infi $ assume s, le_infi $ assume hs,
infi_le_of_le (u '' s) $ infi_le_of_le (image_mem_map hs) $ le_of_eq Sup_image)
(le_infi $ assume s, le_infi $ assume (hs : u ⁻¹' s ∈ f),
infi_le_of_le _ $ infi_le_of_le hs $ supr_le $ assume a, supr_le $ assume ha, le_Sup ha)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup at_top u = ⨅n:ℕ, ⨆i≥n, u i :=
calc
limsup at_top u = ⨅ s ∈ at_top, ⨆n∈s, u n : limsup_eq_infi_supr
... = ⨅ n, ⨆i≥n, u i :
le_antisymm
(le_infi $ assume n, infi_le_of_le {i | i ≥ n} $ infi_le_of_le
(mem_at_top _)
(supr_le_supr $ assume i, supr_le_supr_const (by simp)))
(le_infi $ assume s, le_infi $ assume hs,
let ⟨n, hn⟩ := mem_at_top_sets.1 hs in
infi_le_of_le n $ supr_le_supr $ assume i, supr_le_supr_const (hn i))
theorem Liminf_eq_supr_Inf {f : filter α} : f.Liminf = ⨆ s ∈ f, Inf s :=
le_antisymm
(Sup_le $ assume a (ha : ∀ᶠ n in f, a ≤ n),
le_supr_of_le _ $ le_supr_of_le ha $ le_Inf $ assume b, id)
(supr_le $ assume s, supr_le $ assume hs, le_Sup $ show ∀ᶠ n in f, Inf s ≤ n,
by filter_upwards [hs] assume a, Inf_le)
/-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter
of the supremum of the function over `s` -/
theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : f.liminf u = ⨆ s ∈ f, ⨅ a ∈ s, u a :=
calc f.liminf u = ⨆ s ∈ f.map u, Inf s : Liminf_eq_supr_Inf
... = ⨆ s ∈ f, ⨅a∈s, u a :
le_antisymm
(supr_le $ assume s, supr_le $ assume (hs : u ⁻¹' s ∈ f),
le_supr_of_le _ $ le_supr_of_le hs $ le_infi $ assume a, le_infi $ assume ha, Inf_le ha)
(supr_le $ assume s, supr_le $ assume hs,
le_supr_of_le (u '' s) $ le_supr_of_le (image_mem_map hs) $ ge_of_eq Inf_image)
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf at_top u = ⨆n:ℕ, ⨅i≥n, u i :=
calc
liminf at_top u = ⨆ s ∈ at_top, ⨅ n ∈ s, u n : liminf_eq_supr_infi
... = ⨆n:ℕ, ⨅i≥n, u i :
le_antisymm
(supr_le $ assume s, supr_le $ assume hs,
let ⟨n, hn⟩ := mem_at_top_sets.1 hs in
le_supr_of_le n $ infi_le_infi $ assume i, infi_le_infi_const (hn _) )
(supr_le $ assume n, le_supr_of_le {i | n ≤ i} $
le_supr_of_le
(mem_at_top _)
(infi_le_infi $ assume i, infi_le_infi_const (by simp)))
end complete_lattice
section conditionally_complete_linear_order
lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : b < liminf f u) (hu : f.is_bounded_under (≥) u . is_bounded_default) :
∀ᶠ a in f, b < u a :=
begin
obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c :=
exists_lt_of_lt_cSup hu h,
exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx)
end
lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β]
{u : α → β} {b : β} (h : limsup f u < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) :
∀ᶠ a in f, u a < b :=
begin
obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, u n ≤ c}), c < b :=
exists_lt_of_cInf_lt hu h,
exact hc.mono (λ x hx, lt_of_le_of_lt hx hbc)
end
end conditionally_complete_linear_order
end filter
|
0f25c9259110183e9cfb5e694f708dabc265bb50 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/lcnf4.lean | 49bee19ffab0a5c63b11756249cda71eab51793a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 1,521 | lean | import Lean
partial def foo (n : Nat) : Nat := Id.run do
if n == 10 then return 0
foo (n+1)
partial def bar (n : Nat) : Nat := Id.run do
if n == 10 then 0 else
bar (n+1)
#print foo._unsafe_rec
#eval Lean.Compiler.compile #[``foo]
def xyz : BaseIO UInt32 := do
let ref ← IO.mkRef 42
ref.set 10
ref.get
-- set_option trace.Compiler.simp true in
#eval Lean.Compiler.compile #[``xyz]
@[extern "f_imp"]
opaque f : Nat → Nat
@[extern "g_imp"]
opaque g : Nat → Nat → Nat → Nat
inductive Ty where
| c1 | c2 | c3 | c4 | c5
def bla (ty : Ty) :=
match ty with
| .c1 => true
| _ => true
#eval Lean.Compiler.compile #[``bla]
def boo (ty ty' : Ty) (a b : Nat) :=
let d := match ty with
| .c1 => f b + f a + f (a+1) + f (a*2) + f (a*3)
| _ => f (b+1) + f b + f a
let e := match ty' with
| .c2 => f a * f (b+1) + f (a*2) + f (a*3)
| _ => f b * f (b + 1) + f (a*2) + f (a*3)
g e d e + g d d d
-- set_option trace.Compiler.simp.step true in
-- set_option trace.Compiler.simp.inline true in
-- set_option trace.Compiler.simp.inline.stats true in
-- set_option trace.Compiler.simp true in
#eval Lean.Compiler.compile #[``boo]
def f' (x y : Nat) :=
let s := (x, y)
let y := s.2
y + s.2
-- set_option trace.Compiler.simp true in
#eval Lean.Compiler.compile #[``f']
#eval Lean.Compiler.compile #[``Lean.Meta.isExprDefEqAuxImpl]
set_option trace.Meta.debug true
set_option trace.Compiler true
#eval Lean.Compiler.compile #[``Lean.MetavarContext.MkBinding.collectForwardDeps]
|
26729005caf3f31f4d90aeea601877e7238c0b3e | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/ring_theory/polynomial/content.lean | d9e0d16cc5aa6bce228b289a46478a6ffb799187 | [
"Apache-2.0"
] | permissive | ilitzroth/mathlib | ea647e67f1fdfd19a0f7bdc5504e8acec6180011 | 5254ef14e3465f6504306132fe3ba9cec9ffff16 | refs/heads/master | 1,680,086,661,182 | 1,617,715,647,000 | 1,617,715,647,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,783 | lean | /-
Copyright (c) 2020 Aaron Anderson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson
-/
import data.finset.gcd
import data.polynomial
import data.polynomial.erase_lead
import data.polynomial.cancel_leads
/-!
# GCD structures on polynomials
Definitions and basic results about polynomials over GCD domains, particularly their contents
and primitive polynomials.
## Main Definitions
Let `p : polynomial R`.
- `p.content` is the `gcd` of the coefficients of `p`.
- `p.is_primitive` indicates that `p.content = 1`.
## Main Results
- `polynomial.content_mul`:
If `p q : polynomial R`, then `(p * q).content = p.content * q.content`.
- `polynomial.gcd_monoid`:
The polynomial ring of a GCD domain is itself a GCD domain.
-/
variables {R : Type*} [integral_domain R]
namespace polynomial
section gcd_monoid
variable [gcd_monoid R]
/-- `p.content` is the `gcd` of the coefficients of `p`. -/
def content (p : polynomial R) : R := (p.support).gcd p.coeff
lemma content_dvd_coeff {p : polynomial R} (n : ℕ) : p.content ∣ p.coeff n :=
begin
by_cases h : n ∈ p.support,
{ apply finset.gcd_dvd h },
rw [mem_support_iff, not_not] at h,
rw h,
apply dvd_zero,
end
@[simp] lemma content_C {r : R} : (C r).content = normalize r :=
begin
rw content,
by_cases h0 : r = 0,
{ simp [h0] },
have h : (C r).support = {0} := finsupp.support_single_ne_zero h0,
simp [h],
end
@[simp] lemma content_zero : content (0 : polynomial R) = 0 :=
by rw [← C_0, content_C, normalize_zero]
@[simp] lemma content_one : content (1 : polynomial R) = 1 :=
by rw [← C_1, content_C, normalize_one]
lemma content_X_mul {p : polynomial R} : content (X * p) = content p :=
begin
rw [content, content, finset.gcd_def, finset.gcd_def],
refine congr rfl _,
have h : (X * p).support = p.support.map ⟨nat.succ, nat.succ_injective⟩,
{ ext a,
simp only [exists_prop, finset.mem_map, function.embedding.coe_fn_mk, ne.def,
mem_support_iff],
cases a,
{ simp [coeff_X_mul_zero, nat.succ_ne_zero] },
rw [mul_comm, coeff_mul_X],
split,
{ intro h,
use a,
simp [h] },
{ rintros ⟨b, ⟨h1, h2⟩⟩,
rw ← nat.succ_injective h2,
apply h1 } },
rw h,
simp only [finset.map_val, function.comp_app, function.embedding.coe_fn_mk, multiset.map_map],
refine congr (congr rfl _) rfl,
ext a,
rw mul_comm,
simp [coeff_mul_X],
end
@[simp] lemma content_X_pow {k : ℕ} : content ((X : polynomial R) ^ k) = 1 :=
begin
induction k with k hi,
{ simp },
rw [pow_succ, content_X_mul, hi]
end
@[simp] lemma content_X : content (X : polynomial R) = 1 :=
by { rw [← mul_one X, content_X_mul, content_one] }
lemma content_C_mul (r : R) (p : polynomial R) : (C r * p).content = normalize r * p.content :=
begin
by_cases h0 : r = 0, { simp [h0] },
rw content, rw content, rw ← finset.gcd_mul_left,
refine congr (congr rfl _) _; ext; simp [h0, mem_support_iff]
end
@[simp] lemma content_monomial {r : R} {k : ℕ} : content (monomial k r) = normalize r :=
by { rw [single_eq_C_mul_X, content_C_mul, content_X_pow, mul_one] }
lemma content_eq_zero_iff {p : polynomial R} : content p = 0 ↔ p = 0 :=
begin
rw [content, finset.gcd_eq_zero_iff],
split; intro h,
{ ext n,
by_cases h0 : n ∈ p.support,
{ rw [h n h0, coeff_zero], },
{ rw mem_support_iff at h0,
push_neg at h0,
simp [h0] } },
{ intros x h0,
simp [h] }
end
@[simp] lemma normalize_content {p : polynomial R} : normalize p.content = p.content :=
finset.normalize_gcd
lemma content_eq_gcd_range_of_lt (p : polynomial R) (n : ℕ) (h : p.nat_degree < n) :
p.content = (finset.range n).gcd p.coeff :=
begin
apply dvd_antisymm_of_normalize_eq normalize_content finset.normalize_gcd,
{ rw finset.dvd_gcd_iff,
intros i hi,
apply content_dvd_coeff _ },
{ apply finset.gcd_mono,
intro i,
simp only [nat.lt_succ_iff, mem_support_iff, ne.def, finset.mem_range],
contrapose!,
intro h1,
apply coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le h h1), }
end
lemma content_eq_gcd_range_succ (p : polynomial R) :
p.content = (finset.range p.nat_degree.succ).gcd p.coeff :=
content_eq_gcd_range_of_lt _ _ (nat.lt_succ_self _)
lemma content_eq_gcd_leading_coeff_content_erase_lead (p : polynomial R) :
p.content = gcd_monoid.gcd p.leading_coeff (erase_lead p).content :=
begin
by_cases h : p = 0,
{ simp [h] },
rw [← leading_coeff_eq_zero, leading_coeff, ← ne.def, ← mem_support_iff] at h,
rw [content, ← finset.insert_erase h, finset.gcd_insert, leading_coeff, content,
erase_lead_support],
refine congr rfl (finset.gcd_congr rfl (λ i hi, _)),
rw finset.mem_erase at hi,
rw [erase_lead_coeff, if_neg hi.1],
end
lemma dvd_content_iff_C_dvd {p : polynomial R} {r : R} : r ∣ p.content ↔ C r ∣ p :=
begin
rw C_dvd_iff_dvd_coeff,
split,
{ intros h i,
apply dvd_trans h (content_dvd_coeff _) },
{ intro h,
rw [content, finset.dvd_gcd_iff],
intros i hi,
apply h i }
end
lemma C_content_dvd (p : polynomial R) : C p.content ∣ p :=
dvd_content_iff_C_dvd.1 (dvd_refl _)
/-- A polynomial over a GCD domain is primitive when the `gcd` of its coefficients is 1 -/
def is_primitive (p : polynomial R) : Prop := p.content = 1
@[simp]
lemma is_primitive_one : is_primitive (1 : polynomial R) :=
by rw [is_primitive, ← C_1, content_C, normalize_one]
lemma monic.is_primitive {p : polynomial R} (hp : p.monic) : p.is_primitive :=
by rw [is_primitive, content_eq_gcd_leading_coeff_content_erase_lead,
hp.leading_coeff, gcd_one_left]
lemma is_primitive.ne_zero {p : polynomial R} (hp : p.is_primitive) : p ≠ 0 :=
begin
rintro rfl,
rw [is_primitive, content_zero] at hp,
apply zero_ne_one hp,
end
lemma is_primitive.content_eq_one {p : polynomial R} (hp : p.is_primitive) : p.content = 1 := hp
lemma is_primitive_iff_is_unit_of_C_dvd {p : polynomial R} :
p.is_primitive ↔ ∀ (r : R), C r ∣ p → is_unit r :=
begin
rw [is_primitive],
split,
{ intros h r hdvd,
rw [← dvd_content_iff_C_dvd, h] at hdvd,
apply is_unit_of_dvd_one _ hdvd },
{ intro h,
rw [← normalize_content, normalize_eq_one],
apply h _ (C_content_dvd _) }
end
open_locale classical
noncomputable theory
section prim_part
/-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by
`p.content`. If `p = 0`, then `p.prim_part = 1`. -/
def prim_part (p : polynomial R) : polynomial R :=
if p = 0 then 1 else classical.some (C_content_dvd p)
lemma eq_C_content_mul_prim_part (p : polynomial R) : p = C p.content * p.prim_part :=
begin
by_cases h : p = 0, { simp [h] },
rw [prim_part, if_neg h, ← classical.some_spec (C_content_dvd p)],
end
@[simp]
lemma prim_part_zero : prim_part (0 : polynomial R) = 1 := if_pos rfl
lemma is_primitive_prim_part (p : polynomial R) : p.prim_part.is_primitive :=
begin
by_cases h : p = 0, { simp [h] },
rw ← content_eq_zero_iff at h,
apply mul_left_cancel' h,
conv_rhs { rw [p.eq_C_content_mul_prim_part, mul_one, content_C_mul, normalize_content] }
end
lemma content_prim_part (p : polynomial R) : p.prim_part.content = 1 :=
p.is_primitive_prim_part
lemma prim_part_ne_zero (p : polynomial R) : p.prim_part ≠ 0 := p.is_primitive_prim_part.ne_zero
lemma nat_degree_prim_part (p : polynomial R) : p.prim_part.nat_degree = p.nat_degree :=
begin
by_cases h : C p.content = 0,
{ rw [C_eq_zero, content_eq_zero_iff] at h, simp [h] },
conv_rhs { rw [p.eq_C_content_mul_prim_part,
nat_degree_mul h p.prim_part_ne_zero, nat_degree_C, zero_add] },
end
@[simp]
lemma is_primitive.prim_part_eq {p : polynomial R} (hp : p.is_primitive) : p.prim_part = p :=
by rw [← one_mul p.prim_part, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_prim_part]
lemma is_unit_prim_part_C (r : R) : is_unit (C r).prim_part :=
begin
by_cases h0 : r = 0,
{ simp [h0] },
unfold is_unit,
refine ⟨⟨C ↑(norm_unit r)⁻¹, C ↑(norm_unit r),
by rw [← ring_hom.map_mul, units.inv_mul, C_1],
by rw [← ring_hom.map_mul, units.mul_inv, C_1]⟩, _⟩,
rw [← normalize_eq_zero, ← C_eq_zero] at h0,
apply mul_left_cancel' h0,
conv_rhs { rw [← content_C, ← (C r).eq_C_content_mul_prim_part], },
simp only [units.coe_mk, normalize_apply, ring_hom.map_mul],
rw [mul_assoc, ← ring_hom.map_mul, units.mul_inv, C_1, mul_one],
end
lemma prim_part_dvd (p : polynomial R) : p.prim_part ∣ p :=
dvd.intro_left (C p.content) p.eq_C_content_mul_prim_part.symm
end prim_part
lemma gcd_content_eq_of_dvd_sub {a : R} {p q : polynomial R} (h : C a ∣ p - q) :
gcd_monoid.gcd a p.content = gcd_monoid.gcd a q.content :=
begin
rw content_eq_gcd_range_of_lt p (max p.nat_degree q.nat_degree).succ
(lt_of_le_of_lt (le_max_left _ _) (nat.lt_succ_self _)),
rw content_eq_gcd_range_of_lt q (max p.nat_degree q.nat_degree).succ
(lt_of_le_of_lt (le_max_right _ _) (nat.lt_succ_self _)),
apply finset.gcd_eq_of_dvd_sub,
intros x hx,
cases h with w hw,
use w.coeff x,
rw [← coeff_sub, hw, coeff_C_mul]
end
lemma content_mul_aux {p q : polynomial R} :
gcd_monoid.gcd (p * q).erase_lead.content p.leading_coeff =
gcd_monoid.gcd (p.erase_lead * q).content p.leading_coeff :=
begin
rw [gcd_comm (content _) _, gcd_comm (content _) _],
apply gcd_content_eq_of_dvd_sub,
rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add,
sub_sub_cancel, leading_coeff_mul, ring_hom.map_mul, mul_assoc, mul_assoc],
apply dvd_sub (dvd.intro _ rfl) (dvd.intro _ rfl),
end
@[simp]
theorem content_mul {p q : polynomial R} : (p * q).content = p.content * q.content :=
begin
classical,
suffices h : ∀ (n : ℕ) (p q : polynomial R), ((p * q).degree < n) →
(p * q).content = p.content * q.content,
{ apply h,
apply (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_succ_self _))) },
intro n,
induction n with n ih,
{ intros p q hpq,
rw [with_bot.coe_zero, nat.with_bot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq,
rcases hpq with rfl | rfl; simp },
intros p q hpq,
by_cases p0 : p = 0, { simp [p0] },
by_cases q0 : q = 0, { simp [q0] },
rw [degree_eq_nat_degree (mul_ne_zero p0 q0), with_bot.coe_lt_coe, nat.lt_succ_iff_lt_or_eq,
← with_bot.coe_lt_coe, ← degree_eq_nat_degree (mul_ne_zero p0 q0), nat_degree_mul p0 q0] at hpq,
rcases hpq with hlt | heq, { apply ih _ _ hlt },
rw [← p.nat_degree_prim_part, ← q.nat_degree_prim_part, ← with_bot.coe_eq_coe, with_bot.coe_add,
← degree_eq_nat_degree p.prim_part_ne_zero, ← degree_eq_nat_degree q.prim_part_ne_zero] at heq,
rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part],
suffices h : (q.prim_part * p.prim_part).content = 1,
{ rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.prim_part, mul_assoc, content_C_mul,
content_C_mul, h, mul_one, content_prim_part, content_prim_part, mul_one, mul_one] },
rw [← normalize_content, normalize_eq_one, is_unit_iff_dvd_one,
content_eq_gcd_leading_coeff_content_erase_lead, leading_coeff_mul, gcd_comm],
apply dvd_trans (gcd_mul_dvd_mul_gcd _ _ _),
rw [content_mul_aux, ih, content_prim_part, mul_one, gcd_comm,
← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part, one_mul,
mul_comm q.prim_part, content_mul_aux, ih, content_prim_part, mul_one, gcd_comm,
← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part],
{ rw [← heq, degree_mul, with_bot.add_lt_add_iff_right],
{ apply degree_erase_lt p.prim_part_ne_zero },
{ rw [bot_lt_iff_ne_bot, ne.def, degree_eq_bot],
apply q.prim_part_ne_zero } },
{ rw [mul_comm, ← heq, degree_mul, with_bot.add_lt_add_iff_left],
{ apply degree_erase_lt q.prim_part_ne_zero },
{ rw [bot_lt_iff_ne_bot, ne.def, degree_eq_bot],
apply p.prim_part_ne_zero } }
end
theorem is_primitive.mul {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) :
(p * q).is_primitive :=
by rw [is_primitive, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one]
@[simp]
theorem prim_part_mul {p q : polynomial R} (h0 : p * q ≠ 0) :
(p * q).prim_part = p.prim_part * q.prim_part :=
begin
rw [ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0,
apply mul_left_cancel' h0,
conv_lhs { rw [← (p * q).eq_C_content_mul_prim_part,
p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part] },
rw [content_mul, ring_hom.map_mul],
ring,
end
lemma is_primitive.is_primitive_of_dvd {p q : polynomial R} (hp : p.is_primitive) (hdvd : q ∣ p) :
q.is_primitive :=
begin
rcases hdvd with ⟨r, rfl⟩,
rw [is_primitive, ← normalize_content, normalize_eq_one, is_unit_iff_dvd_one],
apply dvd.intro r.content,
rwa [is_primitive, content_mul] at hp,
end
lemma is_primitive.dvd_prim_part_iff_dvd {p q : polynomial R}
(hp : p.is_primitive) (hq : q ≠ 0) :
p ∣ q.prim_part ↔ p ∣ q :=
begin
refine ⟨λ h, dvd.trans h (dvd.intro_left _ q.eq_C_content_mul_prim_part.symm), λ h, _⟩,
rcases h with ⟨r, rfl⟩,
apply dvd.intro _,
rw [prim_part_mul hq, hp.prim_part_eq],
end
theorem exists_primitive_lcm_of_is_primitive {p q : polynomial R}
(hp : p.is_primitive) (hq : q.is_primitive) :
∃ r : polynomial R, r.is_primitive ∧ (∀ s : polynomial R, p ∣ s ∧ q ∣ s ↔ r ∣ s) :=
begin
classical,
have h : ∃ (n : ℕ) (r : polynomial R), r.nat_degree = n ∧ r.is_primitive ∧ p ∣ r ∧ q ∣ r :=
⟨(p * q).nat_degree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩,
rcases nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩,
refine ⟨r, rprim, λ s, ⟨_, λ rs, ⟨dvd.trans pr rs, dvd.trans qr rs⟩⟩⟩,
suffices hs : ∀ (n : ℕ) (s : polynomial R), s.nat_degree = n → (p ∣ s ∧ q ∣ s → r ∣ s),
{ apply hs s.nat_degree s rfl },
clear s,
by_contra con,
push_neg at con,
rcases nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩,
have s0 : s ≠ 0,
{ contrapose! rs, simp [rs] },
have hs := nat.find_min' h ⟨_, s.nat_degree_prim_part, s.is_primitive_prim_part,
(hp.dvd_prim_part_iff_dvd s0).2 ps, (hq.dvd_prim_part_iff_dvd s0).2 qs⟩,
rw ← rdeg at hs,
by_cases sC : s.nat_degree ≤ 0,
{ rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), is_primitive,
content_C, normalize_eq_one] at rprim,
rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs,
apply rs rprim.dvd },
have hcancel := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree hs (lt_of_not_ge sC),
rw sdeg at hcancel,
apply nat.find_min con hcancel,
refine ⟨_, rfl, ⟨dvd_cancel_leads_of_dvd_of_dvd pr ps, dvd_cancel_leads_of_dvd_of_dvd qr qs⟩,
λ rcs, rs _⟩,
rw ← rprim.dvd_prim_part_iff_dvd s0,
rw [cancel_leads, nat.sub_eq_zero_of_le hs, pow_zero, mul_one] at rcs,
have h := dvd_add rcs (dvd.intro_left _ rfl),
have hC0 := rprim.ne_zero,
rw [ne.def, ← leading_coeff_eq_zero, ← C_eq_zero] at hC0,
rw [sub_add_cancel, ← rprim.dvd_prim_part_iff_dvd (mul_ne_zero hC0 s0)] at h,
rcases is_unit_prim_part_C r.leading_coeff with ⟨u, hu⟩,
apply dvd.trans h (dvd_of_associated (associated.symm ⟨u, _⟩)),
rw [prim_part_mul (mul_ne_zero hC0 s0), hu, mul_comm],
end
lemma dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part
{p q : polynomial R} (hq : q ≠ 0) :
p ∣ q ↔ p.content ∣ q.content ∧ p.prim_part ∣ q.prim_part :=
begin
split; intro h,
{ rcases h with ⟨r, rfl⟩,
rw [content_mul, p.is_primitive_prim_part.dvd_prim_part_iff_dvd hq],
exact ⟨dvd.intro _ rfl, dvd.trans p.prim_part_dvd (dvd.intro _ rfl)⟩ },
{ rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part],
exact mul_dvd_mul (ring_hom.map_dvd C h.1) h.2 }
end
@[priority 100]
instance gcd_monoid : gcd_monoid (polynomial R) :=
gcd_monoid_of_exists_lcm $ λ p q, begin
rcases exists_primitive_lcm_of_is_primitive p.is_primitive_prim_part q.is_primitive_prim_part
with ⟨r, rprim, hr⟩,
refine ⟨C (lcm p.content q.content) * r, λ s, _⟩,
by_cases hs : s = 0,
{ simp [hs] },
by_cases hpq : C (lcm p.content q.content) = 0,
{ rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq,
rcases hpq with hpq | hpq; simp [hpq, hs] },
iterate 3 { rw dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part hs },
rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff,
prim_part_mul (mul_ne_zero hpq rprim.ne_zero), rprim.prim_part_eq,
is_unit.mul_left_dvd _ _ _ (is_unit_prim_part_C (lcm p.content q.content)), ← hr s.prim_part],
tauto,
end
end gcd_monoid
end polynomial
|
a66e869cd5c422679e1b5eb17287072eaea66750 | 076f5040b63237c6dd928c6401329ed5adcb0e44 | /answers/hw5_higher_order_functions.lean | 2dfccb6047d39ad470ca27192ddc201d26c1954d | [] | no_license | kevinsullivan/uva-cs-dm-f19 | 0f123689cf6cb078f263950b18382a7086bf30be | 09a950752884bd7ade4be33e9e89a2c4b1927167 | refs/heads/master | 1,594,771,841,541 | 1,575,853,850,000 | 1,575,853,850,000 | 205,433,890 | 4 | 9 | null | 1,571,592,121,000 | 1,567,188,539,000 | Lean | UTF-8 | Lean | false | false | 8,643 | lean | open list
/-
#1. You are to implement a function
that takes a "predicate" function and a
list and that returns a new list: namely
a list that contains all and only those
elements of the first list for which the
given predicate function returns true.
We start by giving you two predicate
functions. Each takes an argument, n,
of type ℕ. The first returns true if
and only if n < 5. The second returns
true if and only if n is even.
-/
/-
Here's a "predicate" function that
takes a natural number as an argument
and returns true if the number is less
than 5 otherwise it returns false.
-/
def lt_5 (n : ℕ) : bool :=
n < 5
-- example cases
#eval lt_5 2
#eval lt_5 6
/-
Here's another predicate function, one
that returns true if a given nat is even,
and false otherwise. Note that we have
defined this function recursively. Zero
is even, one is not, and (2 + n') is if
and only if n' is.
You can think of a predicate function
as a function that answers the question,
does some value (here a nat) have some
property? The properties in these two
cases are (1) the property of being less
than 5, and (2) the property of being
even.
-/
def evenb : ℕ → bool
| 0 := tt
| 1 := ff
| (n' + 2) := evenb n'
#eval evenb 0
#eval evenb 3
#eval evenb 4
#eval evenb 5
/-
We call the function you are going to
implement a "filter" function, because
it takes a list and returns a "filtered"
version of the list. Call you function
"mfilter".
If you filter an empty list you always
get an empty list as a result. If you
filter a non-empty list, l = (cons h t),
the returned list has h at its head if
and only if the predicate function applied
to h returns true, otherwise the returned
value is just the filtered version of t.
A. [15 points]
TA: Original had typo (actually due an
an unforeseen name conflict). Have the
students change all appearances of the
name, mfilter, to myfilter.
Your task is to complete an incomplete
version of the definition of the myfilter
function. We use a Lean construct new to
you: the if ... then ... else. It works
as you would expect from your work with
other programming languages. Replace the
underscores to complete the definition.
-/
def myfilter : (ℕ → bool) → list ℕ → list ℕ
| p [] := []
| p (cons h t) :=
if p h
then (cons h (myfilter p t))
else myfilter p t
/-
B. [10 points]
Here's the definition of a simple list.
-/
def a_list := [0,1,2,3,4,5,6,7,8,9]
/-
Replace the underscores in the first two
eval commands below as follows. Replace
the first one with an expression in which
myfilter is used to compute a new list that
contains the numbers in a_list that are
less than 5. Replace the second one with
an expression in which mfilter is used to
compute a list containing even elements of
a_list. You may use the predicate functions
we defined above.
Replace the third underscore with a similar
expression but where you use a λ expression
to specify a predicate function that takes
a nat, n, and returns tt if n is equal to
three and false otherwise. Hint: n=3 is
an expression that will return the desired
bool.
-/
#eval myfilter lt_5 a_list
#eval myfilter evenb a_list
#eval myfilter (λ (n : ℕ), n = 3) a_list
#eval a_list
/-
#2.
Here's a function that takes a function, f,
from ℕ to ℕ, and a value, n, of type ℕ, and
that returns the value that is obtained by
simply applying f to n.
-/
def f_apply : (ℕ → ℕ) → ℕ → ℕ
| f n := (f n)
-- examples of its use
#eval f_apply nat.succ 3
#eval f_apply (λ n : ℕ, n * n) 3
/-
A. [10 points]
Write a function, f_apply_2, that takes a
function, f, from ℕ to ℕ, and a value, n,
of type ℕ, and that returns (read this
carefully) the value obtained by applying
f twice to n: the result of applying f to
the result of applying f to n. For example,
if f is the function that squares its nat
argument, then (f_apply_2 f 3) returns 81,
as f applied to 3 is 9 and f applied to 9
is 81.
-/
-- Your answer here
/-
TA: Original had typo: ff_apply instead of
f_apply_2. Have students change ff_apply to
f_apply_2.
-/
def f_apply_2 : (ℕ → ℕ) → ℕ → ℕ
| f n := f (f n)
/-
B. [10 points]
Write a function f_apply_k that takes (1)
a function, f, of type ℕ to ℕ, (2) a value,
n, of type ℕ, and (3) a value, k of type ℕ,
and that returns the result of applying f
to n k times.
Note that f_apply applies f to n once and
ff_apply applies f to n twice. Your job is
to write a function that is general in the
sense that you specify by a parameter, k,
how many times to apply f.
Hint 1: Use recursion. Note: The result of
applying any function, f, to n, zero times
is just n.
-/
def f_apply_k : (ℕ → ℕ) → ℕ → ℕ → ℕ
| f n 0 := n
| f n (nat.succ k') := f (f_apply_k f n k')
-- Answer here
/-
Use #eval to evaluate an expression in
which the squaring function, expressed
as a λ expression, is applied to 3 two
times. You should be able to confirm that
you get the same answer given by using
the ff_apply function in the example above.
-/
-- Answer here
#eval f_apply_k (λ n, n^2) 3 2
/-
C. [Extra Credit]
Write a function f_apply_k_fun that takes (1)
a function, f, of type ℕ to ℕ, (2) a value,
k of type ℕ, and that returns a function that,
when applied to a natural number, n, returns
the result of applying f to n k times.
-/
def f_apply_k_fun : (ℕ → ℕ) → ℕ → (ℕ → ℕ)
| f 0 := λ n, n
| f (nat.succ k') := λ n, f (f_apply_k f n k')
def sq_twice := f_apply_k_fun (λ n, n^2) 2
#eval sq_twice 3 -- yay!
/-
#3: [15 points]
Write a function, mcompose, that
takes two functions, g and f (in that
order), each of type ℕ → ℕ, and that
returns *a function* that, when applied
to an argument, n, of type ℕ, returns
the result of applying g to the result
of applying f to n.
-/
-- Answer here
def mcompose : (ℕ → ℕ) → (ℕ → ℕ) → (ℕ → ℕ)
| g f := λ n, g (f n)
-- test
#eval (mcompose nat.succ (λ n, n^2)) 4 -- 4^2+1 = 17
/-
#4. Higher-Order Functions
4A. [10 points] Provide an implementatation of
a function, map_pred that takes as its arguments
(1) a predicate function of type ℕ → bool, (2) a
list of natural numbers (of type "list nat"),
and that returns a list in which each ℕ value,
n,in the argument list is replaced by true (tt)
if the predicate returns true for a, otherwise
false (ff).
For example, if the predicate function returns
true if and only if its argument is zero, then
applying map to this function and to the list
[0,1,2,0,1,0] must return [tt,ff,ff,tt,ff,tt].
Test your code by using #eval or #reduce to evaluate
an expression in which map_pred is applied to
such an "is_zero" predicate function and to the
list 0,1,2,0,1,0]. Express the predicate function
as a lambda abstraction within the #eval command.
NOTE: You will have to use list.nil and list.cons
to refer to the nil and cons constructors of the
library-provided list data type, as you already
have definitions for list and cons in the current
namespace.
-/
-- Answer here
def map_pred : (ℕ → bool) → list nat → list bool
| p [] := []
| p (cons h t) := cons (p h) (map_pred p t)
/-
4B. [10 points] Implement a function, reduce_or,
that takes as its argument a list of Boolean values
and that reduces the list to a single Boolean value:
tt if there is at least one true value in the list,
otherwise ff. Note: the Lean libraries provide the
function "bor" to compute "b1 or b2", where b1 and
b2 are Booleans. We recommend that you include
tests of your solution.
-/
-- example
#reduce bor tt tt
-- Answer here
def reduce_or : list bool → bool
| [] := ff
| (cons h t) := bor h (reduce_or t)
/-
4C. [10points] Implement a function, reduce_and,
that takes as its argument a list of Boolean values
and that reduces the list to a single Boolean value:
tt if every value in the list is true, otherwise ff.
-/
-- Note: band implements the Boolean "and" function
#reduce band tt tt
-- Answer here
def reduce_and : list bool → bool
| [] := tt
| (cons h t) := band h (reduce_and t)
/-
4D. [10 points] Define a function, all_zero, that
takes a list of nat values and returns true if and
only if they are all zero. Express your answer using
map and reduce functions that you have previously
defined above. Again we recommend that you test your
solution.
-/
-- Answer here (replace the _'s as needed)
def all_zero : list nat → bool
| [] := tt
| (cons h t) := band (h=0) (all_zero t)
/-
Some tests
-/
#reduce all_zero []
#reduce all_zero [0,0,0,0]
#reduce all_zero [1,0,0,0]
#reduce all_zero [0,1,0,0]
#reduce all_zero [1,0,0,1]
|
f600b46d2d29da14d7b1f99462495d7cc09cce20 | 9ee042bf34eebe0464f0f80c0db14ceb048dab10 | /stage0/src/Lean/Elab/PreDefinition/WF/PackDomain.lean | 234df1e8323768704dc43bd786d45997dab88281 | [
"Apache-2.0"
] | permissive | dexmagic/lean4 | 7507e7b07dc9f49db45df5ebd011886367dc2a6c | 48764b60d5bac337eaff4bf8a3d63a216e1d9e03 | refs/heads/master | 1,692,156,265,016 | 1,633,276,980,000 | 1,633,339,480,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,976 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.PreDefinition.Basic
namespace Lean.Elab.WF
open Meta
/--
Given a (dependent) tuple `t` (using `PSigma`) of the given arity.
Return an array containing its "elements".
Example: `mkTupleElems a 4` returns `#[a.1, a.2.1, a.2.2.1, a.2.2.2]`.
-/
private def mkTupleElems (t : Expr) (arity : Nat) : Array Expr := do
let mut result := #[]
let mut t := t
for i in [:arity - 1] do
result := result.push (mkProj ``PSigma 0 t)
t := mkProj ``PSigma 1 t
result.push t
/-- Create a unary application by packing the given arguments using `PSigma.mk` -/
partial def mkUnaryArg (type : Expr) (args : Array Expr) : MetaM Expr := do
go 0 type
where
go (i : Nat) (type : Expr) : MetaM Expr := do
if i < args.size - 1 then
let arg := args[i]
assert! type.isAppOfArity ``PSigma 2
let us := type.getAppFn.constLevels!
let α := type.appFn!.appArg!
let β := type.appArg!
assert! β.isLambda
let type := β.bindingBody!.instantiate1 arg
let rest ← go (i+1) type
return mkApp4 (mkConst ``PSigma.mk us) α β arg rest
else
return args[i]
private partial def mkPSigmaCasesOn (y : Expr) (codomain : Expr) (xs : Array Expr) (value : Expr) : MetaM Expr := do
let mvar ← mkFreshExprSyntheticOpaqueMVar codomain
let rec go (mvarId : MVarId) (y : FVarId) (ys : Array Expr) : MetaM Unit := do
if ys.size < xs.size - 1 then
let #[s] ← cases mvarId y | unreachable!
go s.mvarId s.fields[1].fvarId! (ys.push s.fields[0])
else
let ys := ys.push (mkFVar y)
assignExprMVar mvarId (value.replaceFVars xs ys)
go mvar.mvarId! y.fvarId! #[]
instantiateMVars mvar
/--
Convert the given pre-definitions into unary functions.
We "pack" the arguments using `PSigma`.
-/
def packDomain (preDefs : Array PreDefinition) : MetaM (Array PreDefinition) := do
let mut preDefsNew := #[]
let mut arities := #[]
let mut modified := false
for preDef in preDefs do
let (preDefNew, arity, modifiedCurr) ← lambdaTelescope preDef.value fun xs body => do
if xs.size > 1 then
let bodyType ← instantiateForall preDef.type xs
let mut d ← inferType xs.back
for x in xs.pop.reverse do
d ← mkAppOptM ``PSigma #[some (← inferType x), some (← mkLambdaFVars #[x] d)]
withLocalDeclD (← mkFreshUserName `_x) d fun tuple => do
let elems := mkTupleElems tuple xs.size
let codomain := bodyType.replaceFVars xs elems
let preDefNew:= { preDef with
declName := preDef.declName ++ `_unary
type := (← mkForallFVars #[tuple] codomain)
}
addAsAxiom preDefNew
return (preDefNew, xs.size, true)
else
return (preDef, 1, false)
modified := modified || modifiedCurr
arities := arities.push arity
preDefsNew := preDefsNew.push preDefNew
if !modified then
return preDefs
/- Return `some i` if `e` is a `preDefs[i]` application -/
let isAppOfPreDef? (e : Expr) : OptionM Nat := do
let f := e.getAppFn
guard f.isConst
preDefs.findIdx? (·.declName == f.constName!)
/- Return `some i` if `e` is a `preDefs[i]` application with `arities[i]` arguments. -/
let isTargetApp? (e : Expr) : OptionM Nat := do
let i ← isAppOfPreDef? e
guard (e.getAppNumArgs == arities[i])
return i
-- Update values
for i in [:preDefs.size] do
let preDef := preDefs[i]
let preDefNew := preDefsNew[i]
let arity := arities[i]
let valueNew ← lambdaTelescope preDef.value fun xs body => do
if arity > 1 then
forallBoundedTelescope preDefNew.type (some 1) fun y codomain => do
let y := y[0]
let newBody ← mkPSigmaCasesOn y codomain xs body
let visit (e : Expr) : MetaM TransformStep := do
if let some idx := isTargetApp? e |>.run then
let f := e.getAppFn
let fNew := mkConst preDefsNew[idx].declName f.constLevels!
let Expr.forallE _ d .. ← inferType fNew | unreachable!
let argNew ← mkUnaryArg d e.getAppArgs
return TransformStep.done <| mkApp fNew argNew
else
return TransformStep.done e
mkLambdaFVars #[y] (← transform newBody (post := visit))
else
preDef.value
if let some bad := valueNew.find? fun e => isAppOfPreDef? e |>.isSome then
if let some i := isAppOfPreDef? bad then
throwErrorAt preDef.ref "well-founded recursion cannot be used, function '{preDef.declName}' contains application of function '{preDefs[i].declName}' with #{bad.getAppNumArgs} argument(s), but function has arity {arities[i]}"
preDefsNew := preDefsNew.set! i { preDefNew with value := valueNew }
return preDefsNew
end Lean.Elab.WF
|
149a43809fe02cff4c88ae6e7affc9c2e8185cda | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/meta/expr.lean | bba75bd21608587f684c4e4447fbcde52e3afc4b | [
"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 | 46,452 | lean | /-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis, Floris van Doorn
-/
import data.string.defs
import meta.rb_map
import tactic.derive_inhabited
/-!
# Additional operations on expr and related types
This file defines basic operations on the types expr, name, declaration, level, environment.
This file is mostly for non-tactics. Tactics should generally be placed in `tactic.core`.
## Tags
expr, name, declaration, level, environment, meta, metaprogramming, tactic
-/
attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind
@[priority 100] meta instance has_reflect.has_to_pexpr {α} [has_reflect α] : has_to_pexpr α :=
⟨λ b, pexpr.of_expr (reflect b)⟩
namespace binder_info
/-! ### Declarations about `binder_info` -/
instance : inhabited binder_info := ⟨ binder_info.default ⟩
/-- The brackets corresponding to a given binder_info. -/
def brackets : binder_info → string × string
| binder_info.implicit := ("{", "}")
| binder_info.strict_implicit := ("{{", "}}")
| binder_info.inst_implicit := ("[", "]")
| _ := ("(", ")")
end binder_info
namespace name
/-! ### Declarations about `name` -/
/-- Find the largest prefix `n` of a `name` such that `f n ≠ none`, then replace this prefix
with the value of `f n`. -/
def map_prefix (f : name → option name) : name → name
| anonymous := anonymous
| (mk_string s n') := (f (mk_string s n')).get_or_else (mk_string s $ map_prefix n')
| (mk_numeral d n') := (f (mk_numeral d n')).get_or_else (mk_numeral d $ map_prefix n')
/-- If `nm` is a simple name (having only one string component) starting with `_`, then
`deinternalize_field nm` removes the underscore. Otherwise, it does nothing. -/
meta def deinternalize_field : name → name
| (mk_string s name.anonymous) :=
let i := s.mk_iterator in
if i.curr = '_' then i.next.next_to_string else s
| n := n
/-- `get_nth_prefix nm n` removes the last `n` components from `nm` -/
meta def get_nth_prefix : name → ℕ → name
| nm 0 := nm
| nm (n + 1) := get_nth_prefix nm.get_prefix n
/-- Auxiliary definition for `pop_nth_prefix` -/
private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ
| anonymous n := (anonymous, 1)
| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in
if height ≤ n then (anonymous, height + 1)
else (nm.update_prefix pfx, height + 1)
/-- Pops the top `n` prefixes from the given name. -/
meta def pop_nth_prefix (nm : name) (n : ℕ) : name :=
prod.fst $ pop_nth_prefix_aux nm n
/-- Pop the prefix of a name -/
meta def pop_prefix (n : name) : name :=
pop_nth_prefix n 1
/-- Auxiliary definition for `from_components` -/
private def from_components_aux : name → list string → name
| n [] := n
| n (s :: rest) := from_components_aux (name.mk_string s n) rest
/-- Build a name from components. For example `from_components ["foo","bar"]` becomes
``` `foo.bar``` -/
def from_components : list string → name :=
from_components_aux name.anonymous
/-- `name`s can contain numeral pieces, which are not legal names
when typed/passed directly to the parser. We turn an arbitrary
name into a legal identifier name by turning the numbers to strings. -/
meta def sanitize_name : name → name
| name.anonymous := name.anonymous
| (name.mk_string s p) := name.mk_string s $ sanitize_name p
| (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p
/-- Append a string to the last component of a name. -/
def append_suffix : name → string → name
| (mk_string s n) s' := mk_string (s ++ s') n
| n _ := n
/-- Update the last component of a name. -/
def update_last (f : string → string) : name → name
| (mk_string s n) := mk_string (f s) n
| n := n
/-- `append_to_last nm s is_prefix` adds `s` to the last component of `nm`,
either as prefix or as suffix (specified by `is_prefix`), separated by `_`.
Used by `simps_add_projections`. -/
def append_to_last (nm : name) (s : string) (is_prefix : bool) : name :=
nm.update_last $ λ s', if is_prefix then s ++ "_" ++ s' else s' ++ "_" ++ s
/-- The first component of a name, turning a number to a string -/
meta def head : name → string
| (mk_string s anonymous) := s
| (mk_string s p) := head p
| (mk_numeral n p) := head p
| anonymous := "[anonymous]"
/-- Tests whether the first component of a name is `"_private"` -/
meta def is_private (n : name) : bool :=
n.head = "_private"
/-- Get the last component of a name, and convert it to a string. -/
meta def last : name → string
| (mk_string s _) := s
| (mk_numeral n _) := repr n
| anonymous := "[anonymous]"
/-- Returns the number of characters used to print all the string components of a name,
including periods between name segments. Ignores numerical parts of a name. -/
meta def length : name → ℕ
| (mk_string s anonymous) := s.length
| (mk_string s p) := s.length + 1 + p.length
| (mk_numeral n p) := p.length
| anonymous := "[anonymous]".length
/-- Checks whether `nm` has a prefix (including itself) such that P is true -/
def has_prefix (P : name → bool) : name → bool
| anonymous := ff
| (mk_string s nm) := P (mk_string s nm) ∨ has_prefix nm
| (mk_numeral s nm) := P (mk_numeral s nm) ∨ has_prefix nm
/-- Appends `'` to the end of a name. -/
meta def add_prime : name → name
| (name.mk_string s p) := name.mk_string (s ++ "'") p
| n := (name.mk_string "x'" n)
/-- `last_string n` returns the rightmost component of `n`, ignoring numeral components.
For example, ``last_string `a.b.c.33`` will return `` `c ``. -/
def last_string : name → string
| anonymous := "[anonymous]"
| (mk_string s _) := s
| (mk_numeral _ n) := last_string n
/--
Constructs a (non-simple) name from a string.
Example: ``name.from_string "foo.bar" = `foo.bar``
-/
meta def from_string (s : string) : name :=
from_components $ s.split (= '.')
/--
In surface Lean, we can write anonymous Π binders (i.e. binders where the
argument is not named) using the function arrow notation:
```lean
inductive test : Type
| intro : unit → test
```
After elaboration, however, every binder must have a name, so Lean generates
one. In the example, the binder in the type of `intro` is anonymous, so Lean
gives it the name `ᾰ`:
```lean
test.intro : ∀ (ᾰ : unit), test
```
When there are multiple anonymous binders, they are named `ᾰ_1`, `ᾰ_2` etc.
Thus, when we want to know whether the user named a binder, we can check whether
the name follows this scheme. Note, however, that this is not reliable. When the
user writes (for whatever reason)
```lean
inductive test : Type
| intro : ∀ (ᾰ : unit), test
```
we cannot tell that the binder was, in fact, named.
The function `name.is_likely_generated_binder_name` checks if
a name is of the form `ᾰ`, `ᾰ_1`, etc.
-/
library_note "likely generated binder names"
/--
Check whether a simple name was likely generated by Lean to name an anonymous
binder. Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_simple_name : string → bool
| "ᾰ" := tt
| n :=
match n.get_rest "ᾰ_" with
| none := ff
| some suffix := suffix.is_nat
end
/--
Check whether a name was likely generated by Lean to name an anonymous binder.
Such names are either `ᾰ` or `ᾰ_n` for some natural `n`. See
note [likely generated binder names].
-/
meta def is_likely_generated_binder_name (n : name) : bool :=
match n with
| mk_string s anonymous := is_likely_generated_binder_simple_name s
| _ := ff
end
end name
namespace level
/-! ### Declarations about `level` -/
/-- Tests whether a universe level is non-zero for all assignments of its variables -/
meta def nonzero : level → bool
| (succ _) := tt
| (max l₁ l₂) := l₁.nonzero || l₂.nonzero
| (imax _ l₂) := l₂.nonzero
| _ := ff
/--
`l.fold_mvar f` folds a function `f : name → α → α`
over each `n : name` appearing in a `level.mvar n` in `l`.
-/
meta def fold_mvar {α} : level → (name → α → α) → α → α
| zero f := id
| (succ a) f := fold_mvar a f
| (param a) f := id
| (mvar a) f := f a
| (max a b) f := fold_mvar a f ∘ fold_mvar b f
| (imax a b) f := fold_mvar a f ∘ fold_mvar b f
/--
`l.params` is the set of parameters occuring in `l`.
For example if `l = max 1 (max (u+1) (max v w))` then `l.params = {u, v, w}`.
-/
protected meta def params (u : level) : name_set :=
u.fold mk_name_set $ λ v l,
match v with
| (param nm) := l.insert nm
| _ := l
end
end level
/-! ### Declarations about `binder` -/
/-- The type of binders containing a name, the binding info and the binding type -/
@[derive decidable_eq, derive inhabited]
meta structure binder :=
(name : name)
(info : binder_info)
(type : expr)
namespace binder
/-- Turn a binder into a string. Uses expr.to_string for the type. -/
protected meta def to_string (b : binder) : string :=
let (l, r) := b.info.brackets in
l ++ b.name.to_string ++ " : " ++ b.type.to_string ++ r
open tactic
meta instance : has_to_string binder := ⟨ binder.to_string ⟩
meta instance : has_to_format binder := ⟨ λ b, b.to_string ⟩
meta instance : has_to_tactic_format binder :=
⟨ λ b, let (l, r) := b.info.brackets in
(λ e, l ++ b.name.to_string ++ " : " ++ e ++ r) <$> pp b.type ⟩
end binder
/-!
### Converting between expressions and numerals
There are a number of ways to convert between expressions and numerals, depending on the input and
output types and whether you want to infer the necessary type classes.
See also the tactics `expr.of_nat`, `expr.of_int`, `expr.of_rat`.
-/
/--
`nat.mk_numeral n` embeds `n` as a numeral expression inside a type with 0, 1, and +.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`: expressions of the type `has_zero %%type`, etc.
-/
meta def nat.mk_numeral (type has_zero has_one has_add : expr) : ℕ → expr :=
let z : expr := `(@has_zero.zero.{0} %%type %%has_zero),
o : expr := `(@has_one.one.{0} %%type %%has_one) in
nat.binary_rec z
(λ b n e, if n = 0 then o else
if b then `(@bit1.{0} %%type %%has_one %%has_add %%e)
else `(@bit0.{0} %%type %%has_add %%e))
/--
`int.mk_numeral z` embeds `z` as a numeral expression inside a type with 0, 1, +, and -.
`type`: an expression representing the target type. This must live in Type 0.
`has_zero`, `has_one`, `has_add`, `has_neg`: expressions of the type `has_zero %%type`, etc.
-/
meta def int.mk_numeral (type has_zero has_one has_add has_neg : expr) : ℤ → expr
| (int.of_nat n) := n.mk_numeral type has_zero has_one has_add
| -[1+n] := let ne := (n+1).mk_numeral type has_zero has_one has_add in
`(@has_neg.neg.{0} %%type %%has_neg %%ne)
/--
`nat.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(nat.to_pexpr 5) : ℤ))` will create a native integer numeral `(5 : ℤ)`.
-/
meta def nat.to_pexpr : ℕ → pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))
namespace expr
/--
Turns an expression into a natural number, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero`, `nat.zero`, and `nat.succ`.
-/
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero) := some 0
| `(has_one.one) := some 1
| `(bit0 %%e) := bit0 <$> e.to_nat
| `(bit1 %%e) := bit1 <$> e.to_nat
| `(nat.succ %%e) := (+1) <$> e.to_nat
| `(nat.zero) := some 0
| _ := none
/--
Turns an expression into a integer, assuming it is only built up from
`has_one.one`, `bit0`, `bit1`, `has_zero.zero` and a optionally a single `has_neg.neg` as head.
-/
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := coe <$> e.to_nat
/--
Turns an expression into a list, assuming it is only built up from `list.nil` and `list.cons`.
-/
protected meta def to_list {α} (f : expr → option α) : expr → option (list α)
| `(list.nil) := some []
| `(list.cons %%x %%l) := list.cons <$> f x <*> l.to_list
| _ := none
/--
`is_num_eq n1 n2` returns true if `n1` and `n2` are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
meta def is_num_eq : expr → expr → bool
| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt
| `(@has_one.one _ _) `(@has_one.one _ _) := tt
| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b
| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b
| `(-%%a) `(-%%b) := a.is_num_eq b
| `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b
| _ _ := ff
end expr
/-! ### Declarations about `expr` -/
namespace expr
open tactic
/-- List of names removed by `clean`. All these names must resolve to functions defeq `id`. -/
meta def clean_ids : list name :=
[``id, ``id_rhs, ``id_delta, ``hidden]
/-- Clean an expression by removing `id`s listed in `clean_ids`. -/
meta def clean (e : expr) : expr :=
e.replace (λ e n,
match e with
| (app (app (const n _) _) e') :=
if n ∈ clean_ids then some e' else none
| (app (lam _ _ _ (var 0)) e') := some e'
| _ := none
end)
/-- `replace_with e s s'` replaces ocurrences of `s` with `s'` in `e`. -/
meta def replace_with (e : expr) (s : expr) (s' : expr) : expr :=
e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none
/-- Implementation of `expr.mreplace`. -/
meta def mreplace_aux {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) :
expr → ℕ → m expr
| (app f x) n := option.mget_or_else (R (app f x) n)
(do Rf ← mreplace_aux f n, Rx ← mreplace_aux x n, return $ app Rf Rx)
| (lam nm bi ty bd) n := option.mget_or_else (R (lam nm bi ty bd) n)
(do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ lam nm bi Rty Rbd)
| (pi nm bi ty bd) n := option.mget_or_else (R (pi nm bi ty bd) n)
(do Rty ← mreplace_aux ty n, Rbd ← mreplace_aux bd (n+1), return $ pi nm bi Rty Rbd)
| (elet nm ty a b) n := option.mget_or_else (R (elet nm ty a b) n)
(do Rty ← mreplace_aux ty n,
Ra ← mreplace_aux a n,
Rb ← mreplace_aux b n,
return $ elet nm Rty Ra Rb)
| (macro c es) n := option.mget_or_else (R (macro c es) n) $
macro c <$> es.mmap (λ e, mreplace_aux e n)
| e n := option.mget_or_else (R e n) (return e)
/--
Monadic analogue of `expr.replace`.
The `mreplace R e` visits each subexpression `s` of `e`, and is called with `R s n`, where
`n` is the number of binders above `e`.
If `R s n` fails, the whole replacement fails.
If `R s n` returns `some t`, `s` is replaced with `t` (and `mreplace` does not visit
its subexpressions).
If `R s n` return `none`, then `mreplace` continues visiting subexpressions of `s`.
WARNING: This function performs exponentially worse on large terms than `expr.replace`,
if a subexpression occurs more than once in an expression, `expr.replace` visits them only once,
but this function will visit every occurence of it. Do not use this on large expressions.
-/
meta def mreplace {m : Type* → Type*} [monad m] (R : expr → nat → m (option expr)) (e : expr) :
m expr :=
mreplace_aux R e 0
/-- Match a variable. -/
meta def match_var {elab} : expr elab → option ℕ
| (var n) := some n
| _ := none
/-- Match a sort. -/
meta def match_sort {elab} : expr elab → option level
| (sort u) := some u
| _ := none
/-- Match a constant. -/
meta def match_const {elab} : expr elab → option (name × list level)
| (const n lvls) := some (n, lvls)
| _ := none
/-- Match a metavariable. -/
meta def match_mvar {elab} : expr elab →
option (name × name × expr elab)
| (mvar unique pretty type) := some (unique, pretty, type)
| _ := none
/-- Match a local constant. -/
meta def match_local_const {elab} : expr elab →
option (name × name × binder_info × expr elab)
| (local_const unique pretty bi type) := some (unique, pretty, bi, type)
| _ := none
/-- Match an application. -/
meta def match_app {elab} : expr elab → option (expr elab × expr elab)
| (app t u) := some (t, u)
| _ := none
/-- Match an application of `coe_fn`. -/
meta def match_app_coe_fn : expr → option (expr × expr × expr × expr × expr)
| (app `(@coe_fn %%α %%β %%inst %%fexpr) x) := some (α, β, inst, fexpr, x)
| _ := none
/-- Match an abstraction. -/
meta def match_lam {elab} : expr elab →
option (name × binder_info × expr elab × expr elab)
| (lam var_name bi type body) := some (var_name, bi, type, body)
| _ := none
/-- Match a Π type. -/
meta def match_pi {elab} : expr elab →
option (name × binder_info × expr elab × expr elab)
| (pi var_name bi type body) := some (var_name, bi, type, body)
| _ := none
/-- Match a let. -/
meta def match_elet {elab} : expr elab →
option (name × expr elab × expr elab × expr elab)
| (elet var_name type assignment body) := some (var_name, type, assignment, body)
| _ := none
/-- Match a macro. -/
meta def match_macro {elab} : expr elab →
option (macro_def × list (expr elab))
| (macro df args) := some (df, args)
| _ := none
/-- Tests whether an expression is a meta-variable. -/
meta def is_mvar : expr → bool
| (mvar _ _ _) := tt
| _ := ff
/-- Tests whether an expression is a sort. -/
meta def is_sort : expr → bool
| (sort _) := tt
| e := ff
/-- Get the universe levels of a `const` expression -/
meta def univ_levels : expr → list level
| (const n ls) := ls
| _ := []
/--
Replace any metavariables in the expression with underscores, in preparation for printing
`refine ...` statements.
-/
meta def replace_mvars (e : expr) : expr :=
e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none)
/-- If `e` is a local constant, `to_implicit_local_const e` changes the binder info of `e` to
`implicit`. See also `to_implicit_binder`, which also changes lambdas and pis. -/
meta def to_implicit_local_const : expr → expr
| (expr.local_const uniq n bi t) := expr.local_const uniq n binder_info.implicit t
| e := e
/-- If `e` is a local constant, lamda, or pi expression, `to_implicit_binder e` changes the binder
info of `e` to `implicit`. See also `to_implicit_local_const`, which only changes local constants.
-/
meta def to_implicit_binder : expr → expr
| (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d
| (lam n _ d b) := lam n binder_info.implicit d b
| (pi n _ d b) := pi n binder_info.implicit d b
| e := e
/-- Returns a list of all local constants in an expression (without duplicates). -/
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)
/-- Returns the set of all local constants in an expression. -/
meta def list_local_consts' (e : expr) : expr_set :=
e.fold mk_expr_set (λ e' _ es, if e'.is_local_constant then es.insert e' else es)
/-- Returns the unique names of all local constants in an expression. -/
meta def list_local_const_unique_names (e : expr) : name_set :=
e.fold mk_name_set
(λ e' _ es, if e'.is_local_constant then es.insert e'.local_uniq_name else es)
/-- Returns a name_set of all constants in an expression. -/
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)
/-- Returns a list of all meta-variables in an expression (without duplicates). -/
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_mvar then insert e' es else es)
/-- Returns the set of all meta-variables in an expression. -/
meta def list_meta_vars' (e : expr) : expr_set :=
e.fold mk_expr_set (λ e' _ es, if e'.is_mvar then es.insert e' else es)
/-- Returns a list of all universe meta-variables in an expression (without duplicates). -/
meta def list_univ_meta_vars (e : expr) : list name :=
native.rb_set.to_list $ e.fold native.mk_rb_set $ λ e' i s,
match e' with
| (sort u) := u.fold_mvar (flip native.rb_set.insert) s
| (const _ ls) := ls.foldl (λ s' l, l.fold_mvar (flip native.rb_set.insert) s') s
| _ := s
end
/--
Test `t` contains the specified subexpression `e`, or a metavariable.
This represents the notion that `e` "may occur" in `t`,
possibly after subsequent unification.
-/
meta def contains_expr_or_mvar (t : expr) (e : expr) : bool :=
-- We can't use `t.has_meta_var` here, as that detects universe metavariables, too.
¬ t.list_meta_vars.empty ∨ e.occurs t
/-- Returns a name_set of all constants in an expression starting with a certain prefix. -/
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
match e' with
| expr.const n _ := if n.get_prefix = pre then l.insert n else l
| _ := l
end
/-- Returns true if `e` contains a name `n` where `p n` is true.
Returns `true` if `p name.anonymous` is true. -/
meta def contains_constant (e : expr) (p : name → Prop) [decidable_pred p] : bool :=
e.fold ff (λ e' _ b, if p (e'.const_name) then tt else b)
/--
Returns true if `e` contains a `sorry`.
-/
meta def contains_sorry (e : expr) : bool :=
e.fold ff (λ e' _ b, if (is_sorry e').is_some then tt else b)
/--
`app_symbol_in e l` returns true iff `e` is an application of a constant whose name is in `l`.
-/
meta def app_symbol_in (e : expr) (l : list name) : bool :=
match e.get_app_fn with
| (expr.const n _) := n ∈ l
| _ := ff
end
/-- `get_simp_args e` returns the arguments of `e` that simp can reach via congruence lemmas. -/
meta def get_simp_args (e : expr) : tactic (list expr) :=
-- `mk_specialized_congr_lemma_simp` throws an assertion violation if its argument is not an app
if ¬ e.is_app then pure [] else do
cgr ← mk_specialized_congr_lemma_simp e,
pure $ do
(arg_kind, arg) ← cgr.arg_kinds.zip e.get_app_args,
guard $ arg_kind = congr_arg_kind.eq,
pure arg
/-- Simplifies the expression `t` with the specified options.
The result is `(new_e, pr)` with the new expression `new_e` and a proof
`pr : e = new_e`. -/
meta def simp (t : expr)
(cfg : simp_config := {}) (discharger : tactic unit := failed)
(no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
tactic (expr × expr × name_set) :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
simplify s to_unfold t cfg `eq discharger
/-- Definitionally simplifies the expression `t` with the specified options.
The result is the simplified expression. -/
meta def dsimp (t : expr)
(cfg : dsimp_config := {})
(no_defaults := ff) (attr_names : list name := []) (hs : list simp_arg_type := []) :
tactic expr :=
do (s, to_unfold) ← mk_simp_set no_defaults attr_names hs,
s.dsimplify to_unfold t cfg
/-- Get the names of the bound variables by a sequence of pis or lambdas. -/
meta def binding_names : expr → list name
| (pi n _ _ e) := n :: e.binding_names
| (lam n _ _ e) := n :: e.binding_names
| e := []
/-- head-reduce a single let expression -/
meta def reduce_let : expr → expr
| (elet _ _ v b) := b.instantiate_var v
| e := e
/-- head-reduce all let expressions -/
meta def reduce_lets : expr → expr
| (elet _ _ v b) := reduce_lets $ b.instantiate_var v
| e := e
/-- Instantiate lambdas in the second argument by expressions from the first. -/
meta def instantiate_lambdas : list expr → expr → expr
| (e'::es) (lam n bi t e) := instantiate_lambdas es (e.instantiate_var e')
| _ e := e
/-- Repeatedly apply `expr.subst`. -/
meta def substs : expr → list expr → expr | e es := es.foldl expr.subst e
/-- `instantiate_lambdas_or_apps es e` instantiates lambdas in `e` by expressions from `es`.
If the length of `es` is larger than the number of lambdas in `e`,
then the term is applied to the remaining terms.
Also reduces head let-expressions in `e`, including those after instantiating all lambdas.
This is very similar to `expr.substs`, but this also reduces head let-expressions. -/
meta def instantiate_lambdas_or_apps : list expr → expr → expr
| (v::es) (lam n bi t b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es (elet _ _ v b) := instantiate_lambdas_or_apps es $ b.instantiate_var v
| es e := mk_app e es
/--
Some declarations work with open expressions, i.e. an expr that has free variables.
Terms will free variables are not well-typed, and one should not use them in tactics like
`infer_type` or `unify`. You can still do syntactic analysis/manipulation on them.
The reason for working with open types is for performance: instantiating variables requires
iterating through the expression. In one performance test `pi_binders` was more than 6x
quicker than `mk_local_pis` (when applied to the type of all imported declarations 100x).
-/
library_note "open expressions"
/-- Get the codomain/target of a pi-type.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
See note [open expressions]. -/
meta def pi_codomain : expr → expr
| (pi n bi d b) := pi_codomain b
| e := e
/-- Get the body/value of a lambda-expression.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
See note [open expressions]. -/
meta def lambda_body : expr → expr
| (lam n bi d b) := lambda_body b
| e := e
/-- Auxiliary defintion for `pi_binders`.
See note [open expressions]. -/
meta def pi_binders_aux : list binder → expr → list binder × expr
| es (pi n bi d b) := pi_binders_aux (⟨n, bi, d⟩::es) b
| es e := (es, e)
/-- Get the binders and codomain of a pi-type.
This definition doesn't instantiate bound variables, and therefore produces a term that is open.
The.tactic `get_pi_binders` in `tactic.core` does the same, but also instantiates the
free variables.
See note [open expressions]. -/
meta def pi_binders (e : expr) : list binder × expr :=
let (es, e) := pi_binders_aux [] e in (es.reverse, e)
/-- Auxiliary defintion for `get_app_fn_args`. -/
meta def get_app_fn_args_aux : list expr → expr → expr × list expr
| r (app f a) := get_app_fn_args_aux (a::r) f
| r e := (e, r)
/-- A combination of `get_app_fn` and `get_app_args`: lists both the
function and its arguments of an application -/
meta def get_app_fn_args : expr → expr × list expr :=
get_app_fn_args_aux []
/-- `drop_pis es e` instantiates the pis in `e` with the expressions from `es`. -/
meta def drop_pis : list expr → expr → tactic expr
| (v :: vs) (pi n bi d b) := do
t ← infer_type v,
guard (t =ₐ d),
drop_pis vs (b.instantiate_var v)
| [] e := return e
| _ _ := failed
/-- `instantiate_pis es e` instantiates the pis in `e` with the expressions from `es`.
Does not check whether the result remains type-correct. -/
meta def instantiate_pis : list expr → expr → expr
| (v :: vs) (pi n bi d b) := instantiate_pis vs (b.instantiate_var v)
| _ e := e
/-- `mk_op_lst op empty [x1, x2, ...]` is defined as `op x1 (op x2 ...)`.
Returns `empty` if the list is empty. -/
meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr
| [] := empty
| [e] := e
| (e :: es) := op e $ mk_op_lst es
/-- `mk_and_lst [x1, x2, ...]` is defined as `x1 ∧ (x2 ∧ ...)`, or `true` if the list is empty. -/
meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true)
/-- `mk_or_lst [x1, x2, ...]` is defined as `x1 ∨ (x2 ∨ ...)`, or `false` if the list is empty. -/
meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false)
/-- `local_binding_info e` returns the binding info of `e` if `e` is a local constant.
Otherwise returns `binder_info.default`. -/
meta def local_binding_info : expr → binder_info
| (expr.local_const _ _ bi _) := bi
| _ := binder_info.default
/-- `is_default_local e` tests whether `e` is a local constant with binder info
`binder_info.default` -/
meta def is_default_local : expr → bool
| (expr.local_const _ _ binder_info.default _) := tt
| _ := ff
/-- `has_local_constant e l` checks whether local constant `l` occurs in expression `e` -/
meta def has_local_constant (e l : expr) : bool :=
e.has_local_in $ mk_name_set.insert l.local_uniq_name
/-- Turns a local constant into a binder -/
meta def to_binder : expr → binder
| (local_const _ nm bi t) := ⟨nm, bi, t⟩
| _ := default binder
/-- Strip-away the context-dependent unique id for the given local const and return: its friendly
`name`, its `binder_info`, and its `type : expr`. -/
meta def get_local_const_kind : expr → name × binder_info × expr
| (expr.local_const _ n bi e) := (n, bi, e)
| _ := (name.anonymous, binder_info.default, expr.const name.anonymous [])
/-- `local_const_set_type e t` sets the type of `e` to `t`, if `e` is a `local_const`. -/
meta def local_const_set_type {elab : bool} : expr elab → expr elab → expr elab
| (expr.local_const x n bi t) new_t := expr.local_const x n bi new_t
| e new_t := e
/-- `unsafe_cast e` freely changes the `elab : bool` parameter of the passed `expr`. Mainly used to
access core `expr` manipulation functions for `pexpr`-based use, but which are restricted to
`expr tt` at the site of definition unnecessarily.
DANGER: Unless you know exactly what you are doing, this is probably not the function you are
looking for. For `pexpr → expr` see `tactic.to_expr`. For `expr → pexpr` see `to_pexpr`. -/
meta def unsafe_cast {elab₁ elab₂ : bool} : expr elab₁ → expr elab₂ := unchecked_cast
/-- `replace_subexprs e mappings` takes an `e : expr` and interprets a `list (expr × expr)` as
a collection of rules for variable replacements. A pair `(f, t)` encodes a rule which says "whenever
`f` is encountered in `e` verbatim, replace it with `t`". -/
meta def replace_subexprs {elab : bool} (e : expr elab) (mappings : list (expr × expr)) :
expr elab :=
unsafe_cast $ e.unsafe_cast.replace $ λ e n,
(mappings.filter $ λ ent : expr × expr, ent.1 = e).head'.map prod.snd
/-- `is_implicitly_included_variable e vs` accepts `e`, an `expr.local_const`, and a list `vs` of
other `expr.local_const`s. It determines whether `e` should be considered "available in context"
as a variable by virtue of the fact that the variables `vs` have been deemed such.
For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that
the typeclass instance `prime n` should be included, but `ih : even n` should not.
DANGER: It is possible that for `f : expr` another `expr.local_const`, we have
`is_implicitly_included_variable f vs = ff` but
`is_implicitly_included_variable f (e :: vs) = tt`. This means that one usually wants to
iteratively add a list of local constants (usually, the `variables` declared in the local scope)
which satisfy `is_implicitly_included_variable` to an initial `vs`, repeating if any variables
were added in a particular iteration. The function `all_implicitly_included_variables` below
implements this behaviour.
Note that if `e ∈ vs` then `is_implicitly_included_variable e vs = tt`. -/
meta def is_implicitly_included_variable (e : expr) (vs : list expr) : bool :=
if ¬(e.local_pp_name.to_string.starts_with "_") then
e ∈ vs
else e.local_type.fold tt $ λ se _ b,
if ¬b then ff
else if ¬se.is_local_constant then tt
else se ∈ vs
/-- Private work function for `all_implicitly_included_variables`, performing the actual series of
iterations, tracking with a boolean whether any updates occured this iteration. -/
private meta def all_implicitly_included_variables_aux
: list expr → list expr → list expr → bool → list expr
| [] vs rs tt := all_implicitly_included_variables_aux rs vs [] ff
| [] vs rs ff := vs
| (e :: rest) vs rs b :=
let (vs, rs, b) :=
if e.is_implicitly_included_variable vs then (e :: vs, rs, tt) else (vs, e :: rs, b) in
all_implicitly_included_variables_aux rest vs rs b
/-- `all_implicitly_included_variables es vs` accepts `es`, a list of `expr.local_const`, and `vs`,
another such list. It returns a list of all variables `e` in `es` or `vs` for which an inclusion
of the variables in `vs` into the local context implies that `e` should also be included. See
`is_implicitly_included_variable e vs` for the details.
In particular, those elements of `vs` are included automatically. -/
meta def all_implicitly_included_variables (es vs : list expr) : list expr :=
all_implicitly_included_variables_aux es vs [] ff
/-- Infer the type of an application of the form `f x1 x2 ... xn`, where `f` is an identifier.
This also works if `x1, ... xn` contain free variables. -/
protected meta def simple_infer_type (env : environment) (e : expr) : exceptional expr := do
(@const tt n ls, es) ← return e.get_app_fn_args |
exceptional.fail "expression is not a constant applied to arguments",
d ← env.get n,
return $ (d.type.instantiate_pis es).instantiate_univ_params $ d.univ_params.zip ls
/-- Auxilliary function for `head_eta_expand`. -/
meta def head_eta_expand_aux : ℕ → expr → expr → expr
| (n+1) e (pi x bi d b) :=
lam x bi d $ head_eta_expand_aux n e b
| _ e _ := e
/-- `head_eta_expand n e t` eta-expands `e` `n` times, with the binders info and domains obtained
by its type `t`. -/
meta def head_eta_expand (n : ℕ) (e t : expr) : expr :=
((e.lift_vars 0 n).mk_app $ (list.range n).reverse.map var).head_eta_expand_aux n t
/-- `e.eta_expand env dict` eta-expands all expressions that have as head a constant `n` in
`dict`. They are expanded until they are applied to one more argument than the maximum in
`dict.find n`. -/
protected meta def eta_expand (env : environment) (dict : name_map $ list ℕ) : expr → expr
| e := e.replace $ λ e _, do
let (e0, es) := e.get_app_fn_args,
let ns := (dict.find e0.const_name).iget,
guard (bnot ns.empty),
let e' := e0.mk_app $ es.map eta_expand,
let needed_n := ns.foldr max 0 + 1,
if needed_n ≤ es.length then some e'
else do
e'_type ← (e'.simple_infer_type env).to_option,
some $ head_eta_expand (needed_n - es.length) e' e'_type
/--
`e.apply_replacement_fun f test` applies `f` to each identifier
(inductive type, defined function etc) in an expression, unless
* The identifier occurs in an application with first argument `arg`; and
* `test arg` is false.
However, if `f` is in the dictionary `relevant`, then the argument `relevant.find f`
is tested, instead of the first argument.
Reorder contains the information about what arguments to reorder:
e.g. `g x₁ x₂ x₃ ... xₙ` becomes `g x₂ x₁ x₃ ... xₙ` if `reorder.find g = some [1]`.
We assume that all functions where we want to reorder arguments are fully applied.
This can be done by applying `expr.eta_expand` first.
-/
protected meta def apply_replacement_fun (f : name → name) (test : expr → bool)
(relevant : name_map ℕ) (reorder : name_map $ list ℕ) : expr → expr
| e := e.replace $ λ e _,
match e with
| const n ls := some $ const (f n) $
-- if the first two arguments are reordered, we also reorder the first two universe parameters
if 1 ∈ (reorder.find n).iget then ls.inth 1::ls.head::ls.drop 2 else ls
| app g x :=
let f := g.get_app_fn,
nm := f.const_name,
n_args := g.get_app_num_args in -- this might be inefficient
if n_args ∈ (reorder.find nm).iget ∧ test g.get_app_args.head then
-- interchange `x` and the last argument of `g`
some $ apply_replacement_fun g.app_fn (apply_replacement_fun x) $
apply_replacement_fun g.app_arg else
if n_args = (relevant.find nm).lhoare 0 ∧ f.is_constant ∧ ¬ test x then
some $ (f.mk_app $ g.get_app_args.map apply_replacement_fun) (apply_replacement_fun x) else
none
| _ := none
end
end expr
/-! ### Declarations about `environment` -/
namespace environment
/-- Tests whether `n` is a structure. -/
meta def is_structure (env : environment) (n : name) : bool :=
(env.structure_fields n).is_some
/-- Get the full names of all projections of the structure `n`. Returns `none` if `n` is not a
structure. -/
meta def structure_fields_full (env : environment) (n : name) : option (list name) :=
(env.structure_fields n).map (list.map $ λ n', n ++ n')
/-- Tests whether `nm` is a generalized inductive type that is not a normal inductive type.
Note that `is_ginductive` returns `tt` even on regular inductive types.
This returns `tt` if `nm` is (part of a) mutually defined inductive type or a nested inductive
type. -/
meta def is_ginductive' (e : environment) (nm : name) : bool :=
e.is_ginductive nm ∧ ¬ e.is_inductive nm
/-- For all declarations `d` where `f d = some x` this adds `x` to the returned list. -/
meta def decl_filter_map {α : Type} (e : environment) (f : declaration → option α) : list α :=
e.fold [] $ λ d l, match f d with
| some r := r :: l
| none := l
end
/-- Maps `f` to all declarations in the environment. -/
meta def decl_map {α : Type} (e : environment) (f : declaration → α) : list α :=
e.decl_filter_map $ λ d, some (f d)
/-- Lists all declarations in the environment -/
meta def get_decls (e : environment) : list declaration :=
e.decl_map id
/-- Lists all trusted (non-meta) declarations in the environment -/
meta def get_trusted_decls (e : environment) : list declaration :=
e.decl_filter_map (λ d, if d.is_trusted then some d else none)
/-- Lists the name of all declarations in the environment -/
meta def get_decl_names (e : environment) : list name :=
e.decl_map declaration.to_name
/-- Fold a monad over all declarations in the environment. -/
meta def mfold {α : Type} {m : Type → Type} [monad m] (e : environment) (x : α)
(fn : declaration → α → m α) : m α :=
e.fold (return x) (λ d t, t >>= fn d)
/-- Filters all declarations in the environment. -/
meta def filter (e : environment) (test : declaration → bool) : list declaration :=
e.fold [] $ λ d ds, if test d then d::ds else ds
/-- Filters all declarations in the environment. -/
meta def mfilter (e : environment) (test : declaration → tactic bool) : tactic (list declaration) :=
e.mfold [] $ λ d ds, do b ← test d, return $ if b then d::ds else ds
/-- Checks whether `s` is a prefix of the file where `n` is declared.
This is used to check whether `n` is declared in mathlib, where `s` is the mathlib directory. -/
meta def is_prefix_of_file (e : environment) (s : string) (n : name) : bool :=
s.is_prefix_of $ (e.decl_olean n).get_or_else ""
end environment
/-!
### `is_eta_expansion`
In this section we define the tactic `is_eta_expansion` which checks whether an expression
is an eta-expansion of a structure. (not to be confused with eta-expanion for `λ`).
-/
namespace expr
open tactic
/-- `is_eta_expansion_of args univs l` checks whether for all elements `(nm, pr)` in `l` we have
`pr = nm.{univs} args`.
Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
want to eta-reduce. -/
meta def is_eta_expansion_of (args : list expr) (univs : list level) (l : list (name × expr)) :
bool :=
l.all $ λ⟨proj, val⟩, val = (const proj univs).mk_app args
/-- `is_eta_expansion_test l` checks whether there is a list of expresions `args` such that for all
elements `(nm, pr)` in `l` we have `pr = nm args`. If so, returns the last element of `args`.
Used in `is_eta_expansion`, where `l` consists of the projections and the fields of the value we
want to eta-reduce. -/
meta def is_eta_expansion_test : list (name × expr) → option expr
| [] := none
| (⟨proj, val⟩::l) :=
match val.get_app_fn with
| (const nm univs : expr) :=
if nm = proj then
let args := val.get_app_args in
let e := args.ilast in
if is_eta_expansion_of args univs l then some e else none
else
none
| _ := none
end
/-- `is_eta_expansion_aux val l` checks whether `val` can be eta-reduced to an expression `e`.
Here `l` is intended to consists of the projections and the fields of `val`.
This tactic calls `is_eta_expansion_test l`, but first removes all proofs from the list `l` and
afterward checks whether the resulting expression `e` unifies with `val`.
This last check is necessary, because `val` and `e` might have different types. -/
meta def is_eta_expansion_aux (val : expr) (l : list (name × expr)) : tactic (option expr) :=
do l' ← l.mfilter (λ⟨proj, val⟩, bnot <$> is_proof val),
match is_eta_expansion_test l' with
| some e := option.map (λ _, e) <$> try_core (unify e val)
| none := return none
end
/-- `is_eta_expansion val` checks whether there is an expression `e` such that `val` is the
eta-expansion of `e`.
With eta-expansion we here mean the eta-expansion of a structure, not of a function.
For example, the eta-expansion of `x : α × β` is `⟨x.1, x.2⟩`.
This assumes that `val` is a fully-applied application of the constructor of a structure.
This is useful to reduce expressions generated by the notation
`{ field_1 := _, ..other_structure }`
If `other_structure` is itself a field of the structure, then the elaborator will insert an
eta-expanded version of `other_structure`. -/
meta def is_eta_expansion (val : expr) : tactic (option expr) := do
e ← get_env,
type ← infer_type val,
projs ← e.structure_fields_full type.get_app_fn.const_name,
let args := (val.get_app_args).drop type.get_app_args.length,
is_eta_expansion_aux val (projs.zip args)
end expr
/-! ### Declarations about `declaration` -/
namespace declaration
open tactic
/--
`declaration.update_with_fun f test tgt decl`
sets the name of the given `decl : declaration` to `tgt`, and applies both `expr.eta_expand` and
`expr.apply_replacement_fun` to the value and type of `decl`.
-/
protected meta def update_with_fun (env : environment) (f : name → name) (test : expr → bool)
(relevant : name_map ℕ) (reorder : name_map $ list ℕ) (tgt : name) (decl : declaration) :
declaration :=
let decl := decl.update_name $ tgt in
let decl := decl.update_type $
(decl.type.eta_expand env reorder).apply_replacement_fun f test relevant reorder in
decl.update_value $
(decl.value.eta_expand env reorder).apply_replacement_fun f test relevant reorder
/-- Checks whether the declaration is declared in the current file.
This is a simple wrapper around `environment.in_current_file`
Use `environment.in_current_file` instead if performance matters. -/
meta def in_current_file (d : declaration) : tactic bool :=
do e ← get_env, return $ e.in_current_file d.to_name
/-- Checks whether a declaration is a theorem -/
meta def is_theorem : declaration → bool
| (thm _ _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is a constant -/
meta def is_constant : declaration → bool
| (cnst _ _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is a axiom -/
meta def is_axiom : declaration → bool
| (ax _ _ _) := tt
| _ := ff
/-- Checks whether a declaration is automatically generated in the environment.
There is no cheap way to check whether a declaration in the namespace of a generalized
inductive type is automatically generated, so for now we say that all of them are automatically
generated. -/
meta def is_auto_generated (e : environment) (d : declaration) : bool :=
e.is_constructor d.to_name ∨
(e.is_projection d.to_name).is_some ∨
(e.is_constructor d.to_name.get_prefix ∧
d.to_name.last ∈ ["inj", "inj_eq", "sizeof_spec", "inj_arrow"]) ∨
(e.is_inductive d.to_name.get_prefix ∧
d.to_name.last ∈ ["below", "binduction_on", "brec_on", "cases_on", "dcases_on", "drec_on", "drec",
"rec", "rec_on", "no_confusion", "no_confusion_type", "sizeof", "ibelow", "has_sizeof_inst"]) ∨
d.to_name.has_prefix (λ nm, e.is_ginductive' nm)
/--
Returns true iff `d` is an automatically-generated or internal declaration.
-/
meta def is_auto_or_internal (env : environment) (d : declaration) : bool :=
d.to_name.is_internal || d.is_auto_generated env
/-- Returns the list of universe levels of a declaration. -/
meta def univ_levels (d : declaration) : list level :=
d.univ_params.map level.param
/-- Returns the `reducibility_hints` field of a `defn`, and `reducibility_hints.opaque` otherwise -/
protected meta def reducibility_hints : declaration → reducibility_hints
| (declaration.defn _ _ _ _ red _) := red
| _ := _root_.reducibility_hints.opaque
/-- formats the arguments of a `declaration.thm` -/
private meta def print_thm (nm : name) (tp : expr) (body : task expr) : tactic format :=
do tp ← pp tp, body ← pp body.get,
return $ "<theorem " ++ to_fmt nm ++ " : " ++ tp ++ " := " ++ body ++ ">"
/-- formats the arguments of a `declaration.defn` -/
private meta def print_defn (nm : name) (tp : expr) (body : expr) (is_trusted : bool) :
tactic format :=
do tp ← pp tp, body ← pp body,
return $ "<" ++ (if is_trusted then "def " else "meta def ") ++ to_fmt nm ++ " : " ++ tp ++
" := " ++ body ++ ">"
/-- formats the arguments of a `declaration.cnst` -/
private meta def print_cnst (nm : name) (tp : expr) (is_trusted : bool) : tactic format :=
do tp ← pp tp,
return $ "<" ++ (if is_trusted then "constant " else "meta constant ") ++ to_fmt nm ++ " : "
++ tp ++ ">"
/-- formats the arguments of a `declaration.ax` -/
private meta def print_ax (nm : name) (tp : expr) : tactic format :=
do tp ← pp tp,
return $ "<axiom " ++ to_fmt nm ++ " : " ++ tp ++ ">"
/-- pretty-prints a `declaration` object. -/
meta def to_tactic_format : declaration → tactic format
| (declaration.thm nm _ tp bd) := print_thm nm tp bd
| (declaration.defn nm _ tp bd _ is_trusted) := print_defn nm tp bd is_trusted
| (declaration.cnst nm _ tp is_trusted) := print_cnst nm tp is_trusted
| (declaration.ax nm _ tp) := print_ax nm tp
meta instance : has_to_tactic_format declaration :=
⟨to_tactic_format⟩
end declaration
meta instance pexpr.decidable_eq {elab} : decidable_eq (expr elab) :=
unchecked_cast
expr.has_decidable_eq
|
fb39b0fcef9f9de372cf5f54f84665eb3b5f77ca | 624f6f2ae8b3b1adc5f8f67a365c51d5126be45a | /src/Init/Lean/Meta/AppBuilder.lean | cb78230245ec1513f5ec4eaad113d01b993fe8b4 | [
"Apache-2.0"
] | permissive | mhuisi/lean4 | 28d35a4febc2e251c7f05492e13f3b05d6f9b7af | dda44bc47f3e5d024508060dac2bcb59fd12e4c0 | refs/heads/master | 1,621,225,489,283 | 1,585,142,689,000 | 1,585,142,689,000 | 250,590,438 | 0 | 2 | Apache-2.0 | 1,602,443,220,000 | 1,585,327,814,000 | C | UTF-8 | Lean | false | false | 8,568 | 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.Lean.Util.Recognizers
import Init.Lean.Meta.SynthInstance
namespace Lean
namespace Meta
/-- Given `e` s.t. `inferType e` is definitionally equal to `expectedType`, return
term `@id expectedType e`. -/
def mkExpectedTypeHint (e : Expr) (expectedType : Expr) : MetaM Expr := do
u ← getLevel expectedType;
pure $ mkApp2 (mkConst `id [u]) expectedType e
def mkEq (a b : Expr) : MetaM Expr := do
aType ← inferType a;
u ← getLevel aType;
pure $ mkApp3 (mkConst `Eq [u]) aType a b
def mkHEq (a b : Expr) : MetaM Expr := do
aType ← inferType a;
bType ← inferType b;
u ← getLevel aType;
pure $ mkApp4 (mkConst `HEq [u]) aType a bType b
def mkEqRefl (a : Expr) : MetaM Expr := do
aType ← inferType a;
u ← getLevel aType;
pure $ mkApp2 (mkConst `Eq.refl [u]) aType a
def mkHEqRefl (a : Expr) : MetaM Expr := do
aType ← inferType a;
u ← getLevel aType;
pure $ mkApp2 (mkConst `HEq.refl [u]) aType a
private def infer (h : Expr) : MetaM Expr := do
hType ← inferType h;
whnfD hType
def mkEqSymm (h : Expr) : MetaM Expr :=
if h.isAppOf `Eq.refl then pure h
else do
hType ← infer h;
match hType.eq? with
| some (α, a, b) => do u ← getLevel α; pure $ mkApp4 (mkConst `Eq.symm [u]) α a b h
| none => throwEx $ Exception.appBuilder `Eq.symm "equality proof expected" #[h]
def mkEqTrans (h₁ h₂ : Expr) : MetaM Expr :=
if h₁.isAppOf `Eq.refl then pure h₂
else if h₂.isAppOf `Eq.refl then pure h₁
else do
hType₁ ← infer h₁;
hType₂ ← infer h₂;
match hType₁.eq?, hType₂.eq? with
| some (α, a, b), some (_, _, c) =>
do u ← getLevel α; pure $ mkApp6 (mkConst `Eq.trans [u]) α a b c h₁ h₂
| _, _ => throwEx $ Exception.appBuilder `Eq.trans "equality proof expected" #[h₁, h₂]
def mkHEqSymm (h : Expr) : MetaM Expr :=
if h.isAppOf `HEq.refl then pure h
else do
hType ← infer h;
match hType.heq? with
| some (α, a, β, b) => do u ← getLevel α; pure $ mkApp5 (mkConst `HEq.symm [u]) α β a b h
| none => throwEx $ Exception.appBuilder `HEq.symm "heterogeneous equality proof expected" #[h]
def mkHEqTrans (h₁ h₂ : Expr) : MetaM Expr :=
if h₁.isAppOf `HEq.refl then pure h₂
else if h₂.isAppOf `HEq.refl then pure h₁
else do
hType₁ ← infer h₁;
hType₂ ← infer h₂;
match hType₁.heq?, hType₂.heq? with
| some (α, a, β, b), some (_, _, γ, c) => do
u ← getLevel α; pure $ mkApp8 (mkConst `HEq.trans [u]) α β γ a b c h₁ h₂
| _, _ => throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h₁, h₂]
def mkEqOfHEq (h : Expr) : MetaM Expr := do
hType ← infer h;
match hType.heq? with
| some (α, a, β, b) => do
unlessM (isDefEq α β) $ throwEx $ Exception.appBuilder `eqOfHEq "heterogeneous equality types are not definitionally equal" #[α, β];
u ← getLevel α;
pure $ mkApp4 (mkConst `eqOfHEq [u]) α a b h
| _ =>
throwEx $ Exception.appBuilder `HEq.trans "heterogeneous equality proof expected" #[h]
def mkCongrArg (f h : Expr) : MetaM Expr := do
hType ← infer h;
fType ← infer f;
match fType.arrow?, hType.eq? with
| some (α, β), some (_, a, b) => do
u ← getLevel α; v ← getLevel β; pure $ mkApp6 (mkConst `congrArg [u, v]) α β a b f h
| none, _ => throwEx $ Exception.appBuilder `congrArg "non-dependent function expected" #[f, h]
| _, none => throwEx $ Exception.appBuilder `congrArg "equality proof expected" #[f, h]
def mkCongrFun (h a : Expr) : MetaM Expr := do
hType ← infer h;
match hType.eq? with
| some (ρ, f, g) => do
ρ ← whnfD ρ;
match ρ with
| Expr.forallE n α β _ => do
let β' := Lean.mkLambda n BinderInfo.default α β;
u ← getLevel α;
v ← getLevel (mkApp β' a);
pure $ mkApp6 (mkConst `congrFun [u, v]) α β' f g h a
| _ => throwEx $ Exception.appBuilder `congrFun "equality proof between functions expected" #[h, a]
| _ => throwEx $ Exception.appBuilder `congrFun "equality proof expected" #[h, a]
def mkCongr (h₁ h₂ : Expr) : MetaM Expr := do
hType₁ ← infer h₁;
hType₂ ← infer h₂;
match hType₁.eq?, hType₂.eq? with
| some (ρ, f, g), some (α, a, b) => do
ρ ← whnfD ρ;
match ρ.arrow? with
| some (_, β) => do
u ← getLevel α;
v ← getLevel β;
pure $ mkApp8 (mkConst `congr [u, v]) α β f g a b h₁ h₂
| _ => throwEx $ Exception.appBuilder `congr "non-dependent function expected" #[h₁, h₂]
| _, _ => throwEx $ Exception.appBuilder `congr "equality proof expected" #[h₁, h₂]
private def mkAppMFinal (f : Expr) (args : Array Expr) (instMVars : Array MVarId) : MetaM Expr := do
instMVars.forM $ fun mvarId => do {
mvarDecl ← getMVarDecl mvarId;
mvarVal ← synthInstance mvarDecl.type;
assignExprMVar mvarId mvarVal
};
result ← instantiateMVars (mkAppN f args);
whenM (hasAssignableMVar result) $ throwEx $ Exception.appBuilder `mkAppM "result contains metavariables" #[result];
pure result
private partial def mkAppMAux (f : Expr) (xs : Array Expr) : Nat → Array Expr → Nat → Array MVarId → Expr → MetaM Expr
| i, args, j, instMVars, Expr.forallE n d b c => do
let d := d.instantiateRevRange j args.size args;
match c.binderInfo with
| BinderInfo.implicit => do mvar ← mkFreshExprMVar d n; mkAppMAux i (args.push mvar) j instMVars b
| BinderInfo.instImplicit => do mvar ← mkFreshExprMVar d n MetavarKind.synthetic; mkAppMAux i (args.push mvar) j (instMVars.push mvar.mvarId!) b
| _ =>
if h : i < xs.size then do
let x := xs.get ⟨i, h⟩;
xType ← inferType x;
condM (isDefEq d xType)
(mkAppMAux (i+1) (args.push x) j instMVars b)
(throwEx $ Exception.appTypeMismatch (mkAppN f args) x)
else
mkAppMFinal f args instMVars
| i, args, j, instMVars, type => do
let type := type.instantiateRevRange j args.size args;
type ← whnfD type;
if type.isForall then
mkAppMAux i args args.size instMVars type
else if i == xs.size then
mkAppMFinal f args instMVars
else
throwEx $ Exception.appBuilder `mkAppM "too many explicit arguments provided" (#[f] ++ xs)
def mkAppM (constName : Name) (xs : Array Expr) : MetaM Expr :=
traceCtx `Meta.appBuilder $ withNewMCtxDepth $ do
cinfo ← getConstInfo constName;
us ← cinfo.lparams.mapM $ fun _ => mkFreshLevelMVar;
let f := mkConst constName us;
let fType := cinfo.instantiateTypeLevelParams us;
mkAppMAux f xs 0 #[] 0 #[] fType
def mkEqNDRec (motive h1 h2 : Expr) : MetaM Expr :=
if h2.isAppOf `Eq.refl then pure h1
else do
h2Type ← infer h2;
match h2Type.eq? with
| none => throwEx $ Exception.appBuilder `Eq.ndrec "equality proof expected" #[h2]
| some (α, a, b) => do
u2 ← getLevel α;
motiveType ← infer motive;
match motiveType with
| Expr.forallE _ _ (Expr.sort u1 _) _ =>
pure $ mkAppN (mkConst `Eq.ndrec [u1, u2]) #[α, a, motive, h1, b, h2]
| _ => throwEx $ Exception.appBuilder `Eq.ndrec "invalid motive" #[motive]
def mkEqRec (motive h1 h2 : Expr) : MetaM Expr :=
if h2.isAppOf `Eq.refl then pure h1
else do
h2Type ← infer h2;
match h2Type.eq? with
| none => throwEx $ Exception.appBuilder `Eq.rec "equality proof expected" #[h2]
| some (α, a, b) => do
u2 ← getLevel α;
motiveType ← infer motive;
match motiveType with
| Expr.forallE _ _ (Expr.forallE _ _ (Expr.sort u1 _) _) _ =>
pure $ mkAppN (mkConst `Eq.rec [u1, u2]) #[α, a, motive, h1, b, h2]
| _ => throwEx $ Exception.appBuilder `Eq.rec "invalid motive" #[motive]
def mkEqMP (eqProof pr : Expr) : MetaM Expr :=
mkAppM `Eq.mp #[eqProof, pr]
def mkEqMPR (eqProof pr : Expr) : MetaM Expr :=
mkAppM `Eq.mpr #[eqProof, pr]
def mkNoConfusion (target : Expr) (h : Expr) : MetaM Expr := do
type ← inferType h;
type ← whnf type;
match type.eq? with
| none => throwEx $ Exception.appBuilder `noConfusion "equality expected" #[h]
| some (α, a, b) => do
α ← whnf α;
env ← getEnv;
let f := α.getAppFn;
matchConst env f (fun _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α]) $ fun cinfo us =>
match cinfo with
| ConstantInfo.inductInfo v => do
u ← getLevel target;
pure $ mkAppN (mkConst (mkNameStr v.name "noConfusion") (u :: us)) (α.getAppArgs ++ #[target, a, b, h])
| _ => throwEx $ Exception.appBuilder `noConfusion "inductive type expected" #[α]
end Meta
end Lean
|
4321f214603fdfde439cde7bf90d4df9ed9b98c3 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/univs.lean | 40abfdb08fded8c2a9d2934906810f7aad028e1f | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 215 | lean | import algebra.category.basic
set_option pp.universes true
section
universes l₁ l₂ l₃ l₄
parameter C : Category.{l₁ l₂}
parameter f : Category.{l₁ l₂} → Category.{l₃ l₄}
check f C
end
|
cd0cccef9783a92fbc77967be363516c6ce2cf80 | 367134ba5a65885e863bdc4507601606690974c1 | /src/topology/algebra/uniform_ring.lean | e8d3524daabb9218471a4108586a664f597301f0 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 7,690 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
Theory of topological rings with uniform structure.
-/
import topology.algebra.group_completion
import topology.algebra.ring
open classical set filter topological_space add_comm_group
open_locale classical
noncomputable theory
namespace uniform_space.completion
open dense_inducing uniform_space function
variables (α : Type*) [ring α] [uniform_space α]
instance : has_one (completion α) := ⟨(1:α)⟩
instance : has_mul (completion α) :=
⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩
@[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl
variables {α} [topological_ring α]
@[norm_cast]
lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b :=
((dense_inducing_coe.prod dense_inducing_coe).extend_eq
((continuous_coe α).comp (@continuous_mul α _ _ _)) (a, b)).symm
variables [uniform_add_group α]
lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) :=
begin
haveI : is_Z_bilin ((coe ∘ uncurry (*)) : α × α → completion α) :=
{ add_left := begin
introv,
change coe ((a + a')*b) = coe (a*b) + coe (a'*b),
rw_mod_cast add_mul
end,
add_right := begin
introv,
change coe (a*(b + b')) = coe (a*b) + coe (a*b'),
rw_mod_cast mul_add
end },
have : continuous ((coe ∘ uncurry (*)) : α × α → completion α),
from (continuous_coe α).comp continuous_mul,
convert dense_inducing_coe.extend_Z_bilin dense_inducing_coe this,
simp only [(*), curry, prod.mk.eta]
end
lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α}
(hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) :=
continuous_mul.comp (hf.prod_mk hg : _)
instance : ring (completion α) :=
{ one_mul := assume a, completion.induction_on a
(is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id)
(assume a, by rw [← coe_one, ← coe_mul, one_mul]),
mul_one := assume a, completion.induction_on a
(is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id)
(assume a, by rw [← coe_one, ← coe_mul, mul_one]),
mul_assoc := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd))
(continuous.mul continuous_fst
(continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]),
left_distrib := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul continuous_fst (continuous.add
(continuous_fst.comp continuous_snd)
(continuous_snd.comp continuous_snd)))
(continuous.add
(continuous.mul continuous_fst (continuous_fst.comp continuous_snd))
(continuous.mul continuous_fst (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]),
right_distrib := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul (continuous.add continuous_fst
(continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd))
(continuous.add
(continuous.mul continuous_fst (continuous_snd.comp continuous_snd))
(continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]),
..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α }
/-- The map from a uniform ring to its completion, as a ring homomorphism. -/
def coe_ring_hom : α →+* completion α :=
⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩
universes u
variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β]
(f : α →+* β) (hf : continuous f)
/-- The completion extension as a ring morphism. -/
def extension_hom [complete_space β] [separated_space β] :
completion α →+* β :=
have hf : uniform_continuous f, from uniform_continuous_of_continuous hf,
{ to_fun := completion.extension f,
map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero],
map_add' := assume a b, completion.induction_on₂ a b
(is_closed_eq
(continuous_extension.comp continuous_add)
((continuous_extension.comp continuous_fst).add
(continuous_extension.comp continuous_snd)))
(assume a b,
by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf,
f.map_add]),
map_one' := by rw [← coe_one, extension_coe hf, f.map_one],
map_mul' := assume a b, completion.induction_on₂ a b
(is_closed_eq
(continuous_extension.comp continuous_mul)
((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd)))
(assume a b,
by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) }
instance top_ring_compl : topological_ring (completion α) :=
{ continuous_add := continuous_add,
continuous_mul := continuous_mul,
continuous_neg := continuous_neg }
/-- The completion map as a ring morphism. -/
def map_ring_hom : completion α →+* completion β :=
extension_hom (coe_ring_hom.comp f) ((continuous_coe β).comp hf)
variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R]
instance : comm_ring (completion R) :=
{ mul_comm := assume a b, completion.induction_on₂ a b
(is_closed_eq (continuous_fst.mul continuous_snd)
(continuous_snd.mul continuous_fst))
(assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]),
..completion.ring }
end uniform_space.completion
namespace uniform_space
variables {α : Type*}
lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) :=
setoid.ext $ assume x y, group_separation_rel x y
lemma ring_sep_quot (α) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
quotient (separation_setoid α) = (⊥ : ideal α).closure.quotient :=
by rw [@ring_sep_rel α r]; refl
/-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly
continuous, get an equivalence between the separated quotient of `α` and the quotient ring
corresponding to the closure of zero. -/
def sep_quot_equiv_ring_quot (α)
[r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
quotient (separation_setoid α) ≃ (⊥ : ideal α).closure.quotient :=
quotient.congr_right $ assume x y, group_separation_rel x y
/- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/
instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
comm_ring (quotient (separation_setoid α)) :=
by rw ring_sep_quot α; apply_instance
instance topological_ring
[comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
topological_ring (quotient (separation_setoid α)) :=
begin
convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel},
simp [uniform_space.comm_ring]
end
end uniform_space
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.