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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a03abbaf91e3463a56097434641941fd986e7e1e | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/analysis/convex/function.lean | 662027edb76e4599a70f52046f75892fa32aaa25 | [
"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 | 37,430 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, François Dupuis
-/
import analysis.convex.basic
import order.order_dual
import tactic.field_simp
import tactic.linarith
import tactic.ring
/-!
# Convex and concave functions
This file defines convex and concave functions in vector spaces and proves the finite Jensen
inequality. The integral version can be found in `analysis.convex.integral`.
A function `f : E → β` is `convex_on` a set `s` if `s` is itself a convex set, and for any two
points `x y ∈ s`, the segment joining `(x, f x)` to `(y, f y)` is above the graph of `f`.
Equivalently, `convex_on 𝕜 f s` means that the epigraph `{p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2}` is
a convex set.
## Main declarations
* `convex_on 𝕜 s f`: The function `f` is convex on `s` with scalars `𝕜`.
* `concave_on 𝕜 s f`: The function `f` is concave on `s` with scalars `𝕜`.
* `strict_convex_on 𝕜 s f`: The function `f` is strictly convex on `s` with scalars `𝕜`.
* `strict_concave_on 𝕜 s f`: The function `f` is strictly concave on `s` with scalars `𝕜`.
-/
open finset linear_map set
open_locale big_operators classical convex pointwise
variables {𝕜 E F β ι : Type*}
section ordered_semiring
variables [ordered_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section has_scalar
variables (𝕜) [has_scalar 𝕜 E] [has_scalar 𝕜 β] (s : set E) (f : E → β)
/-- Convexity of functions -/
def convex_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y
/-- Concavity of functions -/
def concave_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)
/-- Strict convexity of functions -/
def strict_convex_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) < a • f x + b • f y
/-- Strict concavity of functions -/
def strict_concave_on : Prop :=
convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y < f (a • x + b • y)
variables {𝕜 s f}
open order_dual (to_dual of_dual)
lemma convex_on.dual (hf : convex_on 𝕜 s f) : concave_on 𝕜 s (to_dual ∘ f) := hf
lemma concave_on.dual (hf : concave_on 𝕜 s f) : convex_on 𝕜 s (to_dual ∘ f) := hf
lemma strict_convex_on.dual (hf : strict_convex_on 𝕜 s f) : strict_concave_on 𝕜 s (to_dual ∘ f) :=
hf
lemma strict_concave_on.dual (hf : strict_concave_on 𝕜 s f) : strict_convex_on 𝕜 s (to_dual ∘ f) :=
hf
lemma convex_on_id {s : set β} (hs : convex 𝕜 s) : convex_on 𝕜 s id := ⟨hs, by { intros, refl }⟩
lemma concave_on_id {s : set β} (hs : convex 𝕜 s) : concave_on 𝕜 s id := ⟨hs, by { intros, refl }⟩
lemma convex_on.subset {t : set E} (hf : convex_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) :
convex_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
lemma concave_on.subset {t : set E} (hf : concave_on 𝕜 t f) (hst : s ⊆ t) (hs : convex 𝕜 s) :
concave_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
lemma strict_convex_on.subset {t : set E} (hf : strict_convex_on 𝕜 t f) (hst : s ⊆ t)
(hs : convex 𝕜 s) :
strict_convex_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
lemma strict_concave_on.subset {t : set E} (hf : strict_concave_on 𝕜 t f) (hst : s ⊆ t)
(hs : convex 𝕜 s) :
strict_concave_on 𝕜 s f :=
⟨hs, λ x y hx hy, hf.2 (hst hx) (hst hy)⟩
end has_scalar
section distrib_mul_action
variables [has_scalar 𝕜 E] [distrib_mul_action 𝕜 β] {s : set E} {f g : E → β}
lemma convex_on.add (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) :
convex_on 𝕜 s (f + g) :=
⟨hf.1, λ x y hx hy a b ha hb hab,
calc
f (a • x + b • y) + g (a • x + b • y) ≤ (a • f x + b • f y) + (a • g x + b • g y)
: add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
... = a • (f x + g x) + b • (f y + g y) : by rw [smul_add, smul_add, add_add_add_comm]⟩
lemma concave_on.add (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) :
concave_on 𝕜 s (f + g) :=
hf.dual.add hg
end distrib_mul_action
section module
variables [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β}
lemma convex_on_const (c : β) (hs : convex 𝕜 s) : convex_on 𝕜 s (λ x:E, c) :=
⟨hs, λ x y _ _ a b _ _ hab, (convex.combo_self hab c).ge⟩
lemma concave_on_const (c : β) (hs : convex 𝕜 s) : concave_on 𝕜 s (λ x:E, c) :=
@convex_on_const _ _ (order_dual β) _ _ _ _ _ _ c hs
end module
section ordered_smul
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.convex_le (hf : convex_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha hb hab,
calc
f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha hb hab
... ≤ a • r + b • r : add_le_add (smul_le_smul_of_nonneg hx.2 ha)
(smul_le_smul_of_nonneg hy.2 hb)
... = r : convex.combo_self hab r⟩
lemma concave_on.convex_ge (hf : concave_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
hf.dual.convex_le r
lemma convex_on.convex_epigraph (hf : convex_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
begin
rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab,
refine ⟨hf.1 hx hy ha hb hab, _⟩,
calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • r + b • t : add_le_add (smul_le_smul_of_nonneg hr ha)
(smul_le_smul_of_nonneg ht hb)
end
lemma concave_on.convex_hypograph (hf : concave_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
hf.dual.convex_epigraph
lemma convex_on_iff_convex_epigraph :
convex_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 ≤ p.2} :=
⟨convex_on.convex_epigraph, λ h,
⟨λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).1,
λ x y hx hy a b ha hb hab, (@h (x, f x) (y, f y) ⟨hx, le_rfl⟩ ⟨hy, le_rfl⟩ a b ha hb hab).2⟩⟩
lemma concave_on_iff_convex_hypograph :
concave_on 𝕜 s f ↔ convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 ≤ f p.1} :=
@convex_on_iff_convex_epigraph 𝕜 E (order_dual β) _ _ _ _ _ _ _ f
end ordered_smul
section module
variables [module 𝕜 E] [has_scalar 𝕜 β] {s : set E} {f : E → β} {c : E}
/-- Right translation preserves convexity. -/
lemma convex_on.translate_right (hf : convex_on 𝕜 s f) :
convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
⟨hf.1.translate_preimage_right _, λ x y hx hy a b ha hb hab,
calc
f (c + (a • x + b • y)) = f (a • (c + x) + b • (c + y))
: by rw [smul_add, smul_add, add_add_add_comm, convex.combo_self hab]
... ≤ a • f (c + x) + b • f (c + y) : hf.2 hx hy ha hb hab⟩
/-- Right translation preserves concavity. -/
lemma concave_on.translate_right (hf : concave_on 𝕜 s f) :
concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
hf.dual.translate_right
/-- Left translation preserves convexity. -/
lemma convex_on.translate_left (hf : convex_on 𝕜 s f) :
convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
by simpa only [add_comm] using hf.translate_right
/-- Left translation preserves strict concavity. -/
lemma concave_on.translate_left (hf : concave_on 𝕜 s f) :
concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
hf.dual.translate_left
end module
section module
variables [module 𝕜 E] [module 𝕜 β]
lemma convex_on_iff_forall_pos {s : set E} {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ f (a • x + b • y) ≤ a • f x + b • f y :=
begin
refine and_congr_right' ⟨λ h x y hx hy a b ha hb hab, h hx hy ha.le hb.le hab,
λ h x y hx hy a b ha hb hab, _⟩,
obtain rfl | ha' := ha.eq_or_lt,
{ rw [zero_add] at hab, subst b, simp_rw [zero_smul, zero_add, one_smul] },
obtain rfl | hb' := hb.eq_or_lt,
{ rw [add_zero] at hab, subst a, simp_rw [zero_smul, add_zero, one_smul] },
exact h hx hy ha' hb' hab,
end
lemma concave_on_iff_forall_pos {s : set E} {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • f x + b • f y ≤ f (a • x + b • y) :=
@convex_on_iff_forall_pos 𝕜 E (order_dual β) _ _ _ _ _ _ _
lemma convex_on_iff_pairwise_on_pos {s : set E} {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧
s.pairwise_on (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ f (a • x + b • y) ≤ a • f x + b • f y) :=
begin
rw convex_on_iff_forall_pos,
refine and_congr_right' ⟨λ h x hx y hy _ a b ha hb hab, h hx hy ha hb hab,
λ h x y hx hy a b ha hb hab, _⟩,
obtain rfl | hxy := eq_or_ne x y,
{ rw [convex.combo_self hab, convex.combo_self hab] },
exact h x hx y hy hxy ha hb hab,
end
lemma concave_on_iff_pairwise_on_pos {s : set E} {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧
s.pairwise_on (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • f x + b • f y ≤ f (a • x + b • y)) :=
@convex_on_iff_pairwise_on_pos 𝕜 E (order_dual β) _ _ _ _ _ _ _
/-- A linear map is convex. -/
lemma linear_map.convex_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : convex_on 𝕜 s f :=
⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩
/-- A linear map is concave. -/
lemma linear_map.concave_on (f : E →ₗ[𝕜] β) {s : set E} (hs : convex 𝕜 s) : concave_on 𝕜 s f :=
⟨hs, λ _ _ _ _ _ _ _ _ _, by rw [f.map_add, f.map_smul, f.map_smul]⟩
lemma strict_convex_on.convex_on {s : set E} {f : E → β} (hf : strict_convex_on 𝕜 s f) :
convex_on 𝕜 s f :=
⟨hf.1, λ x y hx hy a b ha hb hab, begin
obtain rfl | hxy := eq_or_ne x y,
{ rw [convex.combo_self hab, convex.combo_self hab] },
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rw [hab, zero_smul, zero_smul, one_smul, one_smul, zero_add, zero_add] },
obtain rfl | hb' := hb.eq_or_lt,
{ rw add_zero at hab,
rw [hab, zero_smul, zero_smul, one_smul, one_smul, add_zero, add_zero] },
exact (hf.2 hx hy hxy ha' hb' hab).le,
end⟩
lemma strict_concave_on.concave_on {s : set E} {f : E → β} (hf : strict_concave_on 𝕜 s f) :
concave_on 𝕜 s f :=
hf.dual.convex_on
section ordered_smul
variables [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma strict_convex_on.convex_lt (hf : strict_convex_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | f x < r} :=
convex_iff_pairwise_on_pos.2 $ λ x hx y hy hxy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha.le hb.le hab,
calc
f (a • x + b • y) < a • f x + b • f y : hf.2 hx.1 hy.1 hxy ha hb hab
... ≤ a • r + b • r : add_le_add (smul_lt_smul_of_pos hx.2 ha).le
(smul_lt_smul_of_pos hy.2 hb).le
... = r : convex.combo_self hab r⟩
lemma strict_concave_on.convex_gt (hf : strict_concave_on 𝕜 s f) (r : β) :
convex 𝕜 {x ∈ s | r < f x} :=
hf.dual.convex_lt r
end ordered_smul
section linear_order
variables [linear_order E] {s : set E} {f : E → β}
/-- For a function on a convex set in a linearly ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is convex, it suffices to
verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` only for `x < y` and positive `a`,
`b`. The main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order.
-/
lemma linear_order.convex_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) ≤ a • f x + b • f y) : convex_on 𝕜 s f :=
begin
refine convex_on_iff_pairwise_on_pos.2 ⟨hs, λ x hx y hy hxy a b ha hb hab, _⟩,
wlog h : x ≤ y using [x y a b, y x b a],
{ exact le_total _ _ },
exact hf hx hy (h.lt_of_ne hxy) ha hb hab,
end
/-- For a function on a convex set in a linearly ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is concave it suffices to
verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` for `x < y` and positive `a`, `b`. The
main use case is `E = ℝ` however one can apply it, e.g., to `ℝ^n` with lexicographic order. -/
lemma linear_order.concave_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y ≤ f (a • x + b • y)) : concave_on 𝕜 s f :=
@linear_order.convex_on_of_lt _ _ (order_dual β) _ _ _ _ _ _ s f hs hf
/-- For a function on a convex set in a linearly ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is convex, it suffices to
verify the inequality `f (a • x + b • y) ≤ a • f x + b • f y` for `x < y` and positive `a`, `b`. The
main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order. -/
lemma linear_order.strict_convex_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
f (a • x + b • y) < a • f x + b • f y) : strict_convex_on 𝕜 s f :=
begin
refine ⟨hs, λ x y hx hy hxy a b ha hb hab, _⟩,
wlog h : x ≤ y using [x y a b, y x b a],
{ exact le_total _ _ },
exact hf hx hy (h.lt_of_ne hxy) ha hb hab,
end
/-- For a function on a convex set in a linearly ordered space (where the order and the algebraic
structures aren't necessarily compatible), in order to prove that it is concave it suffices to
verify the inequality `a • f x + b • f y ≤ f (a • x + b • y)` for `x < y` and positive `a`, `b`. The
main use case is `E = 𝕜` however one can apply it, e.g., to `𝕜^n` with lexicographic order. -/
lemma linear_order.strict_concave_on_of_lt (hs : convex 𝕜 s)
(hf : ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x < y → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 →
a • f x + b • f y < f (a • x + b • y)) : strict_concave_on 𝕜 s f :=
@linear_order.strict_convex_on_of_lt _ _ (order_dual β) _ _ _ _ _ _ _ _ hs hf
end linear_order
end module
section module
variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β]
/-- If `g` is convex on `s`, so is `(f ∘ g)` on `f ⁻¹' s` for a linear `f`. -/
lemma convex_on.comp_linear_map {f : F → β} {s : set F} (hf : convex_on 𝕜 s f) (g : E →ₗ[𝕜] F) :
convex_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
⟨hf.1.linear_preimage _, λ x y hx hy a b ha hb hab,
calc
f (g (a • x + b • y)) = f (a • (g x) + b • (g y)) : by rw [g.map_add, g.map_smul, g.map_smul]
... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩
/-- If `g` is concave on `s`, so is `(g ∘ f)` on `f ⁻¹' s` for a linear `f`. -/
lemma concave_on.comp_linear_map {f : F → β} {s : set F} (hf : concave_on 𝕜 s f) (g : E →ₗ[𝕜] F) :
concave_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
hf.dual.comp_linear_map g
end module
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β]
section distrib_mul_action
variables [has_scalar 𝕜 E] [distrib_mul_action 𝕜 β] {s : set E} {f g : E → β}
lemma strict_convex_on.add (hf : strict_convex_on 𝕜 s f) (hg : strict_convex_on 𝕜 s g) :
strict_convex_on 𝕜 s (f + g) :=
⟨hf.1, λ x y hx hy hxy a b ha hb hab,
calc
f (a • x + b • y) + g (a • x + b • y) < (a • f x + b • f y) + (a • g x + b • g y)
: add_lt_add (hf.2 hx hy hxy ha hb hab) (hg.2 hx hy hxy ha hb hab)
... = a • (f x + g x) + b • (f y + g y) : by rw [smul_add, smul_add, add_add_add_comm]⟩
lemma strict_concave_on.add (hf : strict_concave_on 𝕜 s f) (hg : strict_concave_on 𝕜 s g) :
strict_concave_on 𝕜 s (f + g) :=
hf.dual.add hg
end distrib_mul_action
section module
variables [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.convex_lt (hf : convex_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | f x < r} :=
convex_iff_forall_pos.2 $ λ x y hx hy a b ha hb hab, ⟨hf.1 hx.1 hy.1 ha.le hb.le hab,
calc
f (a • x + b • y)
≤ a • f x + b • f y : hf.2 hx.1 hy.1 ha.le hb.le hab
... < a • r + b • r : add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx.2 ha)
(smul_le_smul_of_nonneg hy.2.le hb.le)
... = r : convex.combo_self hab _⟩
lemma concave_on.convex_gt (hf : concave_on 𝕜 s f) (r : β) : convex 𝕜 {x ∈ s | r < f x} :=
hf.dual.convex_lt r
lemma convex_on.convex_strict_epigraph (hf : convex_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ f p.1 < p.2} :=
begin
rw convex_iff_forall_pos,
rintro ⟨x, r⟩ ⟨y, t⟩ ⟨hx, hr⟩ ⟨hy, ht⟩ a b ha hb hab,
refine ⟨hf.1 hx hy ha.le hb.le hab, _⟩,
calc f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha.le hb.le hab
... < a • r + b • t : add_lt_add (smul_lt_smul_of_pos hr ha)
(smul_lt_smul_of_pos ht hb)
end
lemma concave_on.convex_strict_hypograph (hf : concave_on 𝕜 s f) :
convex 𝕜 {p : E × β | p.1 ∈ s ∧ p.2 < f p.1} :=
hf.dual.convex_strict_epigraph
end module
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid β] [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β]
{s : set E} {f g : E → β}
/-- The pointwise maximum of convex functions is convex. -/
lemma convex_on.sup (hf : convex_on 𝕜 s f) (hg : convex_on 𝕜 s g) :
convex_on 𝕜 s (f ⊔ g) :=
begin
refine ⟨hf.left, λ x y hx hy a b ha hb hab, sup_le _ _⟩,
{ calc f (a • x + b • y) ≤ a • f x + b • f y : hf.right hx hy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_left ha)
(smul_le_smul_of_nonneg le_sup_left hb) },
{ calc g (a • x + b • y) ≤ a • g x + b • g y : hg.right hx hy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_right ha)
(smul_le_smul_of_nonneg le_sup_right hb) }
end
/-- The pointwise minimum of concave functions is concave. -/
lemma concave_on.inf (hf : concave_on 𝕜 s f) (hg : concave_on 𝕜 s g) :
concave_on 𝕜 s (f ⊓ g) :=
hf.dual.sup hg
/-- The pointwise maximum of strictly convex functions is strictly convex. -/
lemma strict_convex_on.sup (hf : strict_convex_on 𝕜 s f) (hg : strict_convex_on 𝕜 s g) :
strict_convex_on 𝕜 s (f ⊔ g) :=
⟨hf.left, λ x y hx hy hxy a b ha hb hab, max_lt
(calc f (a • x + b • y) < a • f x + b • f y : hf.2 hx hy hxy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_left ha.le)
(smul_le_smul_of_nonneg le_sup_left hb.le))
(calc g (a • x + b • y) < a • g x + b • g y : hg.2 hx hy hxy ha hb hab
... ≤ a • (f x ⊔ g x) + b • (f y ⊔ g y) : add_le_add
(smul_le_smul_of_nonneg le_sup_right ha.le)
(smul_le_smul_of_nonneg le_sup_right hb.le))⟩
/-- The pointwise minimum of strictly concave functions is strictly concave. -/
lemma strict_concave_on.inf (hf : strict_concave_on 𝕜 s f) (hg : strict_concave_on 𝕜 s g) :
strict_concave_on 𝕜 s (f ⊓ g) :=
hf.dual.sup hg
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
f (a • x + b • y) ≤ max (f x) (f y) :=
calc
f (a • x + b • y) ≤ a • f x + b • f y : hf.2 hx hy ha hb hab
... ≤ a • max (f x) (f y) + b • max (f x) (f y) :
add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha)
(smul_le_smul_of_nonneg (le_max_right _ _) hb)
... = max (f x) (f y) : convex.combo_self hab _
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.ge_on_segment' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min (f x) (f y) ≤ f (a • x + b • y) :=
hf.dual.le_on_segment' hx hy ha hb hab
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) :
f z ≤ max (f x) (f y) :=
let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.le_on_segment' hx hy ha hb hab
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.ge_on_segment (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s) (hy : y ∈ s)
(hz : z ∈ [x -[𝕜] y]) :
min (f x) (f y) ≤ f z :=
hf.dual.le_on_segment hx hy hz
/-- A strictly convex function on an open segment is strictly upper-bounded by the max of its
endpoints. -/
lemma strict_convex_on.lt_on_open_segment' (hf : strict_convex_on 𝕜 s f) {x y : E} (hx : x ∈ s)
(hy : y ∈ s) (hxy : x ≠ y) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) :
f (a • x + b • y) < max (f x) (f y) :=
calc
f (a • x + b • y) < a • f x + b • f y : hf.2 hx hy hxy ha hb hab
... ≤ a • max (f x) (f y) + b • max (f x) (f y) :
add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha.le)
(smul_le_smul_of_nonneg (le_max_right _ _) hb.le)
... = max (f x) (f y) : convex.combo_self hab _
/-- A strictly concave function on an open segment is strictly lower-bounded by the min of its
endpoints. -/
lemma strict_concave_on.lt_on_open_segment' (hf : strict_concave_on 𝕜 s f) {x y : E} (hx : x ∈ s)
(hy : y ∈ s) (hxy : x ≠ y) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1) :
min (f x) (f y) < f (a • x + b • y) :=
hf.dual.lt_on_open_segment' hx hy hxy ha hb hab
/-- A strictly convex function on an open segment is strictly upper-bounded by the max of its
endpoints. -/
lemma strict_convex_on.lt_on_open_segment (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hxy : x ≠ y) (hz : z ∈ open_segment 𝕜 x y) :
f z < max (f x) (f y) :=
let ⟨a, b, ha, hb, hab, hz⟩ := hz in hz ▸ hf.lt_on_open_segment' hx hy hxy ha hb hab
/-- A strictly concave function on an open segment is strictly lower-bounded by the min of its
endpoints. -/
lemma strict_concave_on.lt_on_open_segment (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hxy : x ≠ y) (hz : z ∈ open_segment 𝕜 x y) :
min (f x) (f y) < f z :=
hf.dual.lt_on_open_segment hx hy hxy hz
end linear_ordered_add_comm_monoid
section linear_ordered_cancel_add_comm_monoid
variables [linear_ordered_cancel_add_comm_monoid β]
section ordered_smul
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β}
lemma convex_on.le_left_of_right_le' (hf : convex_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f y ≤ f (a • x + b • y)) :
f (a • x + b • y) ≤ f x :=
le_of_not_lt $ λ h, lt_irrefl (f (a • x + b • y)) $
calc
f (a • x + b • y)
≤ a • f x + b • f y : hf.2 hx hy ha.le hb hab
... < a • f (a • x + b • y) + b • f (a • x + b • y)
: add_lt_add_of_lt_of_le (smul_lt_smul_of_pos h ha) (smul_le_smul_of_nonneg hfy hb)
... = f (a • x + b • y) : convex.combo_self hab _
lemma concave_on.left_le_of_le_right' (hf : concave_on 𝕜 s f) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) (hfy : f (a • x + b • y) ≤ f y) :
f x ≤ f (a • x + b • y) :=
hf.dual.le_left_of_right_le' hx hy ha hb hab hfy
lemma convex_on.le_right_of_left_le' (hf : convex_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f x ≤ f (a • x + b • y)) :
f (a • x + b • y) ≤ f y :=
begin
rw add_comm at ⊢ hab hfx,
exact hf.le_left_of_right_le' hy hx hb ha hab hfx,
end
lemma concave_on.le_right_of_left_le' (hf : concave_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f (a • x + b • y) ≤ f x) :
f y ≤ f (a • x + b • y) :=
hf.dual.le_right_of_left_le' hx hy ha hb hab hfx
lemma convex_on.le_left_of_right_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f y ≤ f z) :
f z ≤ f x :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.le_left_of_right_le' hx hy ha hb.le hab hyz,
end
lemma concave_on.left_le_of_le_right (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f z ≤ f y) :
f x ≤ f z :=
hf.dual.le_left_of_right_le hx hy hz hyz
lemma convex_on.le_right_of_left_le (hf : convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f x ≤ f z) :
f z ≤ f y :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.le_right_of_left_le' hx hy ha.le hb hab hxz,
end
lemma concave_on.le_right_of_left_le (hf : concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f z ≤ f x) :
f y ≤ f z :=
hf.dual.le_right_of_left_le hx hy hz hxz
end ordered_smul
section module
variables [module 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f g : E → β}
/- The following lemmas don't require `module 𝕜 E` if you add the hypothesis `x ≠ y`. At the time of
the writing, we decided the resulting lemmas wouldn't be useful. Feel free to reintroduce them. -/
lemma strict_convex_on.lt_left_of_right_lt' (hf : strict_convex_on 𝕜 s f) {x y : E} (hx : x ∈ s)
(hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1)
(hfy : f y < f (a • x + b • y)) :
f (a • x + b • y) < f x :=
not_le.1 $ λ h, lt_irrefl (f (a • x + b • y)) $
calc
f (a • x + b • y)
< a • f x + b • f y : hf.2 hx hy begin
rintro rfl,
rw convex.combo_self hab at hfy,
exact lt_irrefl _ hfy,
end ha hb hab
... < a • f (a • x + b • y) + b • f (a • x + b • y)
: add_lt_add_of_le_of_lt (smul_le_smul_of_nonneg h ha.le) (smul_lt_smul_of_pos hfy hb)
... = f (a • x + b • y) : convex.combo_self hab _
lemma strict_concave_on.left_lt_of_lt_right' (hf : strict_concave_on 𝕜 s f) {x y : E} (hx : x ∈ s)
(hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1)
(hfy : f (a • x + b • y) < f y) :
f x < f (a • x + b • y) :=
hf.dual.lt_left_of_right_lt' hx hy ha hb hab hfy
lemma strict_convex_on.lt_right_of_left_lt' (hf : strict_convex_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f x < f (a • x + b • y)) :
f (a • x + b • y) < f y :=
begin
rw add_comm at ⊢ hab hfx,
exact hf.lt_left_of_right_lt' hy hx hb ha hab hfx,
end
lemma strict_concave_on.lt_right_of_left_lt' (hf : strict_concave_on 𝕜 s f) {x y : E} {a b : 𝕜}
(hx : x ∈ s) (hy : y ∈ s) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1)
(hfx : f (a • x + b • y) < f x) :
f y < f (a • x + b • y) :=
hf.dual.lt_right_of_left_lt' hx hy ha hb hab hfx
lemma strict_convex_on.lt_left_of_right_lt (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f y < f z) :
f z < f x :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.lt_left_of_right_lt' hx hy ha hb hab hyz,
end
lemma strict_concave_on.left_lt_of_lt_right (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hyz : f z < f y) :
f x < f z :=
hf.dual.lt_left_of_right_lt hx hy hz hyz
lemma strict_convex_on.lt_right_of_left_lt (hf : strict_convex_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f x < f z) :
f z < f y :=
begin
obtain ⟨a, b, ha, hb, hab, rfl⟩ := hz,
exact hf.lt_right_of_left_lt' hx hy ha hb hab hxz,
end
lemma strict_concave_on.lt_right_of_left_lt (hf : strict_concave_on 𝕜 s f) {x y z : E} (hx : x ∈ s)
(hy : y ∈ s) (hz : z ∈ open_segment 𝕜 x y) (hxz : f z < f x) :
f y < f z :=
hf.dual.lt_right_of_left_lt hx hy hz hxz
end module
end linear_ordered_cancel_add_comm_monoid
section ordered_add_comm_group
variables [ordered_add_comm_group β] [has_scalar 𝕜 E] [module 𝕜 β] {s : set E} {f : E → β}
/-- A function `-f` is convex iff `f` is concave. -/
@[simp] lemma neg_convex_on_iff : convex_on 𝕜 s (-f) ↔ concave_on 𝕜 s f :=
begin
split,
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩,
simp [neg_apply, neg_le, add_comm] at h,
exact h hx hy ha hb hab },
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy a b ha hb hab, _⟩,
rw ←neg_le_neg_iff,
simp_rw [neg_add, pi.neg_apply, smul_neg, neg_neg],
exact h hx hy ha hb hab }
end
/-- A function `-f` is concave iff `f` is convex. -/
@[simp] lemma neg_concave_on_iff : concave_on 𝕜 s (-f) ↔ convex_on 𝕜 s f:=
by rw [← neg_convex_on_iff, neg_neg f]
/-- A function `-f` is strictly convex iff `f` is strictly concave. -/
@[simp] lemma neg_strict_convex_on_iff : strict_convex_on 𝕜 s (-f) ↔ strict_concave_on 𝕜 s f :=
begin
split,
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy hxy a b ha hb hab, _⟩,
simp [neg_apply, neg_lt, add_comm] at h,
exact h hx hy hxy ha hb hab },
{ rintro ⟨hconv, h⟩,
refine ⟨hconv, λ x y hx hy hxy a b ha hb hab, _⟩,
rw ←neg_lt_neg_iff,
simp_rw [neg_add, pi.neg_apply, smul_neg, neg_neg],
exact h hx hy hxy ha hb hab }
end
/-- A function `-f` is strictly concave iff `f` is strictly convex. -/
@[simp] lemma neg_strict_concave_on_iff : strict_concave_on 𝕜 s (-f) ↔ strict_convex_on 𝕜 s f :=
by rw [← neg_strict_convex_on_iff, neg_neg f]
alias neg_convex_on_iff ↔ _ concave_on.neg
alias neg_concave_on_iff ↔ _ convex_on.neg
alias neg_strict_convex_on_iff ↔ _ strict_concave_on.neg
alias neg_strict_concave_on_iff ↔ _ strict_convex_on.neg
end ordered_add_comm_group
end add_comm_monoid
section add_cancel_comm_monoid
variables [add_cancel_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E] [has_scalar 𝕜 β]
{s : set E} {f : E → β} {c : E}
/-- Right translation preserves strict convexity. -/
lemma strict_convex_on.translate_right (hf : strict_convex_on 𝕜 s f) :
strict_convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
⟨hf.1.translate_preimage_right _, λ x y hx hy hxy a b ha hb hab,
calc
f (c + (a • x + b • y)) = f (a • (c + x) + b • (c + y))
: by rw [smul_add, smul_add, add_add_add_comm, convex.combo_self hab]
... < a • f (c + x) + b • f (c + y) : hf.2 hx hy ((add_right_injective c).ne hxy) ha hb hab⟩
/-- Right translation preserves strict concavity. -/
lemma strict_concave_on.translate_right (hf : strict_concave_on 𝕜 s f) :
strict_concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, c + z)) :=
hf.dual.translate_right
/-- Left translation preserves strict convexity. -/
lemma strict_convex_on.translate_left (hf : strict_convex_on 𝕜 s f) :
strict_convex_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
by simpa only [add_comm] using hf.translate_right
/-- Left translation preserves strict concavity. -/
lemma strict_concave_on.translate_left (hf : strict_concave_on 𝕜 s f) :
strict_concave_on 𝕜 ((λ z, c + z) ⁻¹' s) (f ∘ (λ z, z + c)) :=
by simpa only [add_comm] using hf.translate_right
end add_cancel_comm_monoid
end ordered_semiring
section ordered_comm_semiring
variables [ordered_comm_semiring 𝕜] [add_comm_monoid E]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section module
variables [has_scalar 𝕜 E] [module 𝕜 β] [ordered_smul 𝕜 β] {s : set E} {f : E → β}
lemma convex_on.smul {c : 𝕜} (hc : 0 ≤ c) (hf : convex_on 𝕜 s f) : convex_on 𝕜 s (λ x, c • f x) :=
⟨hf.1, λ x y hx hy a b ha hb hab,
calc
c • f (a • x + b • y) ≤ c • (a • f x + b • f y)
: smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc
... = a • (c • f x) + b • (c • f y)
: by rw [smul_add, smul_comm c, smul_comm c]; apply_instance⟩
lemma concave_on.smul {c : 𝕜} (hc : 0 ≤ c) (hf : concave_on 𝕜 s f) :
concave_on 𝕜 s (λ x, c • f x) :=
hf.dual.smul hc
end module
end ordered_add_comm_monoid
end ordered_comm_semiring
section ordered_ring
variables [linear_ordered_field 𝕜] [add_comm_group E] [add_comm_group F]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section module
variables [module 𝕜 E] [module 𝕜 F] [has_scalar 𝕜 β]
/-- If a function is convex on `s`, it remains convex when precomposed by an affine map. -/
lemma convex_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : convex_on 𝕜 s f) :
convex_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
⟨hf.1.affine_preimage _, λ x y hx hy a b ha hb hab,
calc
(f ∘ g) (a • x + b • y) = f (g (a • x + b • y)) : rfl
... = f (a • (g x) + b • (g y)) : by rw [convex.combo_affine_apply hab]
... ≤ a • f (g x) + b • f (g y) : hf.2 hx hy ha hb hab⟩
/-- If a function is concave on `s`, it remains concave when precomposed by an affine map. -/
lemma concave_on.comp_affine_map {f : F → β} (g : E →ᵃ[𝕜] F) {s : set F} (hf : concave_on 𝕜 s f) :
concave_on 𝕜 (g ⁻¹' s) (f ∘ g) :=
hf.dual.comp_affine_map g
end module
end ordered_add_comm_monoid
end ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜] [add_comm_monoid E]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β]
section has_scalar
variables [has_scalar 𝕜 E] [has_scalar 𝕜 β] {s : set E}
lemma convex_on_iff_div {f : E → β} :
convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → 0 < a + b
→ f ((a/(a+b)) • x + (b/(a+b)) • y) ≤ (a/(a+b)) • f x + (b/(a+b)) • f y :=
and_congr iff.rfl
⟨begin
intros h x y hx hy a b ha hb hab,
apply h hx hy (div_nonneg ha hab.le) (div_nonneg hb hab.le),
rw [←add_div, div_self hab.ne'],
end,
begin
intros h x y hx hy a b ha hb hab,
simpa [hab, zero_lt_one] using h hx hy ha hb,
end⟩
lemma concave_on_iff_div {f : E → β} :
concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b
→ 0 < a + b → (a/(a+b)) • f x + (b/(a+b)) • f y ≤ f ((a/(a+b)) • x + (b/(a+b)) • y) :=
@convex_on_iff_div _ _ (order_dual β) _ _ _ _ _ _ _
lemma strict_convex_on_iff_div {f : E → β} :
strict_convex_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a
→ 0 < b → f ((a/(a+b)) • x + (b/(a+b)) • y) < (a/(a+b)) • f x + (b/(a+b)) • f y :=
and_congr iff.rfl
⟨begin
intros h x y hx hy hxy a b ha hb,
have hab := add_pos ha hb,
apply h hx hy hxy (div_pos ha hab) (div_pos hb hab),
rw [←add_div, div_self hab.ne'],
end,
begin
intros h x y hx hy hxy a b ha hb hab,
simpa [hab, zero_lt_one] using h hx hy hxy ha hb,
end⟩
lemma strict_concave_on_iff_div {f : E → β} :
strict_concave_on 𝕜 s f ↔ convex 𝕜 s ∧ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → x ≠ y → ∀ ⦃a b : 𝕜⦄, 0 < a
→ 0 < b → (a/(a+b)) • f x + (b/(a+b)) • f y < f ((a/(a+b)) • x + (b/(a+b)) • y) :=
@strict_convex_on_iff_div _ _ (order_dual β) _ _ _ _ _ _ _
end has_scalar
end ordered_add_comm_monoid
end linear_ordered_field
|
bb842fea6ee2bd84b7370f2989440eb6b5303137 | 302b541ac2e998a523ae04da7673fd0932ded126 | /tests/playground/nat.lean | 56ca73c1945599425335cbee5dc79ada53d2f336 | [] | no_license | mattweingarten/lambdapure | 4aeff69e8e3b8e78ea3c0a2b9b61770ef5a689b1 | f920a4ad78e6b1e3651f30bf8445c9105dfa03a8 | refs/heads/master | 1,680,665,168,790 | 1,618,420,180,000 | 1,618,420,180,000 | 310,816,264 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 654 | lean | set_option trace.compiler.ir.init true
def add (x : Nat) (y : Nat ) :Nat := x + y
def sub (x : Nat) (y : Nat ) :Nat := x - y
def mul (x : Nat) (y : Nat ) :Nat := x * y
def div (x : Nat) (y : Nat ) :Nat := x / y
def lt (x : Nat) (y : Nat) : Bool := x > y
def eq (x : Nat) (y : Nat) : Bool := x == y
def le (x : Nat) (y : Nat) : Bool := x >= y
def gt (x : Nat) (y : Nat) : Bool := x < y
unsafe def main : List String → IO UInt32
| [s] => do
let n := s.toNat;
let e := (mkExpr n 1);
let v₁ := eval e;
let v₂ := eval (constFolding (reassoc e));
IO.println (toString v₁ ++ " " ++ toString v₂);
pure 0
| _ => pure 1
|
0e20e7dc7c4ba6f725d8fe3797d0c21b5f3dbc31 | 5f83eb0c32f15aeed5993a3ad5ededb6f31fe7aa | /lean/attic/natutil.lean | 31af08a0cdb4c50bd7858e98f411a9596648154c | [] | no_license | uw-unsat/jitterbug | 45b54979b156c0f5330012313052f8594abd6f14 | 78d1e75ad506498b585fbac66985ff9d9d05952d | refs/heads/master | 1,689,066,921,433 | 1,687,061,448,000 | 1,688,415,161,000 | 244,440,882 | 46 | 5 | null | null | null | null | UTF-8 | Lean | false | false | 11,437 | lean | -- nat helpers
namespace nat
lemma eq_zero_of_lt_one {n : nat} (h : n < 1) : n = 0 :=
begin
apply eq_zero_of_le_zero,
apply le_of_lt_succ h,
end
theorem sub_eq_zero_of_lt {n m : ℕ} (h : n < m) : n - m = 0 :=
by { apply sub_eq_zero_of_le (le_of_lt h) }
theorem eq_sub_of_add_eq {a b c : ℕ} (h : a + c = b) : a = b - c :=
calc
a = a + c - c : by rw nat.add_sub_cancel
... = b - c : by rw h
theorem sub_add_eq_add_sub {a b c : ℕ} (h : a ≥ b) : a - b + c = a + c - b :=
begin
rw ← nat.sub_add_comm h,
end
theorem sub_sub_eq_add_sub {a b c : ℕ} (h : b ≥ c) : a - (b - c) = a + c - b :=
begin
cases (le_or_gt b (a + c)) with h1 h1,
{ have h2 : b - c ≤ a,
{ apply @nat.le_of_add_le_add_right c,
rw [nat.sub_add_cancel h],
assumption },
rw nat.sub_eq_iff_eq_add h2,
rw ← nat.add_sub_assoc h,
rw nat.sub_add_cancel h1,
rw nat.add_sub_cancel },
{ rw nat.sub_eq_zero_of_lt h1,
apply nat.sub_eq_zero_of_le,
apply @nat.le_of_add_le_add_right c,
rw nat.sub_add_cancel h,
apply le_of_lt h1 }
end
theorem sub_sub_eq_sub_add {a b c : ℕ} (ab : a ≥ b) (bc : b ≥ c) : a - (b - c) = a - b + c :=
begin
rw sub_sub_eq_add_sub bc,
rw sub_add_eq_add_sub ab
end
lemma le_add_to_sub_le {x y z : ℕ} (h : x ≤ y + z) : x - y ≤ z :=
calc
x - y ≤ y + z - y : by { apply nat.sub_le_sub_right h }
... = z : by { apply nat.add_sub_cancel_left }
lemma add_lt_to_lt_sub {x y z : ℕ} (h : x + y < z) : y < z - x :=
begin
have h1 : x ≤ z,
{ apply le_of_lt, apply lt_of_le_of_lt (nat.le_add_right x y) h },
have h2 : y + x < z - x + x,
{ rw [add_comm, nat.sub_add_cancel h1], assumption },
apply lt_of_add_lt_add_right h2
end
theorem le_mul_of_pos_left {n k : ℕ} (h : k > 0) : n ≤ k * n :=
calc
n = 1 * n : by rw one_mul
... ≤ k * n : by { apply mul_le_mul_right, apply succ_le_of_lt h }
lemma mul_add_div_right (x z : ℕ) {y : ℕ} (H : y > 0) : (x * y + z) / y = x + z / y :=
calc
(x * y + z) / y = (z + x * y) / y : by simp
... = z / y + x : by { apply add_mul_div_right _ _ H }
... = x + z / y : by simp
theorem mul_add_mod_left (k x z : ℕ) : (k * x + z) % x = z % x :=
by simp
lemma mul_add_mod_self_right (x y z : ℕ) : (x * y + z) % y = z % y :=
by simp
theorem pow_add_mul (b n m : ℕ) : b^(n + m) = b^n * b^m :=
begin
intros,
induction m with m ih,
{ simp },
{ calc
b^(n + nat.succ m) = b^(nat.succ (n + m)) : by simp
... = b^(n + m) * b : by { apply nat.pow_succ }
... = b^n * b^m * b : by { rw ih }
... = b^n * (b^m * b) : by { apply mul_assoc }
... = b^n * b^nat.succ m : by { rw nat.pow_succ }
}
end
theorem dvd_pow_of_le (b : ℕ) {n m : ℕ} (h : m ≤ n) : b^m ∣ b^n :=
begin
apply nat.dvd_of_mod_eq_zero,
calc
b^n % b^m = b^(n - m + m) % b^m : by { rw nat.sub_add_cancel h }
... = b^(n - m) * b^m % b^m : by { rw pow_add_mul }
... = 0 : by { rw mul_mod_left }
end
lemma dvd_pow_add_left (b n m : ℕ) : b^n ∣ b^(m + n) :=
dvd_pow_of_le b (le_add_left n m)
lemma dvd_pow_add_right (b n m : ℕ) : b^n ∣ b^(n + m) :=
dvd_pow_of_le b (le_add_right n m)
lemma pow_pred {b n : ℕ} (h₁ : b > 0) (h₂ : n > 0) : b^(n - 1) = b^n / b :=
begin
cases n,
{ have : ¬ 0 > 0,
apply gt_irrefl,
contradiction },
{ simp [nat.pow_succ],
rw nat.mul_div_left,
assumption }
end
theorem pow_sub_div {b n m : ℕ} (h₁ : b > 0) (h₂ : m ≤ n) : b^(n - m) = b^n / b^m :=
begin
induction m with m ih,
{ simp },
{ calc
b^(n - nat.succ m) = b^(n - (m + 1)) : by simp
... = b^(n - m - 1) : by { rw nat.sub_sub }
... = b^(n - m) / b : by { rw pow_pred h₁, apply nat.sub_pos_of_lt, apply nat.lt_of_succ_le, assumption }
... = b^n / b^m / b : by { rw ih, apply le_trans, apply nat.le_succ, assumption }
... = b^n / (b^m * b) : by { apply nat.div_div_eq_div_mul }
... = b^n / b^nat.succ m : by { rw nat.pow_succ }
}
end
theorem mod_sub_div (x y : ℕ) : x % y = x - y * (x / y) :=
have (x % y) + (y * (x / y)) = x, by { apply nat.mod_add_div },
by { apply nat.eq_sub_of_add_eq this }
theorem mul_div_le_self : ∀ (m n : ℕ), n * (m / n) ≤ m :=
begin
intros,
rewrite mul_comm,
apply nat.div_mul_le_self
end
theorem add_mod_self_left (x y z : ℕ) : (x % z + y) % z = (x + y) % z :=
have hxz: z * (x / z) ≤ x, by { apply mul_div_le_self },
have hxzy : z * (x / z) ≤ x + y, by { apply le_trans hxz, apply nat.le_add_right },
calc
(x % z + y) % z = (x - z * (x / z) + y) % z : by rw mod_sub_div x z
... = (x + y - z * (x / z)) % z : by rw nat.sub_add_eq_add_sub hxz
... = (x + y) % z : by { apply nat.sub_mul_mod _ _ _ hxzy }
theorem add_mod_self_right (x y z : ℕ) : (x + y % z) % z = (x + y) % z :=
begin
rw add_comm,
rw add_mod_self_left,
rw add_comm
end
theorem add_mod (x y z : ℕ) : (x + y) % z = (x % z + y % z) % z :=
calc
(x + y) % z = (x % z + y) % z : by rw ← add_mod_self_left
... = (x % z + y % z) % z : by rw ← add_mod_self_right
theorem mul_mod_self_left (x y z : ℕ) : ((x % z) * y) % z = (x * y) % z :=
have z * (x / z) ≤ x, by { apply mul_div_le_self },
have z * (x / z) * y ≤ x * y, by { apply nat.mul_le_mul_right _ this },
have h : z * (x / z * y) ≤ x * y, by { rw ← nat.mul_assoc, apply this },
calc
((x % z) * y) % z = ((x - z * (x / z)) * y) % z : by rw mod_sub_div x z
... = (x * y - z * ((x / z) * y)) % z : by simp [nat.mul_sub_right_distrib, nat.mul_assoc]
... = (x * y) % z : by { apply nat.sub_mul_mod _ _ _ h }
theorem mul_mod_self_right (x y z : ℕ) : (x * (y % z)) % z = (x * y) % z :=
calc
(x * (y % z)) % z = ((y % z) * x) % z : by rw mul_comm
... = (y * x) % z : by rw mul_mod_self_left
... = (x * y) % z : by rw mul_comm
theorem mul_mod (x y z : ℕ) : (x * y) % z = ((x % z) * (y % z)) % z :=
calc
(x * y) % z = ((x % z) * y) % z : by rw mul_mod_self_left
... = ((x % z) * (y % z)) % z : by rw mul_mod_self_right
theorem mod_mul (x y z : ℕ) : x % (y * z) = x % y + y * ((x / y) % z) :=
have x % (y * z) + y * z * (x / (y * z)) = x % y + y * ((x / y) % z) + y * z * (x / (y * z)), by calc
x % (y * z) + y * z * (x / (y * z)) = x : by rw nat.mod_add_div
... = x % y + y * (x / y) : by rw nat.mod_add_div
... = x % y + y * ((x / y) % z + z * (x / y / z)) : by rw nat.mod_add_div (x / y)
... = x % y + y * ((x / y) % z) + y * z * (x / y / z) : by rw [left_distrib, add_assoc, mul_assoc]
... = x % y + y * ((x / y) % z) + y * z * (x / (y * z)) : by rw nat.div_div_eq_div_mul,
by { apply nat.add_right_cancel this }
theorem mod_mod (x y : ℕ) : (x % y) % y = x % y :=
begin
cases nat.eq_zero_or_pos y with h h,
{ rw h, simp [nat.mod_zero] },
{ apply nat.mod_eq_of_lt,
apply nat.mod_lt,
exact h }
end
theorem dvd_mod_mod (x y z : ℕ) (H : z ∣ y) : (x % y) % z = x % z :=
match exists_eq_mul_right_of_dvd H with ⟨k, hk⟩ := calc
(x % y) % z = (x % (z * k)) % z : by rw hk
... = (x % z + z * ((x / z) % k)) % z : by rw mod_mul
... = (x % z) % z : by rw nat.add_mul_mod_self_left
... = x % z : by rw mod_mod
end
theorem dvd_mod_div (x y z : ℕ) (H : z ∣ y) : (x % y) / z = x / z % (y / z):=
match exists_eq_mul_right_of_dvd H with ⟨k, hk⟩ := calc
(x % y) / z = (x % (z * k)) / z : by rw hk
... = (x - z * (k * (x / (z * k)))) / z : by rw [mod_sub_div, mul_assoc]
... = x / z - k * (x / (z * k)) : by { rw sub_mul_div,
rw [← mul_assoc z, mul_comm (z * k)],
apply div_mul_le_self }
... = x / z - k * (x / z / k) : by { rw nat.div_div_eq_div_mul }
... = x / z % k : by { rw ← mod_sub_div }
... = x / z % (y / z) : by { cases eq_zero_or_pos z with hz hz,
{ simp [hz] },
{ rw nat.div_eq_of_eq_mul_right hz hk } }
end
theorem mod_div (x : ℕ) {y : ℕ} (h : y > 0) : (x % y) / y = 0 :=
begin
apply nat.div_eq_of_lt,
apply nat.mod_lt _ h
end
-- pow of two
lemma pow2_succ (n : ℕ) : 2^(succ n) = 2 * 2^n :=
by simp [pow_succ, mul_comm]
lemma two_pos : 2 > 0 :=
by { apply succ_pos 1 }
lemma pow2_pos (n : ℕ) : 2^n > 0 :=
by { apply pos_pow_of_pos _ two_pos }
lemma pow2_succ_gt (n : ℕ) : 2^(succ n) > 1 :=
calc
2^(succ n) > (2^0) : by { apply nat.pow_lt_pow_of_lt_right,
apply nat.lt_succ_self,
apply nat.zero_lt_succ }
... = 1 : by simp
@[simp]
lemma one_div_two : 1 / 2 = 0 :=
by { apply div_eq_of_lt (lt_succ_self 1) }
@[simp]
lemma one_mod_two : 1 % 2 = 1 :=
by { apply mod_eq_of_lt (lt_succ_self 1) }
-- bit0/bit1
lemma bit_add_bit0 (b : bool) (n m : ℕ) : bit b n + bit0 m = bit b (n + m) :=
begin
cases b; simp [bit],
{ rw norm_num.bit0_add_bit0 },
{ rw [← norm_num.bit1_add_bit0, add_comm] }
end
lemma bit0_add_bit (b : bool) (n m : ℕ) : bit0 n + bit b m = bit b (n + m) :=
begin
cases b; simp [bit],
{ rw norm_num.bit0_add_bit0 },
{ rw [← norm_num.bit0_add_bit1, add_comm] }
end
lemma bit_div_two (b : bool) (n : ℕ) : bit b n / 2 = n :=
begin
cases b; simp [bit],
{ rw bit0_val,
rw nat.mul_div_cancel_left _ two_pos },
{ rw bit1_val,
rw add_comm,
simp [add_mul_div_left _ _ two_pos] }
end
lemma bit_mod_two (b : bool) (n : ℕ) : bit b n % 2 = cond b 1 0 :=
begin
cases b; simp [bit],
{ rw bit0_val,
rw mul_mod_right },
{ rw bit1_val,
rw add_comm,
simp [add_mul_mod_self_left] }
end
protected lemma bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m :=
add_le_add h h
protected lemma bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m :=
succ_le_succ (add_le_add h h)
lemma bit_le (b : bool) {n m : ℕ} (h : n ≤ m) : bit b n ≤ bit b m :=
begin
cases b; simp [bit],
{ apply nat.bit0_le h },
{ apply nat.bit1_le h }
end
lemma bit_le_bit1 (b : bool) {n m : ℕ} (h : n ≤ m) : bit b n ≤ bit1 m :=
begin
cases b; simp [bit],
{ apply le_of_lt, apply nat.bit0_lt_bit1 h },
{ apply nat.bit1_le h }
end
lemma bit_inj {b : bool} {n m : ℕ} (h : bit b n = bit b m) : n = m :=
begin
cases b; simp [bit] at *,
{ apply nat.bit0_inj h },
{ apply nat.bit1_inj h }
end
lemma bodd_bit0 (n : ℕ) : bodd (bit0 n) = ff :=
by rw bit0_val; simp
lemma bodd_bit1 (n : ℕ) : bodd (bit1 n) = tt :=
by rw bit1_val; simp
lemma bit1_pow2_minus_one (n : ℕ) : bit1 (2^n - 1) = 2^(succ n) - 1 :=
calc
bit1 (2^n - 1) = 2 * (2^n - 1) + 1 : by { rw bit1_val }
... = 2 * 2^n - 2 + 1 : by { rw nat.mul_sub_left_distrib, simp }
... = 2 * 2^n - (2 - 1) : by { rw nat.sub_sub_eq_sub_add,
{ apply @mul_le_mul_left 1 _ 2,
apply pow2_pos },
{ apply le_succ } }
... = 2^(succ n) - 1 : by { rw [pow_succ, mul_comm] }
end nat
|
322edcd0b9c21ddee6c414a92c8c5a5f0bc487d2 | fe84e287c662151bb313504482b218a503b972f3 | /src/combinatorics/fibonacci.lean | f9167f6bd6e7e8da317de79e46adbe293f4c9f6f | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 5,162 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
This file defines Fibonacci numbers and their reductions mod `n`.
It was intended to make computation efficient, but does not
succeed very well. Some better approaches were discussed on
Zulip by Mario and Kenny; they should be incorporated here.
-/
import data.real.basic data.fintype.basic algebra.big_operators data.nat.modeq
import tactic.find tactic.squeeze tactic.norm_num tactic.ring
namespace combinatorics
/- This is the basic definition of fibonacci numbers. It
is not good for efficient evaluation.
-/
def fibonacci : ℕ → ℕ
| 0 := 0
| 1 := 1
| (n + 2) := (fibonacci n) + (fibonacci (n + 1))
/- We now do a more efficient version, and prove that it is
consistent with the original one.
-/
def fibonacci_step : ℕ × ℕ → ℕ × ℕ :=
λ ⟨a,b⟩, ⟨b, a + b⟩
def fibonacci_pair : ℕ → ℕ × ℕ
| 0 := ⟨0,1⟩
| (n + 1) := fibonacci_step (fibonacci_pair n)
lemma fibonacci_pair_spec : ∀ n ,
fibonacci_pair n = ⟨fibonacci n,fibonacci n.succ⟩
| 0 := rfl
| (nat.succ n) := begin
rw[fibonacci_pair,fibonacci_pair_spec n,fibonacci_step,fibonacci],
ext,refl,refl,
end
lemma fibonacci_from_pair (n : ℕ) :
fibonacci n = (fibonacci_pair n).fst :=
by rw[fibonacci_pair_spec n].
/- We now prove a fact about the fibonacci numbers mod 2.
Later we will generalise this for an arbitrary modulus.
-/
lemma fibonacci_bodd_step (n : ℕ) :
(fibonacci (n + 3)).bodd = (fibonacci n).bodd :=
begin
rw[fibonacci,fibonacci,nat.bodd_add,nat.bodd_add],
cases (fibonacci (n + 1)).bodd;
cases (fibonacci n).bodd;
refl,
end
lemma fibonacci_bodd : ∀ n, (fibonacci n).bodd = bnot (n % 3 = 0)
| 0 := rfl
| 1 := rfl
| 2 := rfl
| (n + 3) := begin
rw[fibonacci_bodd_step n,fibonacci_bodd n,nat.add_mod_right]
end
/-
We now do a more general theory of modular periodicity
of fibonacci numbers. For computational efficiency, we
give an inductive definition of modular fibonacci numbers
that does not require us to calculate the non-modular ones.
We then prove that it is consistent with the original
definition.
-/
def pair_mod (p : ℕ) : ℕ × ℕ → ℕ × ℕ :=
λ ⟨a,b⟩, ⟨a % p,b % p⟩
lemma pair_mod_mod (p : ℕ) : ∀ (c : ℕ × ℕ),
pair_mod p (pair_mod p c) = pair_mod p c :=
λ ⟨a,b⟩, by {simp[pair_mod,nat.mod_mod],}
def fibonacci_pair_mod (p : ℕ) : ℕ → ℕ × ℕ
| 0 := pair_mod p ⟨0,1⟩
| (n + 1) := pair_mod p (fibonacci_step (fibonacci_pair_mod n))
lemma fibonacci_pair_mod_mod (p : ℕ) : ∀ n,
pair_mod p (fibonacci_pair_mod p n) = fibonacci_pair_mod p n
| 0 := by {rw[fibonacci_pair_mod,pair_mod_mod],}
| (n + 1) := by {rw[fibonacci_pair_mod,pair_mod_mod],}
lemma mod_step_mod (p : ℕ) : ∀ (c : ℕ × ℕ),
pair_mod p (fibonacci_step c) =
pair_mod p (fibonacci_step (pair_mod p c)) :=
λ ⟨a,b⟩, begin
change (⟨b % p,(a + b) % p⟩ : ℕ × ℕ) =
⟨b % p % p,(a % p + b % p) % p⟩,
have e0 : b % p % p = b % p := nat.mod_mod b p,
have e1 : (a % p + b % p) % p = (a + b) % p :=
nat.modeq.add (nat.mod_mod a p) (nat.mod_mod b p),
rw[e0,e1],
end
lemma fibonacci_pair_mod_spec (p : ℕ) : ∀ n,
fibonacci_pair_mod p n = pair_mod p (fibonacci_pair n)
| 0 := rfl
| (n + 1) := begin
rw[fibonacci_pair_mod,fibonacci_pair,fibonacci_pair_mod_spec n],
rw[← mod_step_mod],
end
lemma fibonacci_mod_spec (p : ℕ) (n : ℕ) :
(fibonacci_pair_mod p n).fst = (fibonacci n) % p :=
begin
rw[fibonacci_pair_mod_spec,fibonacci_pair_spec,pair_mod],
refl,
end
lemma fibonacci_pair_period₀ {p : ℕ} {d : ℕ}
(h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) :
∀ n, fibonacci_pair_mod p (n + d) = fibonacci_pair_mod p n
| 0 := by {rw[zero_add,h,fibonacci_pair_mod],}
| (n + 1) := by {
rw[add_assoc,add_comm 1 d,← add_assoc],
rw[fibonacci_pair_mod,fibonacci_pair_mod],
rw[fibonacci_pair_period₀ n],
}
lemma fibonacci_pair_period₁ {p : ℕ} {d : ℕ}
(h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (m : ℕ) :
∀ n, fibonacci_pair_mod p (m + d * n) = fibonacci_pair_mod p m
| 0 := by {rw[mul_zero,add_zero]}
| (n + 1) := by {
have : m + d * (n + 1) = (m + d * n) + d := by ring,
rw[this,fibonacci_pair_period₀ h,fibonacci_pair_period₁],
}
lemma fibonacci_pair_period {p : ℕ} {d : ℕ}
(h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (n : ℕ) :
fibonacci_pair_mod p n = fibonacci_pair_mod p (n % d) :=
calc
fibonacci_pair_mod p n = fibonacci_pair_mod p (n % d + d * (n / d)) :
congr_arg (fibonacci_pair_mod p) (nat.mod_add_div n d).symm
... = fibonacci_pair_mod p (n % d) : fibonacci_pair_period₁ h (n % d) (n / d)
lemma fibonacci_period {p : ℕ} {d : ℕ}
(h : fibonacci_pair_mod p d = pair_mod p ⟨0,1⟩) (n : ℕ) :
(fibonacci n) ≡ (fibonacci (n % d)) [MOD p] :=
begin
rw[nat.modeq,← fibonacci_mod_spec,← fibonacci_mod_spec],
rw[fibonacci_pair_period],
exact h,
end
/-
Prove the identity
(fibonacci n) = (choose n 0) + (choose n-1 1) + (choose n-2 2) + ...
-/
end combinatorics |
4c32287d2d173fa9d34146f64ed040e8cc2ab698 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /test/traversable.lean | 6adc03f87b4114f8cef75a8c0c923fd0bdd8556e | [
"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 | 1,962 | lean | import control.traversable.derive
import control.traversable.instances
universes u
/- traversable -/
open tactic.interactive
run_cmd do
lawful_traversable_derive_handler' `test ``(is_lawful_traversable) ``list
-- the above creates local instances of `traversable` and `is_lawful_traversable`
-- for `list`
-- do not put in instances because they are not universe polymorphic
@[derive [traversable, is_lawful_traversable]]
structure my_struct (α : Type) :=
(y : ℤ)
@[derive [traversable, is_lawful_traversable]]
inductive either (α : Type u)
| left : α → ℤ → either
| right : α → either
@[derive [traversable, is_lawful_traversable]]
structure my_struct2 (α : Type u) : Type u :=
(x : α)
(y : ℤ)
(η : list α)
(k : list (list α))
@[derive [traversable, is_lawful_traversable]]
inductive rec_data3 (α : Type u) : Type u
| nil : rec_data3
| cons : ℕ → α → rec_data3 → rec_data3 → rec_data3
@[derive traversable]
meta structure meta_struct (α : Type u) : Type u :=
(x : α)
(y : ℤ)
(z : list α)
(k : list (list α))
(w : expr)
@[derive [traversable,is_lawful_traversable]]
inductive my_tree (α : Type)
| leaf : my_tree
| node : my_tree → my_tree → α → my_tree
section
open my_tree (hiding traverse)
def x : my_tree (list nat) :=
node
leaf
(node
(node leaf leaf [1,2,3])
leaf
[3,2])
[1]
/-- demonstrate the nested use of `traverse`. It traverses each node of the tree and
in each node, traverses each list. For each `ℕ` visited, apply an action `ℕ -> state (list ℕ) unit`
which adds its argument to the state. -/
def ex : state (list ℕ) (my_tree $ list unit) :=
do xs ← traverse (traverse $ λ a, modify $ list.cons a) x,
pure xs
example : (ex.run []).1 = node leaf (node (node leaf leaf [(), (), ()]) leaf [(), ()]) [()] := rfl
example : (ex.run []).2 = [1, 2, 3, 3, 2, 1] := rfl
example : is_lawful_traversable my_tree := my_tree.is_lawful_traversable
end
|
2f3e9852adaee90a7af64707df3ffbfbe13bbeb9 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/order/filter/bases.lean | 7480d36f4222344ca3c57762098496644443b69e | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36,536 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov, Johannes Hölzl, Mario Carneiro, Patrick Massot
-/
import order.filter.basic
import data.set.countable
/-!
# Filter bases
A filter basis `B : filter_basis α` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element of
the collection. Compared to filters, filter bases do not require that any set containing
an element of `B` belongs to `B`.
A filter basis `B` can be used to construct `B.filter : filter α` such that a set belongs
to `B.filter` if and only if it contains an element of `B`.
Given an indexing type `ι`, a predicate `p : ι → Prop`, and a map `s : ι → set α`,
the proposition `h : filter.is_basis p s` makes sure the range of `s` bounded by `p`
(ie. `s '' set_of p`) defines a filter basis `h.filter_basis`.
If one already has a filter `l` on `α`, `filter.has_basis l p s` (where `p : ι → Prop`
and `s : ι → set α` as above) means that a set belongs to `l` if and
only if it contains some `s i` with `p i`. It implies `h : filter.is_basis p s`, and
`l = h.filter_basis.filter`. The point of this definition is that checking statements
involving elements of `l` often reduces to checking them on the basis elements.
We define a function `has_basis.index (h : filter.has_basis l p s) (t) (ht : t ∈ l)` that returns
some index `i` such that `p i` and `s i ⊆ t`. This function can be useful to avoid manual
destruction of `h.mem_iff.mpr ht` using `cases` or `let`.
This file also introduces more restricted classes of bases, involving monotonicity or
countability. In particular, for `l : filter α`, `l.is_countably_generated` means
there is a countable set of sets which generates `s`. This is reformulated in term of bases,
and consequences are derived.
## Main statements
* `has_basis.mem_iff`, `has_basis.mem_of_superset`, `has_basis.mem_of_mem` : restate `t ∈ f`
in terms of a basis;
* `basis_sets` : all sets of a filter form a basis;
* `has_basis.inf`, `has_basis.inf_principal`, `has_basis.prod`, `has_basis.prod_self`,
`has_basis.map`, `has_basis.comap` : combinators to construct filters of `l ⊓ l'`,
`l ⊓ 𝓟 t`, `l ×ᶠ l'`, `l ×ᶠ l`, `l.map f`, `l.comap f` respectively;
* `has_basis.le_iff`, `has_basis.ge_iff`, has_basis.le_basis_iff` : restate `l ≤ l'` in terms
of bases.
* `has_basis.tendsto_right_iff`, `has_basis.tendsto_left_iff`, `has_basis.tendsto_iff` : restate
`tendsto f l l'` in terms of bases.
* `is_countably_generated_iff_exists_antimono_basis` : proves a filter is
countably generated if and only if it admis a basis parametrized by a
decreasing sequence of sets indexed by `ℕ`.
* `tendsto_iff_seq_tendsto ` : an abstract version of "sequentially continuous implies continuous".
## Implementation notes
As with `Union`/`bUnion`/`sUnion`, there are three different approaches to filter bases:
* `has_basis l s`, `s : set (set α)`;
* `has_basis l s`, `s : ι → set α`;
* `has_basis l p s`, `p : ι → Prop`, `s : ι → set α`.
We use the latter one because, e.g., `𝓝 x` in an `emetric_space` or in a `metric_space` has a basis
of this form. The other two can be emulated using `s = id` or `p = λ _, true`.
With this approach sometimes one needs to `simp` the statement provided by the `has_basis`
machinery, e.g., `simp only [exists_prop, true_and]` or `simp only [forall_const]` can help
with the case `p = λ _, true`.
-/
open set filter
open_locale filter classical
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} {ι' : Type*}
/-- A filter basis `B` on a type `α` is a nonempty collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure filter_basis (α : Type*) :=
(sets : set (set α))
(nonempty : sets.nonempty)
(inter_sets {x y} : x ∈ sets → y ∈ sets → ∃ z ∈ sets, z ⊆ x ∩ y)
instance filter_basis.nonempty_sets (B : filter_basis α) : nonempty B.sets := B.nonempty.to_subtype
/-- If `B` is a filter basis on `α`, and `U` a subset of `α` then we can write `U ∈ B` as
on paper. -/
@[reducible]
instance {α : Type*}: has_mem (set α) (filter_basis α) := ⟨λ U B, U ∈ B.sets⟩
-- For illustration purposes, the filter basis defining (at_top : filter ℕ)
instance : inhabited (filter_basis ℕ) :=
⟨{ sets := range Ici,
nonempty := ⟨Ici 0, mem_range_self 0⟩,
inter_sets := begin
rintros _ _ ⟨n, rfl⟩ ⟨m, rfl⟩,
refine ⟨Ici (max n m), mem_range_self _, _⟩,
rintros p p_in,
split ; rw mem_Ici at *,
exact le_of_max_le_left p_in,
exact le_of_max_le_right p_in,
end }⟩
/-- `is_basis p s` means the image of `s` bounded by `p` is a filter basis. -/
protected structure filter.is_basis (p : ι → Prop) (s : ι → set α) : Prop :=
(nonempty : ∃ i, p i)
(inter : ∀ {i j}, p i → p j → ∃ k, p k ∧ s k ⊆ s i ∩ s j)
namespace filter
namespace is_basis
/-- Constructs a filter basis from an indexed family of sets satisfying `is_basis`. -/
protected def filter_basis {p : ι → Prop} {s : ι → set α} (h : is_basis p s) : filter_basis α :=
{ sets := s '' set_of p,
nonempty := let ⟨i, hi⟩ := h.nonempty in ⟨s i, mem_image_of_mem s hi⟩,
inter_sets := by { rintros _ _ ⟨i, hi, rfl⟩ ⟨j, hj, rfl⟩,
rcases h.inter hi hj with ⟨k, hk, hk'⟩,
exact ⟨_, mem_image_of_mem s hk, hk'⟩ } }
variables {p : ι → Prop} {s : ι → set α} (h : is_basis p s)
lemma mem_filter_basis_iff {U : set α} : U ∈ h.filter_basis ↔ ∃ i, p i ∧ s i = U :=
iff.rfl
end is_basis
end filter
namespace filter_basis
/-- The filter associated to a filter basis. -/
protected def filter (B : filter_basis α) : filter α :=
{ sets := {s | ∃ t ∈ B, t ⊆ s},
univ_sets := let ⟨s, s_in⟩ := B.nonempty in ⟨s, s_in, s.subset_univ⟩,
sets_of_superset := λ x y ⟨s, s_in, h⟩ hxy, ⟨s, s_in, set.subset.trans h hxy⟩,
inter_sets := λ x y ⟨s, s_in, hs⟩ ⟨t, t_in, ht⟩,
let ⟨u, u_in, u_sub⟩ := B.inter_sets s_in t_in in
⟨u, u_in, set.subset.trans u_sub $ set.inter_subset_inter hs ht⟩ }
lemma mem_filter_iff (B : filter_basis α) {U : set α} : U ∈ B.filter ↔ ∃ s ∈ B, s ⊆ U :=
iff.rfl
lemma mem_filter_of_mem (B : filter_basis α) {U : set α} : U ∈ B → U ∈ B.filter:=
λ U_in, ⟨U, U_in, subset.refl _⟩
lemma eq_infi_principal (B : filter_basis α) : B.filter = ⨅ s : B.sets, 𝓟 s :=
begin
have : directed (≥) (λ (s : B.sets), 𝓟 (s : set α)),
{ rintros ⟨U, U_in⟩ ⟨V, V_in⟩,
rcases B.inter_sets U_in V_in with ⟨W, W_in, W_sub⟩,
use [W, W_in],
finish },
ext U,
simp [mem_filter_iff, mem_infi this]
end
protected lemma generate (B : filter_basis α) : generate B.sets = B.filter :=
begin
apply le_antisymm,
{ intros U U_in,
rcases B.mem_filter_iff.mp U_in with ⟨V, V_in, h⟩,
exact generate_sets.superset (generate_sets.basic V_in) h },
{ rw sets_iff_generate,
apply mem_filter_of_mem }
end
end filter_basis
namespace filter
namespace is_basis
variables {p : ι → Prop} {s : ι → set α}
/-- Constructs a filter from an indexed family of sets satisfying `is_basis`. -/
protected def filter (h : is_basis p s) : filter α := h.filter_basis.filter
protected lemma mem_filter_iff (h : is_basis p s) {U : set α} :
U ∈ h.filter ↔ ∃ i, p i ∧ s i ⊆ U :=
begin
erw [h.filter_basis.mem_filter_iff],
simp only [mem_filter_basis_iff h, exists_prop],
split,
{ rintros ⟨_, ⟨i, pi, rfl⟩, h⟩,
tauto },
{ tauto }
end
lemma filter_eq_generate (h : is_basis p s) : h.filter = generate {U | ∃ i, p i ∧ s i = U} :=
by erw h.filter_basis.generate ; refl
end is_basis
/-- We say that a filter `l` has a basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`. -/
protected structure has_basis (l : filter α) (p : ι → Prop) (s : ι → set α) : Prop :=
(mem_iff' : ∀ (t : set α), t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t)
section same_type
variables {l l' : filter α} {p : ι → Prop} {s : ι → set α} {t : set α} {i : ι}
{p' : ι' → Prop} {s' : ι' → set α} {i' : ι'}
lemma has_basis_generate (s : set (set α)) :
(generate s).has_basis (λ t, finite t ∧ t ⊆ s) (λ t, ⋂₀ t) :=
⟨begin
intro U,
rw mem_generate_iff,
apply exists_congr,
tauto
end⟩
/-- The smallest filter basis containing a given collection of sets. -/
def filter_basis.of_sets (s : set (set α)) : filter_basis α :=
{ sets := sInter '' { t | finite t ∧ t ⊆ s},
nonempty := ⟨univ, ∅, ⟨⟨finite_empty, empty_subset s⟩, sInter_empty⟩⟩,
inter_sets := begin
rintros _ _ ⟨a, ⟨fina, suba⟩, rfl⟩ ⟨b, ⟨finb, subb⟩, rfl⟩,
exact ⟨⋂₀ (a ∪ b), mem_image_of_mem _ ⟨fina.union finb, union_subset suba subb⟩,
by rw sInter_union⟩,
end }
/-- Definition of `has_basis` unfolded with implicit set argument. -/
lemma has_basis.mem_iff (hl : l.has_basis p s) : t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
hl.mem_iff' t
lemma has_basis_iff : l.has_basis p s ↔ ∀ t, t ∈ l ↔ ∃ i (hi : p i), s i ⊆ t :=
⟨λ ⟨h⟩, h, λ h, ⟨h⟩⟩
lemma has_basis.ex_mem (h : l.has_basis p s) : ∃ i, p i :=
let ⟨i, pi, h⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, pi⟩
protected lemma is_basis.has_basis (h : is_basis p s) : has_basis h.filter p s :=
⟨λ t, by simp only [h.mem_filter_iff, exists_prop]⟩
lemma has_basis.mem_of_superset (hl : l.has_basis p s) (hi : p i) (ht : s i ⊆ t) : t ∈ l :=
(hl.mem_iff).2 ⟨i, hi, ht⟩
lemma has_basis.mem_of_mem (hl : l.has_basis p s) (hi : p i) : s i ∈ l :=
hl.mem_of_superset hi $ subset.refl _
/-- Index of a basis set such that `s i ⊆ t` as an element of `subtype p`. -/
noncomputable def has_basis.index (h : l.has_basis p s) (t : set α) (ht : t ∈ l) :
{i : ι // p i} :=
⟨(h.mem_iff.1 ht).some, (h.mem_iff.1 ht).some_spec.fst⟩
lemma has_basis.property_index (h : l.has_basis p s) (ht : t ∈ l) : p (h.index t ht) :=
(h.index t ht).2
lemma has_basis.set_index_mem (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ∈ l :=
h.mem_of_mem $ h.property_index _
lemma has_basis.set_index_subset (h : l.has_basis p s) (ht : t ∈ l) : s (h.index t ht) ⊆ t :=
(h.mem_iff.1 ht).some_spec.snd
lemma has_basis.is_basis (h : l.has_basis p s) : is_basis p s :=
{ nonempty := let ⟨i, hi, H⟩ := h.mem_iff.mp univ_mem_sets in ⟨i, hi⟩,
inter := λ i j hi hj, by simpa [h.mem_iff]
using l.inter_sets (h.mem_of_mem hi) (h.mem_of_mem hj) }
lemma has_basis.filter_eq (h : l.has_basis p s) : h.is_basis.filter = l :=
by { ext U, simp [h.mem_iff, is_basis.mem_filter_iff] }
lemma has_basis.eq_generate (h : l.has_basis p s) : l = generate { U | ∃ i, p i ∧ s i = U } :=
by rw [← h.is_basis.filter_eq_generate, h.filter_eq]
lemma generate_eq_generate_inter (s : set (set α)) :
generate s = generate (sInter '' { t | finite t ∧ t ⊆ s}) :=
by erw [(filter_basis.of_sets s).generate, ← (has_basis_generate s).filter_eq] ; refl
lemma of_sets_filter_eq_generate (s : set (set α)) : (filter_basis.of_sets s).filter = generate s :=
by rw [← (filter_basis.of_sets s).generate, generate_eq_generate_inter s] ; refl
lemma has_basis.to_has_basis (hl : l.has_basis p s) (h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l.has_basis p' s' :=
begin
constructor,
intro t,
rw hl.mem_iff,
split,
{ rintros ⟨i, pi, hi⟩,
rcases h i pi with ⟨i', pi', hi'⟩,
use [i', pi'],
tauto },
{ rintros ⟨i', pi', hi'⟩,
rcases h' i' pi' with ⟨i, pi, hi⟩,
use [i, pi],
tauto },
end
lemma has_basis.eventually_iff (hl : l.has_basis p s) {q : α → Prop} :
(∀ᶠ x in l, q x) ↔ ∃ i, p i ∧ ∀ ⦃x⦄, x ∈ s i → q x :=
by simpa using hl.mem_iff
lemma has_basis.frequently_iff (hl : l.has_basis p s) {q : α → Prop} :
(∃ᶠ x in l, q x) ↔ ∀ i, p i → ∃ x ∈ s i, q x :=
by simp [filter.frequently, hl.eventually_iff]
lemma has_basis.exists_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P t → P s) :
(∃ s ∈ l, P s) ↔ ∃ (i) (hi : p i), P (s i) :=
⟨λ ⟨s, hs, hP⟩, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in ⟨i, hi, mono his hP⟩,
λ ⟨i, hi, hP⟩, ⟨s i, hl.mem_of_mem hi, hP⟩⟩
lemma has_basis.forall_iff (hl : l.has_basis p s) {P : set α → Prop}
(mono : ∀ ⦃s t⦄, s ⊆ t → P s → P t) :
(∀ s ∈ l, P s) ↔ ∀ i, p i → P (s i) :=
⟨λ H i hi, H (s i) $ hl.mem_of_mem hi,
λ H s hs, let ⟨i, hi, his⟩ := hl.mem_iff.1 hs in mono his (H i hi)⟩
lemma has_basis.ne_bot_iff (hl : l.has_basis p s) :
ne_bot l ↔ (∀ {i}, p i → (s i).nonempty) :=
forall_sets_nonempty_iff_ne_bot.symm.trans $ hl.forall_iff $ λ _ _, nonempty.mono
lemma has_basis.eq_bot_iff (hl : l.has_basis p s) :
l = ⊥ ↔ ∃ i, p i ∧ s i = ∅ :=
not_iff_not.1 $ ne_bot_iff.symm.trans $ hl.ne_bot_iff.trans $
by simp only [not_exists, not_and, ← ne_empty_iff_nonempty]
lemma basis_sets (l : filter α) : l.has_basis (λ s : set α, s ∈ l) id :=
⟨λ t, exists_sets_subset_iff.symm⟩
lemma has_basis_self {l : filter α} {P : set α → Prop} :
has_basis l (λ s, s ∈ l ∧ P s) id ↔ ∀ t ∈ l, ∃ r ∈ l, P r ∧ r ⊆ t :=
begin
simp only [has_basis_iff, exists_prop, id, and_assoc],
exact forall_congr (λ s, ⟨λ h, h.1, λ h, ⟨h, λ ⟨t, hl, hP, hts⟩, mem_sets_of_superset hl hts⟩⟩)
end
/-- If `{s i | p i}` is a basis of a filter `l` and each `s i` includes `s j` such that
`p j ∧ q j`, then `{s j | p j ∧ q j}` is a basis of `l`. -/
lemma has_basis.restrict (h : l.has_basis p s) {q : ι → Prop}
(hq : ∀ i, p i → ∃ j, p j ∧ q j ∧ s j ⊆ s i) :
l.has_basis (λ i, p i ∧ q i) s :=
begin
refine ⟨λ t, ⟨λ ht, _, λ ⟨i, hpi, hti⟩, h.mem_iff.2 ⟨i, hpi.1, hti⟩⟩⟩,
rcases h.mem_iff.1 ht with ⟨i, hpi, hti⟩,
rcases hq i hpi with ⟨j, hpj, hqj, hji⟩,
exact ⟨j, ⟨hpj, hqj⟩, subset.trans hji hti⟩
end
/-- If `{s i | p i}` is a basis of a filter `l` and `V ∈ l`, then `{s i | p i ∧ s i ⊆ V}`
is a basis of `l`. -/
lemma has_basis.restrict_subset (h : l.has_basis p s) {V : set α} (hV : V ∈ l) :
l.has_basis (λ i, p i ∧ s i ⊆ V) s :=
h.restrict $ λ i hi, (h.mem_iff.1 (inter_mem_sets hV (h.mem_of_mem hi))).imp $
λ j hj, ⟨hj.fst, subset_inter_iff.1 hj.snd⟩
lemma has_basis.has_basis_self_subset {p : set α → Prop} (h : l.has_basis (λ s, s ∈ l ∧ p s) id)
{V : set α} (hV : V ∈ l) : l.has_basis (λ s, s ∈ l ∧ p s ∧ s ⊆ V) id :=
by simpa only [and_assoc] using h.restrict_subset hV
theorem has_basis.ge_iff (hl' : l'.has_basis p' s') : l ≤ l' ↔ ∀ i', p' i' → s' i' ∈ l :=
⟨λ h i' hi', h $ hl'.mem_of_mem hi',
λ h s hs, let ⟨i', hi', hs⟩ := hl'.mem_iff.1 hs in mem_sets_of_superset (h _ hi') hs⟩
theorem has_basis.le_iff (hl : l.has_basis p s) : l ≤ l' ↔ ∀ t ∈ l', ∃ i (hi : p i), s i ⊆ t :=
by simp only [le_def, hl.mem_iff]
theorem has_basis.le_basis_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
l ≤ l' ↔ ∀ i', p' i' → ∃ i (hi : p i), s i ⊆ s' i' :=
by simp only [hl'.ge_iff, hl.mem_iff]
lemma has_basis.ext (hl : l.has_basis p s) (hl' : l'.has_basis p' s')
(h : ∀ i, p i → ∃ i', p' i' ∧ s' i' ⊆ s i)
(h' : ∀ i', p' i' → ∃ i, p i ∧ s i ⊆ s' i') : l = l' :=
begin
apply le_antisymm,
{ rw hl.le_basis_iff hl',
simpa using h' },
{ rw hl'.le_basis_iff hl,
simpa using h },
end
lemma has_basis.inf (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊓ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∩ s' i.2) :=
⟨begin
intro t,
simp only [mem_inf_sets, exists_prop, hl.mem_iff, hl'.mem_iff],
split,
{ rintros ⟨t, ⟨i, hi, ht⟩, t', ⟨i', hi', ht'⟩, H⟩,
use [(i, i'), ⟨hi, hi'⟩, subset.trans (inter_subset_inter ht ht') H] },
{ rintros ⟨⟨i, i'⟩, ⟨hi, hi'⟩, H⟩,
use [s i, i, hi, subset.refl _, s' i', i', hi', subset.refl _, H] }
end⟩
lemma has_basis_principal (t : set α) : (𝓟 t).has_basis (λ i : unit, true) (λ i, t) :=
⟨λ U, by simp⟩
lemma has_basis.sup (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
(l ⊔ l').has_basis (λ i : ι × ι', p i.1 ∧ p' i.2) (λ i, s i.1 ∪ s' i.2) :=
⟨begin
intros t,
simp only [mem_sup_sets, hl.mem_iff, hl'.mem_iff, prod.exists, union_subset_iff, exists_prop,
and_assoc, exists_and_distrib_left],
simp only [← and_assoc, exists_and_distrib_right, and_comm]
end⟩
lemma has_basis.inf_principal (hl : l.has_basis p s) (s' : set α) :
(l ⊓ 𝓟 s').has_basis p (λ i, s i ∩ s') :=
⟨λ t, by simp only [mem_inf_principal, hl.mem_iff, subset_def, mem_set_of_eq,
mem_inter_iff, and_imp]⟩
lemma has_basis.inf_basis_ne_bot_iff (hl : l.has_basis p s) (hl' : l'.has_basis p' s') :
ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃i'⦄ (hi' : p' i'), (s i ∩ s' i').nonempty :=
(hl.inf hl').ne_bot_iff.trans $ by simp [@forall_swap _ ι']
lemma has_basis.inf_ne_bot_iff (hl : l.has_basis p s) :
ne_bot (l ⊓ l') ↔ ∀ ⦃i⦄ (hi : p i) ⦃s'⦄ (hs' : s' ∈ l'), (s i ∩ s').nonempty :=
hl.inf_basis_ne_bot_iff l'.basis_sets
lemma has_basis.inf_principal_ne_bot_iff (hl : l.has_basis p s) {t : set α} :
ne_bot (l ⊓ 𝓟 t) ↔ ∀ ⦃i⦄ (hi : p i), (s i ∩ t).nonempty :=
(hl.inf_principal t).ne_bot_iff
lemma inf_ne_bot_iff :
ne_bot (l ⊓ l') ↔ ∀ ⦃s : set α⦄ (hs : s ∈ l) ⦃s'⦄ (hs' : s' ∈ l'), (s ∩ s').nonempty :=
l.basis_sets.inf_ne_bot_iff
lemma inf_principal_ne_bot_iff {s : set α} :
ne_bot (l ⊓ 𝓟 s) ↔ ∀ U ∈ l, (U ∩ s).nonempty :=
l.basis_sets.inf_principal_ne_bot_iff
lemma inf_eq_bot_iff {f g : filter α} :
f ⊓ g = ⊥ ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ :=
not_iff_not.1 $ ne_bot_iff.symm.trans $ inf_ne_bot_iff.trans $
by simp [← ne_empty_iff_nonempty]
protected lemma disjoint_iff {f g : filter α} :
disjoint f g ↔ ∃ (U ∈ f) (V ∈ g), U ∩ V = ∅ :=
disjoint_iff.trans inf_eq_bot_iff
lemma mem_iff_inf_principal_compl {f : filter α} {s : set α} :
s ∈ f ↔ f ⊓ 𝓟 sᶜ = ⊥ :=
begin
refine not_iff_not.1 ((inf_principal_ne_bot_iff.trans _).symm.trans ne_bot_iff),
exact ⟨λ h hs, by simpa [empty_not_nonempty] using h s hs,
λ hs t ht, inter_compl_nonempty_iff.2 $ λ hts, hs $ mem_sets_of_superset ht hts⟩,
end
lemma not_mem_iff_inf_principal_compl {f : filter α} {s : set α} :
s ∉ f ↔ ne_bot (f ⊓ 𝓟 sᶜ) :=
(not_congr mem_iff_inf_principal_compl).trans ne_bot_iff.symm
lemma mem_iff_disjoint_principal_compl {f : filter α} {s : set α} :
s ∈ f ↔ disjoint f (𝓟 sᶜ) :=
mem_iff_inf_principal_compl.trans disjoint_iff.symm
lemma le_iff_forall_disjoint_principal_compl {f g : filter α} :
f ≤ g ↔ ∀ V ∈ g, disjoint f (𝓟 Vᶜ) :=
forall_congr $ λ _, forall_congr $ λ _, mem_iff_disjoint_principal_compl
lemma le_iff_forall_inf_principal_compl {f g : filter α} :
f ≤ g ↔ ∀ V ∈ g, f ⊓ 𝓟 Vᶜ = ⊥ :=
forall_congr $ λ _, forall_congr $ λ _, mem_iff_inf_principal_compl
lemma inf_ne_bot_iff_frequently_left {f g : filter α} :
ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in f, p x) → ∃ᶠ x in g, p x :=
by simpa only [inf_ne_bot_iff, frequently_iff, exists_prop, and_comm]
lemma inf_ne_bot_iff_frequently_right {f g : filter α} :
ne_bot (f ⊓ g) ↔ ∀ {p : α → Prop}, (∀ᶠ x in g, p x) → ∃ᶠ x in f, p x :=
by { rw inf_comm, exact inf_ne_bot_iff_frequently_left }
lemma has_basis.eq_binfi (h : l.has_basis p s) :
l = ⨅ i (_ : p i), 𝓟 (s i) :=
eq_binfi_of_mem_sets_iff_exists_mem $ λ t, by simp only [h.mem_iff, mem_principal_sets]
lemma has_basis.eq_infi (h : l.has_basis (λ _, true) s) :
l = ⨅ i, 𝓟 (s i) :=
by simpa only [infi_true] using h.eq_binfi
lemma has_basis_infi_principal {s : ι → set α} (h : directed (≥) s) [nonempty ι] :
(⨅ i, 𝓟 (s i)).has_basis (λ _, true) s :=
⟨begin
refine λ t, (mem_infi (h.mono_comp _ _) t).trans $
by simp only [exists_prop, true_and, mem_principal_sets],
exact λ _ _, principal_mono.2
end⟩
/-- If `s : ι → set α` is an indexed family of sets, then finite intersections of `s i` form a basis
of `⨅ i, 𝓟 (s i)`. -/
lemma has_basis_infi_principal_finite (s : ι → set α) :
(⨅ i, 𝓟 (s i)).has_basis (λ t : set ι, finite t) (λ t, ⋂ i ∈ t, s i) :=
begin
refine ⟨λ U, (mem_infi_finite _).trans _⟩,
simp only [infi_principal_finset, mem_Union, mem_principal_sets, exists_prop,
exists_finite_iff_finset, finset.set_bInter_coe]
end
lemma has_basis_binfi_principal {s : β → set α} {S : set β} (h : directed_on (s ⁻¹'o (≥)) S)
(ne : S.nonempty) :
(⨅ i ∈ S, 𝓟 (s i)).has_basis (λ i, i ∈ S) s :=
⟨begin
refine λ t, (mem_binfi _ ne).trans $ by simp only [mem_principal_sets],
rw [directed_on_iff_directed, ← directed_comp, (∘)] at h ⊢,
apply h.mono_comp _ _,
exact λ _ _, principal_mono.2
end⟩
lemma has_basis_binfi_principal'
(h : ∀ i, p i → ∀ j, p j → ∃ k (h : p k), s k ⊆ s i ∧ s k ⊆ s j) (ne : ∃ i, p i) :
(⨅ i (h : p i), 𝓟 (s i)).has_basis p s :=
filter.has_basis_binfi_principal h ne
lemma has_basis.map (f : α → β) (hl : l.has_basis p s) :
(l.map f).has_basis p (λ i, f '' (s i)) :=
⟨λ t, by simp only [mem_map, image_subset_iff, hl.mem_iff, preimage]⟩
lemma has_basis.comap (f : β → α) (hl : l.has_basis p s) :
(l.comap f).has_basis p (λ i, f ⁻¹' (s i)) :=
⟨begin
intro t,
simp only [mem_comap_sets, exists_prop, hl.mem_iff],
split,
{ rintros ⟨t', ⟨i, hi, ht'⟩, H⟩,
exact ⟨i, hi, subset.trans (preimage_mono ht') H⟩ },
{ rintros ⟨i, hi, H⟩,
exact ⟨s i, ⟨i, hi, subset.refl _⟩, H⟩ }
end⟩
lemma comap_has_basis (f : α → β) (l : filter β) :
has_basis (comap f l) (λ s : set β, s ∈ l) (λ s, f ⁻¹' s) :=
⟨λ t, mem_comap_sets⟩
lemma has_basis.prod_self (hl : l.has_basis p s) :
(l ×ᶠ l).has_basis p (λ i, (s i).prod (s i)) :=
⟨begin
intro t,
apply mem_prod_iff.trans,
split,
{ rintros ⟨t₁, ht₁, t₂, ht₂, H⟩,
rcases hl.mem_iff.1 (inter_mem_sets ht₁ ht₂) with ⟨i, hi, ht⟩,
exact ⟨i, hi, λ p ⟨hp₁, hp₂⟩, H ⟨(ht hp₁).1, (ht hp₂).2⟩⟩ },
{ rintros ⟨i, hi, H⟩,
exact ⟨s i, hl.mem_of_mem hi, s i, hl.mem_of_mem hi, H⟩ }
end⟩
lemma mem_prod_self_iff {s} : s ∈ l ×ᶠ l ↔ ∃ t ∈ l, set.prod t t ⊆ s :=
l.basis_sets.prod_self.mem_iff
lemma has_basis.sInter_sets (h : has_basis l p s) :
⋂₀ l.sets = ⋂ i ∈ set_of p, s i :=
begin
ext x,
suffices : (∀ t ∈ l, x ∈ t) ↔ ∀ i, p i → x ∈ s i,
by simpa only [mem_Inter, mem_set_of_eq, mem_sInter],
simp_rw h.mem_iff,
split,
{ intros h i hi,
exact h (s i) ⟨i, hi, subset.refl _⟩ },
{ rintros h _ ⟨i, hi, sub⟩,
exact sub (h i hi) },
end
variables [preorder ι] (l p s)
/-- `is_antimono_basis p s` means the image of `s` bounded by `p` is a filter basis
such that `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure is_antimono_basis extends is_basis p s : Prop :=
(decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i)
(mono : monotone p)
/-- We say that a filter `l` has a antimono basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`,
and `s` is decreasing and `p` is increasing, ie `i ≤ j → p i → p j`. -/
structure has_antimono_basis [preorder ι] (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s : Prop :=
(decreasing : ∀ {i j}, p i → p j → i ≤ j → s j ⊆ s i)
(mono : monotone p)
end same_type
section two_types
variables {la : filter α} {pa : ι → Prop} {sa : ι → set α}
{lb : filter β} {pb : ι' → Prop} {sb : ι' → set β} {f : α → β}
lemma has_basis.tendsto_left_iff (hla : la.has_basis pa sa) :
tendsto f la lb ↔ ∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t :=
by { simp only [tendsto, (hla.map f).le_iff, image_subset_iff], refl }
lemma has_basis.tendsto_right_iff (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
by simp only [tendsto, hlb.ge_iff, mem_map, filter.eventually]
lemma has_basis.tendsto_iff (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
tendsto f la lb ↔ ∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
by simp [hlb.tendsto_right_iff, hla.eventually_iff]
lemma tendsto.basis_left (H : tendsto f la lb) (hla : la.has_basis pa sa) :
∀ t ∈ lb, ∃ i (hi : pa i), ∀ x ∈ sa i, f x ∈ t :=
hla.tendsto_left_iff.1 H
lemma tendsto.basis_right (H : tendsto f la lb) (hlb : lb.has_basis pb sb) :
∀ i (hi : pb i), ∀ᶠ x in la, f x ∈ sb i :=
hlb.tendsto_right_iff.1 H
lemma tendsto.basis_both (H : tendsto f la lb) (hla : la.has_basis pa sa)
(hlb : lb.has_basis pb sb) :
∀ ib (hib : pb ib), ∃ ia (hia : pa ia), ∀ x ∈ sa ia, f x ∈ sb ib :=
(hla.tendsto_iff hlb).1 H
lemma has_basis.prod (hla : la.has_basis pa sa) (hlb : lb.has_basis pb sb) :
(la ×ᶠ lb).has_basis (λ i : ι × ι', pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) :=
(hla.comap prod.fst).inf (hlb.comap prod.snd)
lemma has_basis.prod' {la : filter α} {lb : filter β} {ι : Type*} {p : ι → Prop}
{sa : ι → set α} {sb : ι → set β}
(hla : la.has_basis p sa) (hlb : lb.has_basis p sb)
(h_dir : ∀ {i j}, p i → p j → ∃ k, p k ∧ sa k ⊆ sa i ∧ sb k ⊆ sb j) :
(la ×ᶠ lb).has_basis p (λ i, (sa i).prod (sb i)) :=
⟨begin
intros t,
rw mem_prod_iff,
split,
{ rintros ⟨u, u_in, v, v_in, huv⟩,
rcases hla.mem_iff.mp u_in with ⟨i, hi, si⟩,
rcases hlb.mem_iff.mp v_in with ⟨j, hj, sj⟩,
rcases h_dir hi hj with ⟨k, hk, ki, kj⟩,
use [k, hk],
calc
(sa k).prod (sb k) ⊆ (sa i).prod (sb j) : set.prod_mono ki kj
... ⊆ u.prod v : set.prod_mono si sj
... ⊆ t : huv, },
{ rintro ⟨i, hi, h⟩,
exact ⟨sa i, hla.mem_of_mem hi, sb i, hlb.mem_of_mem hi, h⟩ },
end⟩
end two_types
/-- `is_countably_generated f` means `f = generate s` for some countable `s`. -/
def is_countably_generated (f : filter α) : Prop :=
∃ s : set (set α), countable s ∧ f = generate s
/-- `is_countable_basis p s` means the image of `s` bounded by `p` is a countable filter basis. -/
structure is_countable_basis (p : ι → Prop) (s : ι → set α) extends is_basis p s : Prop :=
(countable : countable $ set_of p)
/-- We say that a filter `l` has a countable basis `s : ι → set α` bounded by `p : ι → Prop`,
if `t ∈ l` if and only if `t` includes `s i` for some `i` such that `p i`, and the set
defined by `p` is countable. -/
structure has_countable_basis (l : filter α) (p : ι → Prop) (s : ι → set α)
extends has_basis l p s : Prop :=
(countable : countable $ set_of p)
/-- A countable filter basis `B` on a type `α` is a nonempty countable collection of sets of `α`
such that the intersection of two elements of this collection contains some element
of the collection. -/
structure countable_filter_basis (α : Type*) extends filter_basis α :=
(countable : countable sets)
-- For illustration purposes, the countable filter basis defining (at_top : filter ℕ)
instance nat.inhabited_countable_filter_basis : inhabited (countable_filter_basis ℕ) :=
⟨{ countable := countable_range (λ n, Ici n),
..(default $ filter_basis ℕ),}⟩
lemma antimono_seq_of_seq (s : ℕ → set α) :
∃ t : ℕ → set α, (∀ i j, i ≤ j → t j ⊆ t i) ∧ (⨅ i, 𝓟 $ s i) = ⨅ i, 𝓟 (t i) :=
begin
use λ n, ⋂ m ≤ n, s m, split,
{ exact λ i j hij, bInter_mono' (Iic_subset_Iic.2 hij) (λ n hn, subset.refl _) },
apply le_antisymm; rw le_infi_iff; intro i,
{ rw le_principal_iff, refine (bInter_mem_sets (finite_le_nat _)).2 (λ j hji, _),
rw ← le_principal_iff, apply infi_le_of_le j _, apply le_refl _ },
{ apply infi_le_of_le i _, rw principal_mono, intro a, simp, intro h, apply h, refl },
end
lemma countable_binfi_eq_infi_seq [complete_lattice α] {B : set ι} (Bcbl : countable B)
(Bne : B.nonempty) (f : ι → α) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
begin
rw countable_iff_exists_surjective_to_subtype Bne at Bcbl,
rcases Bcbl with ⟨g, gsurj⟩,
rw infi_subtype',
use (λ n, g n), apply le_antisymm; rw le_infi_iff,
{ intro i, apply infi_le_of_le (g i) _, apply le_refl _ },
{ intros a, rcases gsurj a with ⟨i, rfl⟩, apply infi_le }
end
lemma countable_binfi_eq_infi_seq' [complete_lattice α] {B : set ι} (Bcbl : countable B) (f : ι → α)
{i₀ : ι} (h : f i₀ = ⊤) :
∃ (x : ℕ → ι), (⨅ t ∈ B, f t) = ⨅ i, f (x i) :=
begin
cases B.eq_empty_or_nonempty with hB Bnonempty,
{ rw [hB, infi_emptyset],
use λ n, i₀,
simp [h] },
{ exact countable_binfi_eq_infi_seq Bcbl Bnonempty f }
end
lemma countable_binfi_principal_eq_seq_infi {B : set (set α)} (Bcbl : countable B) :
∃ (x : ℕ → set α), (⨅ t ∈ B, 𝓟 t) = ⨅ i, 𝓟 (x i) :=
countable_binfi_eq_infi_seq' Bcbl 𝓟 principal_univ
namespace is_countably_generated
/-- A set generating a countably generated filter. -/
def generating_set {f : filter α} (h : is_countably_generated f) :=
classical.some h
lemma countable_generating_set {f : filter α} (h : is_countably_generated f) :
countable h.generating_set :=
(classical.some_spec h).1
lemma eq_generate {f : filter α} (h : is_countably_generated f) :
f = generate h.generating_set :=
(classical.some_spec h).2
/-- A countable filter basis for a countably generated filter. -/
def countable_filter_basis {l : filter α} (h : is_countably_generated l) :
countable_filter_basis α :=
{ countable := (countable_set_of_finite_subset h.countable_generating_set).image _,
..filter_basis.of_sets (h.generating_set) }
lemma filter_basis_filter {l : filter α} (h : is_countably_generated l) :
h.countable_filter_basis.to_filter_basis.filter = l :=
begin
conv_rhs { rw h.eq_generate },
apply of_sets_filter_eq_generate,
end
lemma has_countable_basis {l : filter α} (h : is_countably_generated l) :
l.has_countable_basis (λ t, finite t ∧ t ⊆ h.generating_set) (λ t, ⋂₀ t) :=
⟨by convert has_basis_generate _ ; exact h.eq_generate,
countable_set_of_finite_subset h.countable_generating_set⟩
lemma exists_countable_infi_principal {f : filter α} (h : f.is_countably_generated) :
∃ s : set (set α), countable s ∧ f = ⨅ t ∈ s, 𝓟 t :=
begin
let B := h.countable_filter_basis,
use [B.sets, B.countable],
rw ← h.filter_basis_filter,
rw B.to_filter_basis.eq_infi_principal,
rw infi_subtype''
end
lemma exists_seq {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, f = ⨅ i, 𝓟 (x i) :=
begin
rcases cblb.exists_countable_infi_principal with ⟨B, Bcbl, rfl⟩,
exact countable_binfi_principal_eq_seq_infi Bcbl,
end
/-- If `f` is countably generated and `f.has_basis p s`, then `f` admits a decreasing basis
enumerated by natural numbers such that all sets have the form `s i`. More precisely, there is a
sequence `i n` such that `p (i n)` for all `n` and `s (i n)` is a decreasing sequence of sets which
forms a basis of `f`-/
lemma exists_antimono_subbasis {f : filter α} (cblb : f.is_countably_generated)
{p : ι → Prop} {s : ι → set α} (hs : f.has_basis p s) :
∃ x : ℕ → ι, (∀ i, p (x i)) ∧ f.has_antimono_basis (λ _, true) (λ i, s (x i)) :=
begin
rcases cblb.exists_seq with ⟨x', hx'⟩,
have : ∀ i, x' i ∈ f := λ i, hx'.symm ▸ (infi_le (λ i, 𝓟 (x' i)) i) (mem_principal_self _),
let x : ℕ → {i : ι // p i} := λ n, nat.rec_on n (hs.index _ $ this 0)
(λ n xn, (hs.index _ $ inter_mem_sets (this $ n + 1) (hs.mem_of_mem xn.coe_prop))),
have x_mono : ∀ n : ℕ, s (x n.succ) ⊆ s (x n) :=
λ n, subset.trans (hs.set_index_subset _) (inter_subset_right _ _),
replace x_mono : ∀ ⦃i j⦄, i ≤ j → s (x j) ≤ s (x i),
{ refine @monotone_of_monotone_nat (order_dual $ set α) _ _ _,
exact x_mono },
have x_subset : ∀ i, s (x i) ⊆ x' i,
{ rintro (_|i),
exacts [hs.set_index_subset _, subset.trans (hs.set_index_subset _) (inter_subset_left _ _)] },
refine ⟨λ i, x i, λ i, (x i).2, _⟩,
have : (⨅ i, 𝓟 (s (x i))).has_antimono_basis (λ _, true) (λ i, s (x i)) :=
⟨has_basis_infi_principal (directed_of_sup x_mono), λ i j _ _ hij, x_mono hij, monotone_const⟩,
convert this,
exact le_antisymm (le_infi $ λ i, le_principal_iff.2 $ by cases i; apply hs.set_index_mem)
(hx'.symm ▸ le_infi (λ i, le_principal_iff.2 $
this.to_has_basis.mem_iff.2 ⟨i, trivial, x_subset i⟩))
end
/-- A countably generated filter admits a basis formed by a monotonically decreasing sequence of
sets. -/
lemma exists_antimono_basis {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x :=
let ⟨x, hxf, hx⟩ := cblb.exists_antimono_subbasis f.basis_sets in ⟨x, hx⟩
end is_countably_generated
lemma has_countable_basis.is_countably_generated {f : filter α} {p : ι → Prop} {s : ι → set α}
(h : f.has_countable_basis p s) :
f.is_countably_generated :=
⟨{t | ∃ i, p i ∧ s i = t}, h.countable.image s, h.to_has_basis.eq_generate⟩
lemma is_countably_generated_seq (x : ℕ → set α) : is_countably_generated (⨅ i, 𝓟 $ x i) :=
begin
rcases antimono_seq_of_seq x with ⟨y, am, h⟩,
rw h,
use [range y, countable_range _],
rw (has_basis_infi_principal _).eq_generate,
{ simp [range] },
{ exact directed_of_sup am },
{ use 0 },
end
lemma is_countably_generated_of_seq {f : filter α} (h : ∃ x : ℕ → set α, f = ⨅ i, 𝓟 $ x i) :
f.is_countably_generated :=
let ⟨x, h⟩ := h in by rw h ; apply is_countably_generated_seq
lemma is_countably_generated_binfi_principal {B : set $ set α} (h : countable B) :
is_countably_generated (⨅ (s ∈ B), 𝓟 s) :=
is_countably_generated_of_seq (countable_binfi_principal_eq_seq_infi h)
lemma is_countably_generated_iff_exists_antimono_basis {f : filter α} :
is_countably_generated f ↔ ∃ x : ℕ → set α, f.has_antimono_basis (λ _, true) x :=
begin
split,
{ exact λ h, h.exists_antimono_basis },
{ rintros ⟨x, h⟩,
rw h.to_has_basis.eq_infi,
exact is_countably_generated_seq x },
end
lemma is_countably_generated_principal (s : set α) : is_countably_generated (𝓟 s) :=
begin
rw show 𝓟 s = ⨅ i : ℕ, 𝓟 s, by simp,
apply is_countably_generated_seq
end
namespace is_countably_generated
lemma inf {f g : filter α} (hf : is_countably_generated f) (hg : is_countably_generated g) :
is_countably_generated (f ⊓ g) :=
begin
rw is_countably_generated_iff_exists_antimono_basis at hf hg,
rcases hf with ⟨s, hs⟩,
rcases hg with ⟨t, ht⟩,
exact has_countable_basis.is_countably_generated
⟨hs.to_has_basis.inf ht.to_has_basis, set.countable_encodable _⟩
end
lemma inf_principal {f : filter α} (h : is_countably_generated f) (s : set α) :
is_countably_generated (f ⊓ 𝓟 s) :=
h.inf (filter.is_countably_generated_principal s)
lemma exists_antimono_seq' {f : filter α} (cblb : f.is_countably_generated) :
∃ x : ℕ → set α, (∀ i j, i ≤ j → x j ⊆ x i) ∧ ∀ {s}, (s ∈ f ↔ ∃ i, x i ⊆ s) :=
let ⟨x, hx⟩ := is_countably_generated_iff_exists_antimono_basis.mp cblb in
⟨x, λ i j, hx.decreasing trivial trivial, λ s, by simp [hx.to_has_basis.mem_iff]⟩
protected lemma comap {l : filter β} (h : l.is_countably_generated) (f : α → β) :
(comap f l).is_countably_generated :=
let ⟨x, hx_mono⟩ := h.exists_antimono_basis in
is_countably_generated_of_seq ⟨_, (hx_mono.to_has_basis.comap _).eq_infi⟩
end is_countably_generated
end filter
|
b43be4a0f3c63a923a457e2ff1200a50466fb78d | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /src/Std/Data/RBMap.lean | 07d25a63d2cbc4270cf11a53fda58c1bd75493b2 | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,410 | 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
-/
namespace Std
universes u v w w'
inductive Rbcolor where
| red | black
inductive RBNode (α : Type u) (β : α → Type v) where
| leaf : RBNode α β
| node (color : Rbcolor) (lchild : RBNode α β) (key : α) (val : β key) (rchild : RBNode α β) : RBNode α β
namespace RBNode
variables {α : Type u} {β : α → Type v} {σ : Type w}
open Std.Rbcolor Nat
def depth (f : Nat → Nat → Nat) : RBNode α β → Nat
| leaf => 0
| node _ l _ _ r => succ (f (depth f l) (depth f r))
protected def min : RBNode α β → Option (Sigma (fun k => β k))
| leaf => none
| node _ leaf k v _ => some ⟨k, v⟩
| node _ l k v _ => RBNode.min l
protected def max : RBNode α β → Option (Sigma (fun k => β k))
| leaf => none
| node _ _ k v leaf => some ⟨k, v⟩
| node _ _ k v r => RBNode.max r
@[specialize] def fold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ
| b, leaf => b
| b, node _ l k v r => fold f (f (fold f b l) k v) r
@[specialize] def foldM {m : Type w → Type w'} [Monad m] (f : σ → (k : α) → β k → m σ) : (init : σ) → RBNode α β → m σ
| b, leaf => pure b
| b, node _ l k v r => do
let b ← foldM f b l
let b ← f b k v
foldM f b r
@[inline] def forIn [Monad m] (as : RBNode α β) (init : σ) (f : (k : α) → β k → σ → m (ForInStep σ)) : m σ := do
let rec @[specialize] visit : RBNode α β → σ → m (ForInStep σ)
| leaf, b => return ForInStep.yield b
| node _ l k v r, b => do
match (← visit l b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield b =>
match (← f k v b) with
| r@(ForInStep.done _) => return r
| ForInStep.yield b => visit r b
match ← visit as init with
| ForInStep.done b => pure b
| ForInStep.yield b => pure b
@[specialize] def revFold (f : σ → (k : α) → β k → σ) : (init : σ) → RBNode α β → σ
| b, leaf => b
| b, node _ l k v r => revFold f (f (revFold f b r) k v) l
@[specialize] def all (p : (k : α) → β k → Bool) : RBNode α β → Bool
| leaf => true
| node _ l k v r => p k v && all p l && all p r
@[specialize] def any (p : (k : α) → β k → Bool) : RBNode α β → Bool
| leaf => false
| node _ l k v r => p k v || any p l || any p r
def singleton (k : α) (v : β k) : RBNode α β :=
node red leaf k v leaf
@[inline] def balance1 : (a : α) → β a → RBNode α β → RBNode α β → RBNode α β
| kv, vv, t, node _ (node red l kx vx r₁) ky vy r₂ => node red (node black l kx vx r₁) ky vy (node black r₂ kv vv t)
| kv, vv, t, node _ l₁ ky vy (node red l₂ kx vx r) => node red (node black l₁ ky vy l₂) kx vx (node black r kv vv t)
| kv, vv, t, node _ l ky vy r => node black (node red l ky vy r) kv vv t
| _, _, _, _ => leaf -- unreachable
@[inline] def balance2 : RBNode α β → (a : α) → β a → RBNode α β → RBNode α β
| t, kv, vv, node _ (node red l kx₁ vx₁ r₁) ky vy r₂ => node red (node black t kv vv l) kx₁ vx₁ (node black r₁ ky vy r₂)
| t, kv, vv, node _ l₁ ky vy (node red l₂ kx₂ vx₂ r₂) => node red (node black t kv vv l₁) ky vy (node black l₂ kx₂ vx₂ r₂)
| t, kv, vv, node _ l ky vy r => node black t kv vv (node red l ky vy r)
| _, _, _, _ => leaf -- unreachable
def isRed : RBNode α β → Bool
| node red .. => true
| _ => false
def isBlack : RBNode α β → Bool
| node black .. => true
| _ => false
section Insert
variables (lt : α → α → Bool)
@[specialize] def ins : RBNode α β → (k : α) → β k → RBNode α β
| leaf, kx, vx => node red leaf kx vx leaf
| node red a ky vy b, kx, vx =>
if lt kx ky then node red (ins a kx vx) ky vy b
else if lt ky kx then node red a ky vy (ins b kx vx)
else node red a kx vx b
| node black a ky vy b, kx, vx =>
if lt kx ky then
if isRed a then balance1 ky vy b (ins a kx vx)
else node black (ins a kx vx) ky vy b
else if lt ky kx then
if isRed b then balance2 a ky vy (ins b kx vx)
else node black a ky vy (ins b kx vx)
else
node black a kx vx b
def setBlack : RBNode α β → RBNode α β
| node _ l k v r => node black l k v r
| e => e
@[specialize] def insert (t : RBNode α β) (k : α) (v : β k) : RBNode α β :=
if isRed t then setBlack (ins lt t k v)
else ins lt t k v
end Insert
def balance₃ (a : RBNode α β) (k : α) (v : β k) (d : RBNode α β) : RBNode α β :=
match a with
| node red (node red a kx vx b) ky vy c => node red (node black a kx vx b) ky vy (node black c k v d)
| node red a kx vx (node red b ky vy c) => node red (node black a kx vx b) ky vy (node black c k v d)
| a => match d with
| node red b ky vy (node red c kz vz d) => node red (node black a k v b) ky vy (node black c kz vz d)
| node red (node red b ky vy c) kz vz d => node red (node black a k v b) ky vy (node black c kz vz d)
| _ => node black a k v d
def setRed : RBNode α β → RBNode α β
| node _ a k v b => node red a k v b
| e => e
def balLeft : RBNode α β → (k : α) → β k → RBNode α β → RBNode α β
| node red a kx vx b, k, v, r => node red (node black a kx vx b) k v r
| l, k, v, node black a ky vy b => balance₃ l k v (node red a ky vy b)
| l, k, v, node red (node black a ky vy b) kz vz c => node red (node black l k v a) ky vy (balance₃ b kz vz (setRed c))
| l, k, v, r => node red l k v r -- unreachable
def balRight (l : RBNode α β) (k : α) (v : β k) (r : RBNode α β) : RBNode α β :=
match r with
| (node red b ky vy c) => node red l k v (node black b ky vy c)
| _ => match l with
| node black a kx vx b => balance₃ (node red a kx vx b) k v r
| node red a kx vx (node black b ky vy c) => node red (balance₃ (setRed a) kx vx b) ky vy (node black c k v r)
| _ => node red l k v r -- unreachable
-- TODO: use wellfounded recursion
partial def appendTrees : RBNode α β → RBNode α β → RBNode α β
| leaf, x => x
| x, leaf => x
| node red a kx vx b, node red c ky vy d =>
match appendTrees b c with
| node red b' kz vz c' => node red (node red a kx vx b') kz vz (node red c' ky vy d)
| bc => node red a kx vx (node red bc ky vy d)
| node black a kx vx b, node black c ky vy d =>
match appendTrees b c with
| node red b' kz vz c' => node red (node black a kx vx b') kz vz (node black c' ky vy d)
| bc => balLeft a kx vx (node black bc ky vy d)
| a, node red b kx vx c => node red (appendTrees a b) kx vx c
| node red a kx vx b, c => node red a kx vx (appendTrees b c)
section Erase
variables (lt : α → α → Bool)
@[specialize] def del (x : α) : RBNode α β → RBNode α β
| leaf => leaf
| node _ a y v b =>
if lt x y then
if a.isBlack then balLeft (del x a) y v b
else node red (del x a) y v b
else if lt y x then
if b.isBlack then balRight a y v (del x b)
else node red a y v (del x b)
else appendTrees a b
@[specialize] def erase (x : α) (t : RBNode α β) : RBNode α β :=
let t := del lt x t;
t.setBlack
end Erase
section Membership
variable (lt : α → α → Bool)
@[specialize] def findCore : RBNode α β → (k : α) → Option (Sigma (fun k => β k))
| leaf, x => none
| node _ a ky vy b, x =>
if lt x ky then findCore a x
else if lt ky x then findCore b x
else some ⟨ky, vy⟩
@[specialize] def find {β : Type v} : RBNode α (fun _ => β) → α → Option β
| leaf, x => none
| node _ a ky vy b, x =>
if lt x ky then find a x
else if lt ky x then find b x
else some vy
@[specialize] def lowerBound : RBNode α β → α → Option (Sigma β) → Option (Sigma β)
| leaf, x, lb => lb
| node _ a ky vy b, x, lb =>
if lt x ky then lowerBound a x lb
else if lt ky x then lowerBound b x (some ⟨ky, vy⟩)
else some ⟨ky, vy⟩
end Membership
inductive WellFormed (lt : α → α → Bool) : RBNode α β → Prop where
| leafWff : WellFormed lt leaf
| insertWff {n n' : RBNode α β} {k : α} {v : β k} : WellFormed lt n → n' = insert lt n k v → WellFormed lt n'
| eraseWff {n n' : RBNode α β} {k : α} : WellFormed lt n → n' = erase lt k n → WellFormed lt n'
end RBNode
open Std.RBNode
/- TODO(Leo): define dRBMap -/
def RBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : Type (max u v) :=
{t : RBNode α (fun _ => β) // t.WellFormed lt }
@[inline] def mkRBMap (α : Type u) (β : Type v) (lt : α → α → Bool) : RBMap α β lt :=
⟨leaf, WellFormed.leafWff⟩
@[inline] def RBMap.empty {α : Type u} {β : Type v} {lt : α → α → Bool} : RBMap α β lt :=
mkRBMap ..
instance (α : Type u) (β : Type v) (lt : α → α → Bool) : EmptyCollection (RBMap α β lt) :=
⟨RBMap.empty⟩
namespace RBMap
variables {α : Type u} {β : Type v} {σ : Type w} {lt : α → α → Bool}
def depth (f : Nat → Nat → Nat) (t : RBMap α β lt) : Nat :=
t.val.depth f
@[inline] def fold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ
| b, ⟨t, _⟩ => t.fold f b
@[inline] def revFold (f : σ → α → β → σ) : (init : σ) → RBMap α β lt → σ
| b, ⟨t, _⟩ => t.revFold f b
@[inline] def foldM [Monad m] (f : σ → α → β → m σ) : (init : σ) → RBMap α β lt → m σ
| b, ⟨t, _⟩ => t.foldM f b
@[inline] def forM [Monad m] (f : α → β → m PUnit) (t : RBMap α β lt) : m PUnit :=
t.foldM (fun _ k v => f k v) ⟨⟩
@[inline] def forIn [Monad m] (t : RBMap α β lt) (init : σ) (f : (α × β) → σ → m (ForInStep σ)) : m σ :=
t.val.forIn init (fun a b acc => f (a, b) acc)
@[inline] def isEmpty : RBMap α β lt → Bool
| ⟨leaf, _⟩ => true
| _ => false
@[specialize] def toList : RBMap α β lt → List (α × β)
| ⟨t, _⟩ => t.revFold (fun ps k v => (k, v)::ps) []
@[inline] protected def min : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ =>
match t.min with
| some ⟨k, v⟩ => some (k, v)
| none => none
@[inline] protected def max : RBMap α β lt → Option (α × β)
| ⟨t, _⟩ =>
match t.max with
| some ⟨k, v⟩ => some (k, v)
| none => none
instance [Repr α] [Repr β] : Repr (RBMap α β lt) where
reprPrec m prec := Repr.addAppParen ("Std.rbmapOf " ++ repr m.toList) prec
@[inline] def insert : RBMap α β lt → α → β → RBMap α β lt
| ⟨t, w⟩, k, v => ⟨t.insert lt k v, WellFormed.insertWff w rfl⟩
@[inline] def erase : RBMap α β lt → α → RBMap α β lt
| ⟨t, w⟩, k => ⟨t.erase lt k, WellFormed.eraseWff w rfl⟩
@[specialize] def ofList : List (α × β) → RBMap α β lt
| [] => mkRBMap ..
| ⟨k,v⟩::xs => (ofList xs).insert k v
@[inline] def findCore? : RBMap α β lt → α → Option (Sigma (fun (k : α) => β))
| ⟨t, _⟩, x => t.findCore lt x
@[inline] def find? : RBMap α β lt → α → Option β
| ⟨t, _⟩, x => t.find lt x
@[inline] def findD (t : RBMap α β lt) (k : α) (v₀ : β) : β :=
(t.find? k).getD v₀
/-- (lowerBound k) retrieves the kv pair of the largest key smaller than or equal to `k`,
if it exists. -/
@[inline] def lowerBound : RBMap α β lt → α → Option (Sigma (fun (k : α) => β))
| ⟨t, _⟩, x => t.lowerBound lt x none
@[inline] def contains (t : RBMap α β lt) (a : α) : Bool :=
(t.find? a).isSome
@[inline] def fromList (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
l.foldl (fun r p => r.insert p.1 p.2) (mkRBMap α β lt)
@[inline] def all : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩, p => t.all p
@[inline] def any : RBMap α β lt → (α → β → Bool) → Bool
| ⟨t, _⟩, p => t.any p
def size (m : RBMap α β lt) : Nat :=
m.fold (fun sz _ _ => sz+1) 0
def maxDepth (t : RBMap α β lt) : Nat :=
t.val.depth Nat.max
@[inline] def min! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β :=
match t.min with
| some p => p
| none => panic! "map is empty"
@[inline] def max! [Inhabited α] [Inhabited β] (t : RBMap α β lt) : α × β :=
match t.max with
| some p => p
| none => panic! "map is empty"
@[inline] def find! [Inhabited β] (t : RBMap α β lt) (k : α) : β :=
match t.find? k with
| some b => b
| none => panic! "key is not in the map"
end RBMap
def rbmapOf {α : Type u} {β : Type v} (l : List (α × β)) (lt : α → α → Bool) : RBMap α β lt :=
RBMap.fromList l lt
end Std
|
c617bed09d6c7f40aad49cd62e472b6b4ad193af | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/category_theory/limits/kan_extension.lean | 7fdb3dc909db4cd1a90c2439d8bb41f6c57be1aa | [
"Apache-2.0"
] | permissive | jjgarzella/mathlib | 96a345378c4e0bf26cf604aed84f90329e4896a2 | 395d8716c3ad03747059d482090e2bb97db612c8 | refs/heads/master | 1,686,480,124,379 | 1,625,163,323,000 | 1,625,163,323,000 | 281,190,421 | 2 | 0 | Apache-2.0 | 1,595,268,170,000 | 1,595,268,169,000 | null | UTF-8 | Lean | false | false | 8,209 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Adam Topaz
-/
import category_theory.punit
import category_theory.structured_arrow
import category_theory.limits.functor_category
import category_theory.limits.shapes.terminal
/-!
# Kan extensions
This file defines the right and left Kan extensions of a functor.
They exist under the assumption that the target category has enough limits
resp. colimits.
The main definitions are `Ran ι` and `Lan ι`, where `ι : S ⥤ L` is a functor.
Namely, `Ran ι` is the right Kan extension, while `Lan ι` is the left Kan extension,
both as functors `(S ⥤ D) ⥤ (L ⥤ D)`.
To access the right resp. left adjunction associated to these, use `Ran.adjunction`
resp. `Lan.adjunction`.
# Projects
A lot of boilerplate could be generalized by defining and working with pseudofunctors.
-/
noncomputable theory
namespace category_theory
open limits
universes v u₁ u₂ u₃
variables {S : Type v} {L : Type u₂} {D : Type u₃}
variables [category.{v} S] [category.{v} L] [category.{v} D]
variables (ι : S ⥤ L)
namespace Ran
local attribute [simp] structured_arrow.proj
/-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/
abbreviation diagram (F : S ⥤ D) (x : L) : structured_arrow x ι ⥤ D :=
structured_arrow.proj x ι ⋙ F
variable {ι}
/-- A cone over `Ran.diagram ι F x` used to define `Ran`. -/
@[simp]
def cone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : ι ⋙ G ⟶ F) :
cone (diagram ι F x) :=
{ X := G.obj x,
π :=
{ app := λ i, G.map i.hom ≫ f.app i.right,
naturality' := begin
rintro ⟨⟨il⟩, ir, i⟩ ⟨⟨jl⟩, jr, j⟩ ⟨⟨⟨fl⟩⟩, fr, ff⟩,
dsimp at *,
simp only [category.id_comp, category.assoc] at *,
rw [ff],
have := f.naturality,
tidy,
end } }
variable (ι)
/-- An auxiliary definition used to define `Ran`. -/
@[simps]
def loc (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] : L ⥤ D :=
{ obj := λ x, limit (diagram ι F x),
map := λ x y f, limit.pre (diagram _ _ _) (structured_arrow.map f : structured_arrow _ ι ⥤ _),
map_id' := begin
intro l,
ext j,
simp only [category.id_comp, limit.pre_π],
congr' 1,
simp,
end,
map_comp' := begin
intros x y z f g,
ext j,
erw [limit.pre_pre, limit.pre_π, limit.pre_π],
congr' 1,
tidy,
end }
/-- An auxiliary definition used to define `Ran` and `Ran.adjunction`. -/
@[simps]
def equiv (F : S ⥤ D) [∀ x, has_limit (diagram ι F x)] (G : L ⥤ D) :
(G ⟶ loc ι F) ≃ (((whiskering_left _ _ _).obj ι).obj G ⟶ F) :=
{ to_fun := λ f,
{ app := λ x, f.app _ ≫ limit.π (diagram ι F (ι.obj x)) (structured_arrow.mk (𝟙 _)),
naturality' := begin
intros x y ff,
dsimp only [whiskering_left],
simp only [functor.comp_map, nat_trans.naturality_assoc, loc_map, category.assoc],
congr' 1,
erw limit.pre_π,
change _ = _ ≫ (diagram ι F (ι.obj x)).map (structured_arrow.hom_mk _ _),
rw limit.w,
tidy,
end },
inv_fun := λ f,
{ app := λ x, limit.lift (diagram ι F x) (cone _ f),
naturality' := begin
intros x y ff,
ext j,
erw [limit.lift_pre, limit.lift_π, category.assoc, limit.lift_π (cone _ f) j],
tidy,
end },
left_inv := begin
intro x,
ext k j,
dsimp only [cone],
rw limit.lift_π,
simp only [nat_trans.naturality_assoc, loc_map],
erw limit.pre_π,
congr,
cases j,
tidy,
end,
right_inv := by tidy }
end Ran
/-- The right Kan extension of a functor. -/
@[simps]
def Ran [∀ X, has_limits_of_shape (structured_arrow X ι) D] : (S ⥤ D) ⥤ L ⥤ D :=
adjunction.right_adjoint_of_equiv (λ F G, (Ran.equiv ι G F).symm) (by tidy)
namespace Ran
variable (D)
/-- The adjunction associated to `Ran`. -/
def adjunction [∀ X, has_limits_of_shape (structured_arrow X ι) D] :
(whiskering_left _ _ D).obj ι ⊣ Ran ι :=
adjunction.adjunction_of_equiv_right _ _
end Ran
namespace Lan
local attribute [simp] costructured_arrow.proj
/-- The diagram indexed by `Ran.index ι x` used to define `Ran`. -/
abbreviation diagram (F : S ⥤ D) (x : L) : costructured_arrow ι x ⥤ D :=
costructured_arrow.proj ι x ⋙ F
variable {ι}
/-- A cocone over `Lan.diagram ι F x` used to define `Lan`. -/
@[simp]
def cocone {F : S ⥤ D} {G : L ⥤ D} (x : L) (f : F ⟶ ι ⋙ G) :
cocone (diagram ι F x) :=
{ X := G.obj x,
ι :=
{ app := λ i, f.app i.left ≫ G.map i.hom,
naturality' := begin
rintro ⟨ir, ⟨il⟩, i⟩ ⟨jl, ⟨jr⟩, j⟩ ⟨fl, ⟨⟨fl⟩⟩, ff⟩,
dsimp at *,
simp only [functor.comp_map, category.comp_id, nat_trans.naturality_assoc],
rw [← G.map_comp, ff],
tidy,
end } }
variable (ι)
/-- An auxiliary definition used to define `Lan`. -/
@[simps]
def loc (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] : L ⥤ D :=
{ obj := λ x, colimit (diagram ι F x),
map := λ x y f,
colimit.pre (diagram _ _ _) (costructured_arrow.map f : costructured_arrow ι _ ⥤ _),
map_id' := begin
intro l,
ext j,
erw [colimit.ι_pre, category.comp_id],
congr' 1,
simp,
end,
map_comp' := begin
intros x y z f g,
ext j,
let ff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map f,
let gg : costructured_arrow ι _ ⥤ _ := costructured_arrow.map g,
let dd := diagram ι F z,
-- I don't know why lean can't deduce the following three instances...
haveI : has_colimit (ff ⋙ gg ⋙ dd) := I _,
haveI : has_colimit ((ff ⋙ gg) ⋙ dd) := I _,
haveI : has_colimit (gg ⋙ dd) := I _,
change _ = colimit.ι ((ff ⋙ gg) ⋙ dd) j ≫ _ ≫ _,
erw [colimit.pre_pre dd gg ff, colimit.ι_pre, colimit.ι_pre],
congr' 1,
simp,
end }
/-- An auxiliary definition used to define `Lan` and `Lan.adjunction`. -/
@[simps]
def equiv (F : S ⥤ D) [I : ∀ x, has_colimit (diagram ι F x)] (G : L ⥤ D) :
(loc ι F ⟶ G) ≃ (F ⟶ ((whiskering_left _ _ _).obj ι).obj G) :=
{ to_fun := λ f,
{ app := λ x,
by apply colimit.ι (diagram ι F (ι.obj x)) (costructured_arrow.mk (𝟙 _)) ≫ f.app _, -- sigh
naturality' := begin
intros x y ff,
dsimp only [whiskering_left],
simp only [functor.comp_map, category.assoc],
rw [← f.naturality (ι.map ff), ← category.assoc, ← category.assoc],
let fff : costructured_arrow ι _ ⥤ _ := costructured_arrow.map (ι.map ff),
-- same issue :-(
haveI : has_colimit (fff ⋙ diagram ι F (ι.obj y)) := I _,
erw colimit.ι_pre (diagram ι F (ι.obj y)) fff (costructured_arrow.mk (𝟙 _)),
let xx : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (ι.map ff),
let yy : costructured_arrow ι (ι.obj y) := costructured_arrow.mk (𝟙 _),
let fff : xx ⟶ yy := costructured_arrow.hom_mk ff
(by {simp only [costructured_arrow.mk_hom_eq_self], erw category.comp_id}),
erw colimit.w (diagram ι F (ι.obj y)) fff,
congr,
simp,
end },
inv_fun := λ f,
{ app := λ x, colimit.desc (diagram ι F x) (cocone _ f),
naturality' := begin
intros x y ff,
ext j,
erw [colimit.pre_desc, ← category.assoc, colimit.ι_desc, colimit.ι_desc],
tidy,
end },
left_inv := begin
intro x,
ext k j,
rw colimit.ι_desc,
dsimp only [cocone],
rw [category.assoc, ← x.naturality j.hom, ← category.assoc],
congr' 1,
change colimit.ι _ _ ≫ colimit.pre (diagram ι F k) (costructured_arrow.map _) = _,
rw colimit.ι_pre,
congr,
cases j,
tidy,
end,
right_inv := by tidy }
end Lan
/-- The left Kan extension of a functor. -/
@[simps]
def Lan [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] : (S ⥤ D) ⥤ L ⥤ D :=
adjunction.left_adjoint_of_equiv (λ F G, Lan.equiv ι F G) (by tidy)
namespace Lan
variable (D)
/-- The adjunction associated to `Lan`. -/
def adjunction [∀ X, has_colimits_of_shape (costructured_arrow ι X) D] :
Lan ι ⊣ (whiskering_left _ _ D).obj ι :=
adjunction.adjunction_of_equiv_left _ _
end Lan
end category_theory
|
700c3b0deaeb56313ec782ef1ec8aa04d0056f67 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/number_theory/bertrand.lean | dd790a5440843dc048a4b66288bd5bfb2be4139e | [
"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,244 | lean | /-
Copyright (c) 2020 Patrick Stevens. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Stevens, Bolton Bailey
-/
import data.nat.choose.factorization
import number_theory.primorial
import analysis.convex.specific_functions
/-!
# Bertrand's Postulate
This file contains a proof of Bertrand's postulate: That between any positive number and its
double there is a prime.
The proof follows the outline of the Erdős proof presented in "Proofs from THE BOOK": One considers
the prime factorization of `(2 * n).choose n`, and splits the constituent primes up into various
groups, then upper bounds the contribution of each group. This upper bounds the central binomial
coefficient, and if the postulate does not hold, this upper bound conflicts with a simple lower
bound for large enough `n`. This proves the result holds for large enough `n`, and for smaller `n`
an explicit list of primes is provided which covers the remaining cases.
As in the [Metamath implementation](carneiro2015arithmetic), we rely on some optimizations from
[Shigenori Tochiori](tochiori_bertrand). In particular we use the cleaner bound on the central
binomial coefficient given in `nat.four_pow_lt_mul_central_binom`.
## References
* [M. Aigner and G. M. Ziegler _Proofs from THE BOOK_][aigner1999proofs]
* [S. Tochiori, _Considering the Proof of “There is a Prime between n and 2n”_][tochiori_bertrand]
* [M. Carneiro, _Arithmetic in Metamath, Case Study: Bertrand's Postulate_][carneiro2015arithmetic]
## Tags
Bertrand, prime, binomial coefficients
-/
open_locale big_operators
section real
open real
namespace bertrand
/--
A reified version of the `bertrand.main_inequality` below.
This is not best possible: it actually holds for 464 ≤ x.
-/
lemma real_main_inequality {x : ℝ} (n_large : (512 : ℝ) ≤ x) :
x * (2 * x) ^ (sqrt (2 * x)) * 4 ^ (2 * x / 3) ≤ 4 ^ x :=
begin
let f : ℝ → ℝ := λ x, log x + sqrt (2 * x) * log (2 * x) - log 4 / 3 * x,
have hf' : ∀ x, 0 < x → 0 < x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3) :=
λ x h, div_pos (mul_pos h (rpow_pos_of_pos (mul_pos two_pos h) _)) (rpow_pos_of_pos four_pos _),
have hf : ∀ x, 0 < x → f x = log (x * (2 * x) ^ sqrt (2 * x) / 4 ^ (x / 3)),
{ intros x h5,
have h6 := mul_pos two_pos h5,
have h7 := rpow_pos_of_pos h6 (sqrt (2 * x)),
rw [log_div (mul_pos h5 h7).ne' (rpow_pos_of_pos four_pos _).ne', log_mul h5.ne' h7.ne',
log_rpow h6, log_rpow zero_lt_four, ← mul_div_right_comm, ← mul_div, mul_comm x] },
have h5 : 0 < x := lt_of_lt_of_le (by norm_num1) n_large,
rw [← div_le_one (rpow_pos_of_pos four_pos x), ← div_div_eq_mul_div, ← rpow_sub four_pos,
← mul_div 2 x, mul_div_left_comm, ← mul_one_sub, (by norm_num1 : (1 : ℝ) - 2 / 3 = 1 / 3),
mul_one_div, ← log_nonpos_iff (hf' x h5), ← hf x h5],
have h : concave_on ℝ (set.Ioi 0.5) f,
{ refine ((strict_concave_on_log_Ioi.concave_on.subset (set.Ioi_subset_Ioi _)
(convex_Ioi 0.5)).add ((strict_concave_on_sqrt_mul_log_Ioi.concave_on.comp_linear_map
((2 : ℝ) • linear_map.id)).subset
(λ a ha, lt_of_eq_of_lt _ ((mul_lt_mul_left two_pos).mpr ha)) (convex_Ioi 0.5))).sub
((convex_on_id (convex_Ioi (0.5 : ℝ))).smul (div_nonneg (log_nonneg _) _)); norm_num1 },
suffices : ∃ x1 x2, 0.5 < x1 ∧ x1 < x2 ∧ x2 ≤ x ∧ 0 ≤ f x1 ∧ f x2 ≤ 0,
{ obtain ⟨x1, x2, h1, h2, h0, h3, h4⟩ := this,
exact (h.right_le_of_le_left'' h1 ((h1.trans h2).trans_le h0) h2 h0 (h4.trans h3)).trans h4 },
refine ⟨18, 512, by norm_num1, by norm_num1, le_trans (by norm_num1) n_large, _, _⟩,
{ have : sqrt (2 * 18) = 6 :=
(sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1),
rw [hf, log_nonneg_iff (hf' 18 _), this]; norm_num1 },
{ have : sqrt (2 * 512) = 32,
{ exact (sqrt_eq_iff_mul_self_eq_of_pos (by norm_num1)).mpr (by norm_num1) },
rw [hf, log_nonpos_iff (hf' _ _), this, div_le_one (rpow_pos_of_pos four_pos _),
← rpow_le_rpow_iff _ (rpow_pos_of_pos four_pos _).le three_pos, ← rpow_mul]; norm_num1 },
end
end bertrand
end real
section nat
open nat
/--
The inequality which contradicts Bertrand's postulate, for large enough `n`.
-/
lemma bertrand_main_inequality {n : ℕ} (n_large : 512 ≤ n) :
n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n :=
begin
rw ← @cast_le ℝ,
simp only [cast_bit0, cast_add, cast_one, cast_mul, cast_pow, ← real.rpow_nat_cast],
have n_pos : 0 < n := (dec_trivial : 0 < 512).trans_le n_large,
have n2_pos : 1 ≤ 2 * n := mul_pos dec_trivial n_pos,
refine trans (mul_le_mul _ _ _ _) (bertrand.real_main_inequality (by exact_mod_cast n_large)),
{ refine mul_le_mul_of_nonneg_left _ (nat.cast_nonneg _),
refine real.rpow_le_rpow_of_exponent_le (by exact_mod_cast n2_pos) _,
exact_mod_cast real.nat_sqrt_le_real_sqrt },
{ exact real.rpow_le_rpow_of_exponent_le (by norm_num1) (cast_div_le.trans (by norm_cast)) },
{ exact real.rpow_nonneg_of_nonneg (by norm_num1) _ },
{ refine mul_nonneg (nat.cast_nonneg _) _,
exact real.rpow_nonneg_of_nonneg (mul_nonneg zero_le_two (nat.cast_nonneg _)) _, },
end
/--
A lemma that tells us that, in the case where Bertrand's postulate does not hold, the prime
factorization of the central binomial coefficent only has factors at most `2 * n / 3 + 1`.
-/
lemma central_binom_factorization_small (n : ℕ) (n_large : 2 < n)
(no_prime: ¬∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n) :
central_binom n = ∏ p in finset.range (2 * n / 3 + 1), p ^ ((central_binom n).factorization p) :=
begin
refine (eq.trans _ n.prod_pow_factorization_central_binom).symm,
apply finset.prod_subset,
{ exact finset.range_subset.2 (add_le_add_right (nat.div_le_self _ _) _) },
intros x hx h2x,
rw [finset.mem_range, lt_succ_iff] at hx h2x,
rw [not_le, div_lt_iff_lt_mul' three_pos, mul_comm x] at h2x,
replace no_prime := not_exists.mp no_prime x,
rw [←and_assoc, not_and', not_and_distrib, not_lt] at no_prime,
cases no_prime hx with h h,
{ rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] },
{ rw [factorization_central_binom_of_two_mul_self_lt_three_mul n_large h h2x, pow_zero] },
end
/--
An upper bound on the central binomial coefficient used in the proof of Bertrand's postulate.
The bound splits the prime factors of `central_binom n` into those
1. At most `sqrt (2 * n)`, which contribute at most `2 * n` for each such prime.
2. Between `sqrt (2 * n)` and `2 * n / 3`, which contribute at most `4^(2 * n / 3)` in total.
3. Between `2 * n / 3` and `n`, which do not exist.
4. Between `n` and `2 * n`, which would not exist in the case where Bertrand's postulate is false.
5. Above `2 * n`, which do not exist.
-/
lemma central_binom_le_of_no_bertrand_prime (n : ℕ) (n_big : 2 < n)
(no_prime : ¬∃ (p : ℕ), nat.prime p ∧ n < p ∧ p ≤ 2 * n) :
central_binom n ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) :=
begin
have n_pos : 0 < n := (nat.zero_le _).trans_lt n_big,
have n2_pos : 1 ≤ 2 * n := mul_pos two_pos n_pos,
let S := (finset.range (2 * n / 3 + 1)).filter nat.prime,
let f := λ x, x ^ n.central_binom.factorization x,
have : ∏ (x : ℕ) in S, f x = ∏ (x : ℕ) in finset.range (2 * n / 3 + 1), f x,
{ refine finset.prod_filter_of_ne (λ p hp h, _),
contrapose! h, dsimp only [f],
rw [factorization_eq_zero_of_non_prime n.central_binom h, pow_zero] },
rw [central_binom_factorization_small n n_big no_prime, ← this,
← finset.prod_filter_mul_prod_filter_not S (≤ sqrt (2 * n))],
apply mul_le_mul',
{ refine (finset.prod_le_prod'' (λ p hp, (_ : f p ≤ 2 * n))).trans _,
{ exact pow_factorization_choose_le (mul_pos two_pos n_pos) },
have : (finset.Icc 1 (sqrt (2 * n))).card = sqrt (2 * n),
{ rw [card_Icc, nat.add_sub_cancel] },
rw finset.prod_const,
refine pow_le_pow n2_pos ((finset.card_le_of_subset (λ x hx, _)).trans this.le),
obtain ⟨h1, h2⟩ := finset.mem_filter.1 hx,
exact finset.mem_Icc.mpr ⟨(finset.mem_filter.1 h1).2.one_lt.le, h2⟩ },
{ refine le_trans _ (primorial_le_4_pow (2 * n / 3)),
refine (finset.prod_le_prod' (λ p hp, (_ : f p ≤ p))).trans _,
{ obtain ⟨h1, h2⟩ := finset.mem_filter.1 hp,
refine (pow_le_pow (finset.mem_filter.1 h1).2.one_lt.le _).trans (pow_one p).le,
exact nat.factorization_choose_le_one (sqrt_lt'.mp $ not_le.1 h2) },
refine finset.prod_le_prod_of_subset_of_one_le' (finset.filter_subset _ _) _,
exact λ p hp _, (finset.mem_filter.1 hp).2.one_lt.le }
end
namespace nat
/--
Proves that Bertrand's postulate holds for all sufficiently large `n`.
-/
lemma exists_prime_lt_and_le_two_mul_eventually (n : ℕ) (n_big : 512 ≤ n) :
∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n :=
begin
-- Assume there is no prime in the range.
by_contradiction no_prime,
-- Then we have the above sub-exponential bound on the size of this central binomial coefficient.
-- We now couple this bound with an exponential lower bound on the central binomial coefficient,
-- yielding an inequality which we have seen is false for large enough n.
have H1 : n * (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) ≤ 4 ^ n := bertrand_main_inequality n_big,
have H2 : 4 ^ n < n * n.central_binom :=
nat.four_pow_lt_mul_central_binom n (le_trans (by norm_num1) n_big),
have H3 : n.central_binom ≤ (2 * n) ^ sqrt (2 * n) * 4 ^ (2 * n / 3) :=
central_binom_le_of_no_bertrand_prime n (lt_of_lt_of_le (by norm_num1) n_big) no_prime,
rw mul_assoc at H1, exact not_le.2 H2 ((mul_le_mul_left' H3 n).trans H1),
end
/--
Proves that Bertrand's postulate holds over all positive naturals less than n by identifying a
descending list of primes, each no more than twice the next, such that the list contains a witness
for each number ≤ n.
-/
lemma exists_prime_lt_and_le_two_mul_succ {n} (q)
{p : ℕ} (prime_p : nat.prime p) (covering : p ≤ 2 * q)
(H : n < q → ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n)
(hn : n < p) : ∃ (p : ℕ), p.prime ∧ n < p ∧ p ≤ 2 * n :=
begin
by_cases p ≤ 2 * n, { exact ⟨p, prime_p, hn, h⟩ },
exact H (lt_of_mul_lt_mul_left' (lt_of_lt_of_le (not_le.1 h) covering))
end
/--
**Bertrand's Postulate**: For any positive natural number, there is a prime which is greater than
it, but no more than twice as large.
-/
theorem exists_prime_lt_and_le_two_mul (n : ℕ) (hn0 : n ≠ 0) :
∃ p, nat.prime p ∧ n < p ∧ p ≤ 2 * n :=
begin
-- Split into cases whether `n` is large or small
cases lt_or_le 511 n,
-- If `n` is large, apply the lemma derived from the inequalities on the central binomial
-- coefficient.
{ exact exists_prime_lt_and_le_two_mul_eventually n h, },
replace h : n < 521 := h.trans_lt (by norm_num1),
revert h,
-- For small `n`, supply a list of primes to cover the initial cases.
([317, 163, 83, 43, 23, 13, 7, 5, 3, 2].mmap' $ λ n,
`[refine exists_prime_lt_and_le_two_mul_succ %%(reflect n) (by norm_num1) (by norm_num1) _]),
exact λ h2, ⟨2, prime_two, h2, nat.mul_le_mul_left 2 (nat.pos_of_ne_zero hn0)⟩,
end
alias nat.exists_prime_lt_and_le_two_mul ← bertrand
end nat
end nat
|
7b279cdfeaee64617349e2285c2e073bcbd56f52 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/meta/backward.lean | 882ea3e31d0fbc3910ff972e8b99e5a46f6cc7e1 | [
"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 | 3,067 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.tactic init.meta.set_get_option_tactics
namespace tactic
meta_constant back_lemmas : Type
/- Create a datastructure containing all lemmas tagged as [intro].
Lemmas are indexed using their head-symbol.
The head-symbol is computed with respect to the given transparency setting. -/
meta_constant mk_back_lemmas_core : transparency → tactic back_lemmas
/- (back_lemmas_insert_core m lemmas lemma) adds the given lemma to the set back_lemmas.
It infers the type of the lemma, and uses its head-symbol as an index.
The head-symbol is computed with respect to the given transparency setting. -/
meta_constant back_lemmas_insert_core : transparency → back_lemmas → expr → tactic back_lemmas
/- Return the lemmas that have the same head symbol of the given expression -/
meta_constant back_lemmas_find : back_lemmas → expr → tactic (list expr)
meta_definition mk_back_lemmas : tactic back_lemmas :=
mk_back_lemmas_core reducible
meta_definition back_lemmas_insert : back_lemmas → expr → tactic back_lemmas :=
back_lemmas_insert_core reducible
/- (backward_chaining_core t insts max_depth pre_tactic leaf_tactic lemmas): perform backward chaining using
the lemmas marked as [intro] and extra_lemmas.
The search maximum depth is \c max_depth.
Before processing each goal, the tactic pre_tactic is invoked. The possible outcomes are:
1) it closes the goal
2) it does nothing, and backward_chaining_core tries applicable lemmas.
3) it fails, and backward_chaining_core backtracks.
Whenever no lemma is applicable, the leaf_tactic is invoked, to try to close the goal.
If insts is tt, then type class resolution is used to discharge goals.
Remark pre_tactic may also be used to trace the execution of backward_chaining_core -/
meta_constant backward_chaining_core : transparency → bool → nat → tactic unit → tactic unit → back_lemmas → tactic unit
meta_definition back_lemmas_add_extra : transparency → back_lemmas → list expr → tactic back_lemmas
| m bls [] := return bls
| m bls (l::ls) := do
new_bls ← back_lemmas_insert_core m bls l,
back_lemmas_add_extra m new_bls ls
meta_definition back_chaining_core (pre_tactic : tactic unit) (leaf_tactic : tactic unit) (extra_lemmas : list expr) : tactic unit :=
do intro_lemmas ← mk_back_lemmas_core reducible,
new_lemmas ← back_lemmas_add_extra reducible intro_lemmas extra_lemmas,
max ← get_nat_option `back_chaining.max_depth 8,
backward_chaining_core reducible tt max pre_tactic leaf_tactic new_lemmas
meta_definition back_chaining : tactic unit :=
back_chaining_core skip assumption []
meta_definition back_chaining_using : list expr → tactic unit :=
back_chaining_core skip assumption
meta_definition back_chaining_using_hs : tactic unit :=
local_context >>= back_chaining_core skip failed
end tactic
|
4b2da98360077f29c91ec6d299a04ca5176b2f86 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /stage0/src/Std/Data/PersistentHashMap.lean | e47c704c41e51adee12d30ee8525d1ec5289f347 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 13,294 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
namespace Std
universes u v w w'
namespace PersistentHashMap
inductive Entry (α : Type u) (β : Type v) (σ : Type w) where
| entry (key : α) (val : β) : Entry α β σ
| ref (node : σ) : Entry α β σ
| null : Entry α β σ
instance {α β σ} : Inhabited (Entry α β σ) := ⟨Entry.null⟩
inductive Node (α : Type u) (β : Type v) : Type (max u v) where
| entries (es : Array (Entry α β (Node α β))) : Node α β
| collision (ks : Array α) (vs : Array β) (h : ks.size = vs.size) : Node α β
instance {α β} : Inhabited (Node α β) := ⟨Node.entries #[]⟩
abbrev shift : USize := 5
abbrev branching : USize := USize.ofNat (2 ^ shift.toNat)
abbrev maxDepth : USize := 7
abbrev maxCollisions : Nat := 4
def mkEmptyEntriesArray {α β} : Array (Entry α β (Node α β)) :=
(Array.mkArray PersistentHashMap.branching.toNat PersistentHashMap.Entry.null)
end PersistentHashMap
structure PersistentHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] where
root : PersistentHashMap.Node α β := PersistentHashMap.Node.entries PersistentHashMap.mkEmptyEntriesArray
size : Nat := 0
abbrev PHashMap (α : Type u) (β : Type v) [BEq α] [Hashable α] := PersistentHashMap α β
namespace PersistentHashMap
variable {α : Type u} {β : Type v}
def empty [BEq α] [Hashable α] : PersistentHashMap α β := {}
def isEmpty [BEq α] [Hashable α] (m : PersistentHashMap α β) : Bool :=
m.size == 0
instance [BEq α] [Hashable α] : Inhabited (PersistentHashMap α β) := ⟨{}⟩
def mkEmptyEntries {α β} : Node α β :=
Node.entries mkEmptyEntriesArray
abbrev mul2Shift (i : USize) (shift : USize) : USize := i.shiftLeft shift
abbrev div2Shift (i : USize) (shift : USize) : USize := i.shiftRight shift
abbrev mod2Shift (i : USize) (shift : USize) : USize := USize.land i ((USize.shiftLeft 1 shift) - 1)
inductive IsCollisionNode : Node α β → Prop where
| mk (keys : Array α) (vals : Array β) (h : keys.size = vals.size) : IsCollisionNode (Node.collision keys vals h)
abbrev CollisionNode (α β) := { n : Node α β // IsCollisionNode n }
inductive IsEntriesNode : Node α β → Prop where
| mk (entries : Array (Entry α β (Node α β))) : IsEntriesNode (Node.entries entries)
abbrev EntriesNode (α β) := { n : Node α β // IsEntriesNode n }
private theorem size_set {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (i : Fin ks.size) (j : Fin vs.size) (k : α) (v : β)
: (ks.set i k).size = (vs.set j v).size := by
simp [h]
private theorem size_push {ks : Array α} {vs : Array β} (h : ks.size = vs.size) (k : α) (v : β) : (ks.push k).size = (vs.push v).size := by
simp [h]
partial def insertAtCollisionNodeAux [BEq α] : CollisionNode α β → Nat → α → β → CollisionNode α β
| n@⟨Node.collision keys vals heq, _⟩, i, k, v =>
if h : i < keys.size then
let idx : Fin keys.size := ⟨i, h⟩;
let k' := keys.get idx;
if k == k' then
let j : Fin vals.size := ⟨i, by rw [←heq]; assumption⟩
⟨Node.collision (keys.set idx k) (vals.set j v) (size_set heq idx j k v), IsCollisionNode.mk _ _ _⟩
else insertAtCollisionNodeAux n (i+1) k v
else
⟨Node.collision (keys.push k) (vals.push v) (size_push heq k v), IsCollisionNode.mk _ _ _⟩
| ⟨Node.entries _, h⟩, _, _, _ => False.elim (nomatch h)
def insertAtCollisionNode [BEq α] : CollisionNode α β → α → β → CollisionNode α β :=
fun n k v => insertAtCollisionNodeAux n 0 k v
def getCollisionNodeSize : CollisionNode α β → Nat
| ⟨Node.collision keys _ _, _⟩ => keys.size
| ⟨Node.entries _, h⟩ => False.elim (nomatch h)
def mkCollisionNode (k₁ : α) (v₁ : β) (k₂ : α) (v₂ : β) : Node α β :=
let ks : Array α := Array.mkEmpty maxCollisions
let ks := (ks.push k₁).push k₂
let vs : Array β := Array.mkEmpty maxCollisions
let vs := (vs.push v₁).push v₂
Node.collision ks vs rfl
partial def insertAux [BEq α] [Hashable α] : Node α β → USize → USize → α → β → Node α β
| Node.collision keys vals heq, _, depth, k, v =>
let newNode := insertAtCollisionNode ⟨Node.collision keys vals heq, IsCollisionNode.mk _ _ _⟩ k v
if depth >= maxDepth || getCollisionNodeSize newNode < maxCollisions then newNode.val
else match newNode with
| ⟨Node.entries _, h⟩ => False.elim (nomatch h)
| ⟨Node.collision keys vals heq, _⟩ =>
let rec traverse (i : Nat) (entries : Node α β) : Node α β :=
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let v := vals.get ⟨i, heq ▸ h⟩
let h := hash k
let h := div2Shift h (shift * (depth - 1))
traverse (i+1) (insertAux entries h depth k v)
else
entries
traverse 0 mkEmptyEntries
| Node.entries entries, h, depth, k, v =>
let j := (mod2Shift h shift).toNat
Node.entries $ entries.modify j fun entry =>
match entry with
| Entry.null => Entry.entry k v
| Entry.ref node => Entry.ref $ insertAux node (div2Shift h shift) (depth+1) k v
| Entry.entry k' v' =>
if k == k' then Entry.entry k v
else Entry.ref $ mkCollisionNode k' v' k v
def insert [BEq α] [Hashable α] : PersistentHashMap α β → α → β → PersistentHashMap α β
| { root := n, size := sz }, k, v => { root := insertAux n (hash k) 1 k v, size := sz + 1 }
partial def findAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option β :=
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩
if k == k' then some (vals.get ⟨i, by rw [←heq]; assumption⟩)
else findAtAux keys vals heq (i+1) k
else none
partial def findAux [BEq α] : Node α β → USize → α → Option β
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat
match entries.get! j with
| Entry.null => none
| Entry.ref node => findAux node (div2Shift h shift) k
| Entry.entry k' v => if k == k' then some v else none
| Node.collision keys vals heq, _, k => findAtAux keys vals heq 0 k
def find? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option β
| { root := n, .. }, k => findAux n (hash k) k
@[inline] def getOp [BEq α] [Hashable α] (self : PersistentHashMap α β) (idx : α) : Option β :=
self.find? idx
@[inline] def findD [BEq α] [Hashable α] (m : PersistentHashMap α β) (a : α) (b₀ : β) : β :=
(m.find? a).getD b₀
@[inline] def find! [BEq α] [Hashable α] [Inhabited β] (m : PersistentHashMap α β) (a : α) : β :=
match m.find? a with
| some b => b
| none => panic! "key is not in the map"
partial def findEntryAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Option (α × β) :=
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩
if k == k' then some (k', vals.get ⟨i, by rw [←heq]; assumption⟩)
else findEntryAtAux keys vals heq (i+1) k
else none
partial def findEntryAux [BEq α] : Node α β → USize → α → Option (α × β)
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat
match entries.get! j with
| Entry.null => none
| Entry.ref node => findEntryAux node (div2Shift h shift) k
| Entry.entry k' v => if k == k' then some (k', v) else none
| Node.collision keys vals heq, _, k => findEntryAtAux keys vals heq 0 k
def findEntry? [BEq α] [Hashable α] : PersistentHashMap α β → α → Option (α × β)
| { root := n, .. }, k => findEntryAux n (hash k) k
partial def containsAtAux [BEq α] (keys : Array α) (vals : Array β) (heq : keys.size = vals.size) (i : Nat) (k : α) : Bool :=
if h : i < keys.size then
let k' := keys.get ⟨i, h⟩
if k == k' then true
else containsAtAux keys vals heq (i+1) k
else false
partial def containsAux [BEq α] : Node α β → USize → α → Bool
| Node.entries entries, h, k =>
let j := (mod2Shift h shift).toNat
match entries.get! j with
| Entry.null => false
| Entry.ref node => containsAux node (div2Shift h shift) k
| Entry.entry k' v => k == k'
| Node.collision keys vals heq, _, k => containsAtAux keys vals heq 0 k
def contains [BEq α] [Hashable α] : PersistentHashMap α β → α → Bool
| { root := n, .. }, k => containsAux n (hash k) k
partial def isUnaryEntries (a : Array (Entry α β (Node α β))) (i : Nat) (acc : Option (α × β)) : Option (α × β) :=
if h : i < a.size then
match a.get ⟨i, h⟩ with
| Entry.null => isUnaryEntries a (i+1) acc
| Entry.ref _ => none
| Entry.entry k v =>
match acc with
| none => isUnaryEntries a (i+1) (some (k, v))
| some _ => none
else acc
def isUnaryNode : Node α β → Option (α × β)
| Node.entries entries => isUnaryEntries entries 0 none
| Node.collision keys vals heq =>
if h : 1 = keys.size then
have 0 < keys.size by rw [←h]; decide
some (keys.get ⟨0, this⟩, vals.get ⟨0, by rw [←heq]; assumption⟩)
else
none
partial def eraseAux [BEq α] : Node α β → USize → α → Node α β × Bool
| n@(Node.collision keys vals heq), _, k =>
match keys.indexOf? k with
| some idx =>
let ⟨keys', keq⟩ := keys.eraseIdx' idx
let ⟨vals', veq⟩ := vals.eraseIdx' (Eq.ndrec idx heq)
have keys.size - 1 = vals.size - 1 by rw [heq]
(Node.collision keys' vals' (keq.trans (this.trans veq.symm)), true)
| none => (n, false)
| n@(Node.entries entries), h, k =>
let j := (mod2Shift h shift).toNat
let entry := entries.get! j
match entry with
| Entry.null => (n, false)
| Entry.entry k' v =>
if k == k' then (Node.entries (entries.set! j Entry.null), true) else (n, false)
| Entry.ref node =>
let entries := entries.set! j Entry.null
let (newNode, deleted) := eraseAux node (div2Shift h shift) k
if !deleted then (n, false)
else match isUnaryNode newNode with
| none => (Node.entries (entries.set! j (Entry.ref newNode)), true)
| some (k, v) => (Node.entries (entries.set! j (Entry.entry k v)), true)
def erase [BEq α] [Hashable α] : PersistentHashMap α β → α → PersistentHashMap α β
| { root := n, size := sz }, k =>
let h := hash k
let (n, del) := eraseAux n h k
{ root := n, size := if del then sz - 1 else sz }
section
variable {m : Type w → Type w'} [Monad m]
variable {σ : Type w}
@[specialize] partial def foldlMAux (f : σ → α → β → m σ) : Node α β → σ → m σ
| Node.collision keys vals heq, acc =>
let rec traverse (i : Nat) (acc : σ) : m σ := do
if h : i < keys.size then
let k := keys.get ⟨i, h⟩
let v := vals.get ⟨i, heq ▸ h⟩
traverse (i+1) (← f acc k v)
else
pure acc
traverse 0 acc
| Node.entries entries, acc => entries.foldlM (fun acc entry =>
match entry with
| Entry.null => pure acc
| Entry.entry k v => f acc k v
| Entry.ref node => foldlMAux f node acc)
acc
@[specialize] def foldlM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → m σ) (init : σ) : m σ :=
foldlMAux f map.root init
@[specialize] def forM [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : α → β → m PUnit) : m PUnit :=
map.foldlM (fun _ => f) ⟨⟩
@[specialize] def foldl [BEq α] [Hashable α] (map : PersistentHashMap α β) (f : σ → α → β → σ) (init : σ) : σ :=
Id.run $ map.foldlM f init
end
def toList [BEq α] [Hashable α] (m : PersistentHashMap α β) : List (α × β) :=
m.foldl (init := []) fun ps k v => (k, v) :: ps
structure Stats where
numNodes : Nat := 0
numNull : Nat := 0
numCollisions : Nat := 0
maxDepth : Nat := 0
partial def collectStats : Node α β → Stats → Nat → Stats
| Node.collision keys _ _, stats, depth =>
{ stats with
numNodes := stats.numNodes + 1,
numCollisions := stats.numCollisions + keys.size - 1,
maxDepth := Nat.max stats.maxDepth depth }
| Node.entries entries, stats, depth =>
let stats :=
{ stats with
numNodes := stats.numNodes + 1,
maxDepth := Nat.max stats.maxDepth depth }
entries.foldl (fun stats entry =>
match entry with
| Entry.null => { stats with numNull := stats.numNull + 1 }
| Entry.ref node => collectStats node stats (depth + 1)
| Entry.entry _ _ => stats)
stats
def stats [BEq α] [Hashable α] (m : PersistentHashMap α β) : Stats :=
collectStats m.root {} 1
def Stats.toString (s : Stats) : String :=
s!"\{ nodes := {s.numNodes}, null := {s.numNull}, collisions := {s.numCollisions}, depth := {s.maxDepth}}"
instance : ToString Stats := ⟨Stats.toString⟩
end PersistentHashMap
end Std
|
cd43fcf64020cdcd5cfcded4fd0a48c63ab914ae | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/homology/single.lean | 82ff2975d8030e1dd528796be556e6637855afb7 | [
"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 | 11,286 | 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 algebra.homology.homology
/-!
# Chain complexes supported in a single degree
We define `single V j c : V ⥤ homological_complex V c`,
which constructs complexes in `V` of shape `c`, supported in degree `j`.
Similarly `single₀ V : V ⥤ chain_complex V ℕ` is the special case for
`ℕ`-indexed chain complexes, with the object supported in degree `0`,
but with better definitional properties.
In `to_single₀_equiv` we characterize chain maps to a `ℕ`-indexed complex concentrated in degree 0;
they are equivalent to `{ f : C.X 0 ⟶ X // C.d 1 0 ≫ f = 0 }`.
(This is useful translating between a projective resolution and
an augmented exact complex of projectives.)
-/
noncomputable theory
open category_theory
open category_theory.limits
universes v u
variables (V : Type u) [category.{v} V] [has_zero_morphisms V] [has_zero_object V]
namespace homological_complex
variables {ι : Type*} [decidable_eq ι] (c : complex_shape ι)
local attribute [instance] has_zero_object.has_zero
/--
The functor `V ⥤ homological_complex V c` creating a chain complex supported in a single degree.
See also `chain_complex.single₀ : V ⥤ chain_complex V ℕ`,
which has better definitional properties,
if you are working with `ℕ`-indexed complexes.
-/
@[simps]
def single (j : ι) : V ⥤ homological_complex V c :=
{ obj := λ A,
{ X := λ i, if i = j then A else 0,
d := λ i j, 0, },
map := λ A B f,
{ f := λ i, if h : i = j then
eq_to_hom (by { dsimp, rw if_pos h, }) ≫ f ≫ eq_to_hom (by { dsimp, rw if_pos h, })
else
0, },
map_id' := λ A, begin
ext,
dsimp,
split_ifs with h,
{ subst h, simp, },
{ rw if_neg h, simp, },
end,
map_comp' := λ A B C f g, begin
ext,
dsimp,
split_ifs with h,
{ subst h, simp, },
{ simp, },
end, }.
/--
The object in degree `j` of `(single V c h).obj A` is just `A`.
-/
@[simps]
def single_obj_X_self (j : ι) (A : V) : ((single V c j).obj A).X j ≅ A :=
eq_to_iso (by simp)
@[simp]
lemma single_map_f_self (j : ι) {A B : V} (f : A ⟶ B) :
((single V c j).map f).f j =
(single_obj_X_self V c j A).hom ≫ f ≫ (single_obj_X_self V c j B).inv :=
by { simp, refl, }
instance (j : ι) : faithful (single V c j) :=
{ map_injective' := λ X Y f g w, begin
have := congr_hom w j,
dsimp at this,
simp only [dif_pos] at this,
rw [←is_iso.inv_comp_eq, inv_eq_to_hom, eq_to_hom_trans_assoc, eq_to_hom_refl, category.id_comp,
←is_iso.comp_inv_eq, category.assoc, inv_eq_to_hom, eq_to_hom_trans, eq_to_hom_refl,
category.comp_id] at this,
exact this,
end, }
instance (j : ι) : full (single V c j) :=
{ preimage := λ X Y f, eq_to_hom (by simp) ≫ f.f j ≫ eq_to_hom (by simp),
witness' := λ X Y f, begin
ext i,
dsimp,
split_ifs,
{ subst h, simp, },
{ symmetry,
apply zero_of_target_iso_zero,
dsimp,
rw [if_neg h], },
end }
end homological_complex
open homological_complex
namespace chain_complex
local attribute [instance] has_zero_object.has_zero
/--
`chain_complex.single₀ V` is the embedding of `V` into `chain_complex V ℕ`
as chain complexes supported in degree 0.
This is naturally isomorphic to `single V _ 0`, but has better definitional properties.
-/
def single₀ : V ⥤ chain_complex V ℕ :=
{ obj := λ X,
{ X := λ n, match n with
| 0 := X
| (n+1) := 0
end,
d := λ i j, 0, },
map := λ X Y f,
{ f := λ n, match n with
| 0 := f
| (n+1) := 0
end, },
map_id' := λ X, by { ext n, cases n, refl, dsimp, unfold_aux, simp, },
map_comp' := λ X Y Z f g, by { ext n, cases n, refl, dsimp, unfold_aux, simp, } }
@[simp] lemma single₀_obj_X_0 (X : V) : ((single₀ V).obj X).X 0 = X := rfl
@[simp] lemma single₀_obj_X_succ (X : V) (n : ℕ) : ((single₀ V).obj X).X (n+1) = 0 := rfl
@[simp] lemma single₀_obj_X_d (X : V) (i j : ℕ) : ((single₀ V).obj X).d i j = 0 := rfl
@[simp] lemma single₀_obj_X_d_to (X : V) (j : ℕ) : ((single₀ V).obj X).d_to j = 0 :=
by { rw [d_to_eq ((single₀ V).obj X) rfl], simp, }
@[simp] lemma single₀_obj_X_d_from (X : V) (i : ℕ) : ((single₀ V).obj X).d_from i = 0 :=
begin
cases i,
{ rw [d_from_eq_zero], simp, },
{ rw [d_from_eq ((single₀ V).obj X) rfl], simp, },
end
@[simp] lemma single₀_map_f_0 {X Y : V} (f : X ⟶ Y) : ((single₀ V).map f).f 0 = f := rfl
@[simp] lemma single₀_map_f_succ {X Y : V} (f : X ⟶ Y) (n : ℕ) :
((single₀ V).map f).f (n+1) = 0 := rfl
section
variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V]
/--
Sending objects to chain complexes supported at `0` then taking `0`-th homology
is the same as doing nothing.
-/
noncomputable
def homology_functor_0_single₀ : single₀ V ⋙ homology_functor V _ 0 ≅ (𝟭 V) :=
nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero)
(λ X Y f, by { ext, dsimp [homology_functor], simp, })
/--
Sending objects to chain complexes supported at `0` then taking `(n+1)`-st homology
is the same as the zero functor.
-/
noncomputable
def homology_functor_succ_single₀ (n : ℕ) : single₀ V ⋙ homology_functor V _ (n+1) ≅ 0 :=
nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫
homology_zero_zero ≪≫ (functor.zero_obj _).iso_zero.symm)
(λ X Y f, by { exact (functor.zero_obj _).eq_of_tgt _ _ })
end
variables {V}
/--
Morphisms from a `ℕ`-indexed chain complex `C`
to a single object chain complex with `X` concentrated in degree 0
are the same as morphisms `f : C.X 0 ⟶ X` such that `C.d 1 0 ≫ f = 0`.
-/
def to_single₀_equiv (C : chain_complex V ℕ) (X : V) :
(C ⟶ (single₀ V).obj X) ≃ { f : C.X 0 ⟶ X // C.d 1 0 ≫ f = 0 } :=
{ to_fun := λ f, ⟨f.f 0, by { rw ←f.comm 1 0, simp, }⟩,
inv_fun := λ f,
{ f := λ i, match i with
| 0 := f.1
| (n+1) := 0
end,
comm' := λ i j h, begin
rcases i with _|_|i; cases j; unfold_aux; simp only [comp_zero, zero_comp, single₀_obj_X_d],
{ rw [C.shape, zero_comp], simp, },
{ exact f.2.symm, },
{ rw [C.shape, zero_comp], simp [i.succ_succ_ne_one.symm] },
end, },
left_inv := λ f, begin
ext i,
rcases i,
{ refl, },
{ ext, },
end,
right_inv := by tidy, }
variables (V)
/-- `single₀` is the same as `single V _ 0`. -/
def single₀_iso_single : single₀ V ≅ single V _ 0 :=
nat_iso.of_components
(λ X,
{ hom := { f := λ i, by { cases i; simpa using 𝟙 _, } },
inv := { f := λ i, by { cases i; simpa using 𝟙 _, } },
hom_inv_id' := by { ext (_|i); { dsimp, simp, }, },
inv_hom_id' := begin
ext (_|i),
{ apply category.id_comp, },
{ apply has_zero_object.to_zero_ext, },
end, })
(λ X Y f, by { ext (_|i); { dsimp, simp, }, })
instance : faithful (single₀ V) := faithful.of_iso (single₀_iso_single V).symm
instance : full (single₀ V) := full.of_iso (single₀_iso_single V).symm
end chain_complex
namespace cochain_complex
local attribute [instance] has_zero_object.has_zero
/--
`cochain_complex.single₀ V` is the embedding of `V` into `cochain_complex V ℕ`
as cochain complexes supported in degree 0.
This is naturally isomorphic to `single V _ 0`, but has better definitional properties.
-/
def single₀ : V ⥤ cochain_complex V ℕ :=
{ obj := λ X,
{ X := λ n, match n with
| 0 := X
| (n+1) := 0
end,
d := λ i j, 0, },
map := λ X Y f,
{ f := λ n, match n with
| 0 := f
| (n+1) := 0
end, },
map_id' := λ X, by { ext n, cases n, refl, dsimp, unfold_aux, simp, },
map_comp' := λ X Y Z f g, by { ext n, cases n, refl, dsimp, unfold_aux, simp, } }
@[simp] lemma single₀_obj_X_0 (X : V) : ((single₀ V).obj X).X 0 = X := rfl
@[simp] lemma single₀_obj_X_succ (X : V) (n : ℕ) : ((single₀ V).obj X).X (n+1) = 0 := rfl
@[simp] lemma single₀_obj_X_d (X : V) (i j : ℕ) : ((single₀ V).obj X).d i j = 0 := rfl
@[simp] lemma single₀_obj_X_d_from (X : V) (j : ℕ) : ((single₀ V).obj X).d_from j = 0 :=
by { rw [d_from_eq ((single₀ V).obj X) rfl], simp, }
@[simp] lemma single₀_obj_X_d_to (X : V) (i : ℕ) : ((single₀ V).obj X).d_to i = 0 :=
begin
cases i,
{ rw [d_to_eq_zero], simp, },
{ rw [d_to_eq ((single₀ V).obj X) rfl], simp, },
end
@[simp] lemma single₀_map_f_0 {X Y : V} (f : X ⟶ Y) : ((single₀ V).map f).f 0 = f := rfl
@[simp] lemma single₀_map_f_succ {X Y : V} (f : X ⟶ Y) (n : ℕ) :
((single₀ V).map f).f (n+1) = 0 := rfl
section
variables [has_equalizers V] [has_cokernels V] [has_images V] [has_image_maps V]
/--
Sending objects to cochain complexes supported at `0` then taking `0`-th homology
is the same as doing nothing.
-/
noncomputable
def homology_functor_0_single₀ : single₀ V ⋙ homology_functor V _ 0 ≅ (𝟭 V) :=
nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫ homology_zero_zero)
(λ X Y f, by { ext, dsimp [homology_functor], simp, })
/--
Sending objects to cochain complexes supported at `0` then taking `(n+1)`-st homology
is the same as the zero functor.
-/
noncomputable
def homology_functor_succ_single₀ (n : ℕ) : single₀ V ⋙ homology_functor V _ (n+1) ≅ 0 :=
nat_iso.of_components (λ X, homology.congr _ _ (by simp) (by simp) ≪≫
homology_zero_zero ≪≫ (functor.zero_obj _).iso_zero.symm)
(λ X Y f, by { exact (functor.zero_obj _).eq_of_tgt _ _ })
end
variables {V}
/--
Morphisms from a single object cochain complex with `X` concentrated in degree 0
to a `ℕ`-indexed cochain complex `C`
are the same as morphisms `f : X ⟶ C.X 0` such that `f ≫ C.d 0 1 = 0`.
-/
def from_single₀_equiv (C : cochain_complex V ℕ) (X : V) :
((single₀ V).obj X ⟶ C) ≃ { f : X ⟶ C.X 0 // f ≫ C.d 0 1 = 0 } :=
{ to_fun := λ f, ⟨f.f 0, by { rw f.comm 0 1, simp, }⟩,
inv_fun := λ f,
{ f := λ i, match i with
| 0 := f.1
| (n+1) := 0
end,
comm' := λ i j h, begin
rcases j with _|_|j; cases i; unfold_aux; simp only [comp_zero, zero_comp, single₀_obj_X_d],
{ convert comp_zero, rw [C.shape], simp, },
{ exact f.2, },
{ convert comp_zero, rw [C.shape], simp only [complex_shape.up_rel, zero_add],
exact (nat.one_lt_succ_succ j).ne },
end, },
left_inv := λ f, begin
ext i,
rcases i,
{ refl, },
{ ext, },
end,
right_inv := by tidy, }
variables (V)
/-- `single₀` is the same as `single V _ 0`. -/
def single₀_iso_single : single₀ V ≅ single V _ 0 :=
nat_iso.of_components
(λ X,
{ hom := { f := λ i, by { cases i; simpa using 𝟙 _, } },
inv := { f := λ i, by { cases i; simpa using 𝟙 _, } },
hom_inv_id' := by { ext (_|i); { dsimp, simp, }, },
inv_hom_id' := begin
ext (_|i),
{ apply category.id_comp, },
{ apply has_zero_object.to_zero_ext, },
end, })
(λ X Y f, by { ext (_|i); { dsimp, simp, }, })
instance : faithful (single₀ V) := faithful.of_iso (single₀_iso_single V).symm
instance : full (single₀ V) := full.of_iso (single₀_iso_single V).symm
end cochain_complex
|
ae4565315bf740feee24a2c734dfae7a0e7c9093 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Lean/Elab/Tactic/Delta.lean | 5a7dcb6a0519443b64c3ffa654835a12f2a0d0b3 | [
"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 | 1,404 | 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.Meta.Tactic.Delta
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.Location
namespace Lean.Elab.Tactic
open Meta
def deltaLocalDecl (declName : Name) (fvarId : FVarId) : TacticM Unit := do
let mvarId ← getMainGoal
let localDecl ← fvarId.getDecl
let typeNew ← deltaExpand localDecl.type (· == declName)
if typeNew == localDecl.type then
throwTacticEx `delta mvarId m!"did not delta reduce '{declName}' at '{localDecl.userName}'"
replaceMainGoal [← mvarId.replaceLocalDeclDefEq fvarId typeNew]
def deltaTarget (declName : Name) : TacticM Unit := do
let mvarId ← getMainGoal
let target ← getMainTarget
let targetNew ← deltaExpand target (· == declName)
if targetNew == target then
throwTacticEx `delta mvarId m!"did not delta reduce '{declName}'"
replaceMainGoal [← mvarId.replaceTargetDefEq targetNew]
/--
"delta " ident (location)?
-/
@[builtinTactic Lean.Parser.Tactic.delta] def evalDelta : Tactic := fun stx => do
let declName ← resolveGlobalConstNoOverloadWithInfo stx[1]
let loc := expandOptLocation stx[2]
withLocation loc (deltaLocalDecl declName) (deltaTarget declName) (throwTacticEx `delta · m!"did not delta reduce '{declName}'")
end Lean.Elab.Tactic
|
1469f959dc3bd08cc462cbb9b961bc480cfd1208 | 6e41ee3ac9b96e8980a16295cc21f131e731884f | /library/data/nat/order.lean | c5f4ff17a32a3b5d7a3251953893f27da78cfcbc | [
"Apache-2.0"
] | permissive | EgbertRijke/lean | 3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3 | 4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183 | refs/heads/master | 1,610,834,871,476 | 1,422,159,801,000 | 1,422,159,801,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,342 | lean | /-
Copyright (c) 2014 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.nat.order
Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad
The order relation on the natural numbers.
-/
import data.nat.basic data.nat.comm_semiring algebra.ordered_ring
open eq.ops
namespace nat
/- lt and le -/
theorem le_of_lt_or_eq {m n : ℕ} (H : m < n ∨ m = n) : m ≤ n :=
or.elim H (take H1, le_of_lt H1) (take H1, H1 ▸ !le.refl)
theorem lt.by_cases {a b : ℕ} {P : Prop}
(H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P :=
or.elim !lt.trichotomy
(assume H, H1 H)
(assume H, or.elim H (assume H', H2 H') (assume H', H3 H'))
theorem lt_or_eq_of_le {m n : ℕ} (H : m ≤ n) : m < n ∨ m = n :=
lt.by_cases
(assume H1 : m < n, or.inl H1)
(assume H1 : m = n, or.inr H1)
(assume H1 : m > n, absurd (lt_of_le_of_lt H H1) !lt.irrefl)
theorem le_iff_lt_or_eq (m n : ℕ) : m ≤ n ↔ m < n ∨ m = n :=
iff.intro lt_or_eq_of_le le_of_lt_or_eq
theorem lt_of_le_and_ne {m n : ℕ} (H1 : m ≤ n) (H2 : m ≠ n) : m < n :=
or.elim (lt_or_eq_of_le H1)
(take H3 : m < n, H3)
(take H3 : m = n, absurd H3 H2)
theorem lt_iff_le_and_ne (m n : ℕ) : m < n ↔ m ≤ n ∧ m ≠ n :=
iff.intro
(take H, and.intro (le_of_lt H) (take H1, lt.irrefl _ (H1 ▸ H)))
(take H, lt_of_le_and_ne (and.elim_left H) (and.elim_right H))
theorem le_add_right (n k : ℕ) : n ≤ n + k :=
induction_on k
(calc n ≤ n : le.refl n
... = n + zero : add_zero)
(λ k (ih : n ≤ n + k), calc
n ≤ succ (n + k) : le_succ_of_le ih
... = n + succ k : add_succ)
theorem le_add_left (n m : ℕ): n ≤ m + n :=
!add.comm ▸ !le_add_right
theorem le.intro {n m k : ℕ} (h : n + k = m) : n ≤ m :=
h ▸ le_add_right n k
theorem le.elim {n m : ℕ} (h : n ≤ m) : ∃k, n + k = m :=
le.rec_on h
(exists.intro 0 rfl)
(λ m (h : n < m), lt.rec_on h
(exists.intro 1 rfl)
(λ b hlt (ih : ∃ (k : ℕ), n + k = b),
obtain (k : ℕ) (h : n + k = b), from ih,
exists.intro (succ k) (calc
n + succ k = succ (n + k) : add_succ
... = succ b : h)))
theorem le.total {m n : ℕ} : m ≤ n ∨ n ≤ m :=
lt.by_cases
(assume H : m < n, or.inl (le_of_lt H))
(assume H : m = n, or.inl (H ▸ !le.refl))
(assume H : m > n, or.inr (le_of_lt H))
/- addition -/
theorem add_le_add_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m :=
obtain (l : ℕ) (Hl : n + l = m), from le.elim H,
le.intro
(calc
k + n + l = k + (n + l) : !add.assoc
... = k + m : {Hl})
theorem add_le_add_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k :=
!add.comm ▸ !add.comm ▸ add_le_add_left H k
theorem le_of_add_le_add_left {k n m : ℕ} (H : k + n ≤ k + m) : n ≤ m :=
obtain (l : ℕ) (Hl : k + n + l = k + m), from (le.elim H),
le.intro (add.cancel_left
(calc
k + (n + l) = k + n + l : (!add.assoc)⁻¹
... = k + m : Hl))
theorem add_lt_add_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m :=
lt_of_succ_le (!add_succ ▸ add_le_add_left (succ_le_of_lt H) k)
theorem add_lt_add_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k :=
!add.comm ▸ !add.comm ▸ add_lt_add_left H k
theorem lt_add_of_pos_right {n k : ℕ} (H : k > 0) : n < n + k :=
!add_zero ▸ add_lt_add_left H n
/- multiplication -/
theorem mul_le_mul_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m :=
obtain (l : ℕ) (Hl : n + l = m), from le.elim H,
have H2 : k * n + k * l = k * m, from
calc
k * n + k * l = k * (n + l) : mul.left_distrib
... = k * m : {Hl},
le.intro H2
theorem mul_le_mul_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k :=
!mul.comm ▸ !mul.comm ▸ (mul_le_mul_left H k)
theorem mul_le_mul {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l :=
le.trans (mul_le_mul_right H1 m) (mul_le_mul_left H2 k)
theorem mul_lt_mul_of_pos_left {n m k : ℕ} (H : n < m) (Hk : k > 0) : k * n < k * m :=
have H2 : k * n < k * n + k, from lt_add_of_pos_right Hk,
have H3 : k * n + k ≤ k * m, from !mul_succ ▸ mul_le_mul_left (succ_le_of_lt H) k,
lt_of_lt_of_le H2 H3
theorem mul_lt_mul_of_pos_right {n m k : ℕ} (H : n < m) (Hk : k > 0) : n * k < m * k :=
!mul.comm ▸ !mul.comm ▸ mul_lt_mul_of_pos_left H Hk
theorem le.antisymm {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m :=
obtain (k : ℕ) (Hk : n + k = m), from (le.elim H1),
obtain (l : ℕ) (Hl : m + l = n), from (le.elim H2),
have L1 : k + l = 0, from
add.cancel_left
(calc
n + (k + l) = n + k + l : (!add.assoc)⁻¹
... = m + l : {Hk}
... = n : Hl
... = n + 0 : (!add_zero)⁻¹),
have L2 : k = 0, from eq_zero_of_add_eq_zero_right L1,
calc
n = n + 0 : (!add_zero)⁻¹
... = n + k : {L2⁻¹}
... = m : Hk
theorem zero_le (n : ℕ) : 0 ≤ n :=
le.intro !zero_add
/- nat is an instance of a linearly ordered semiring -/
section
open [classes] algebra
protected definition linear_ordered_semiring [instance] : algebra.linear_ordered_semiring nat :=
⦃ algebra.linear_ordered_semiring, nat.comm_semiring,
add_left_cancel := @add.cancel_left,
add_right_cancel := @add.cancel_right,
lt := lt,
le := le,
le_refl := le.refl,
le_trans := @le.trans,
le_antisymm := @le.antisymm,
le_total := @le.total,
le_iff_lt_or_eq := @le_iff_lt_or_eq,
lt_iff_le_ne := lt_iff_le_and_ne,
add_le_add_left := @add_le_add_left,
le_of_add_le_add_left := @le_of_add_le_add_left,
mul_le_mul_of_nonneg_left := (take a b c H1 H2, mul_le_mul_left H1 c),
mul_le_mul_of_nonneg_right := (take a b c H1 H2, mul_le_mul_right H1 c),
mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left,
mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right ⦄
end
section port_algebra
theorem ne_of_lt : ∀{a b : ℕ}, a < b → a ≠ b := @algebra.ne_of_lt _ _
theorem lt_of_le_of_ne : ∀{a b : ℕ}, a ≤ b → a ≠ b → a < b :=
@algebra.lt_of_le_of_ne _ _
theorem not_le_of_lt : ∀{a b : ℕ}, a < b → ¬ b ≤ a := @algebra.not_le_of_lt _ _
theorem not_lt_of_le : ∀{a b : ℕ}, a ≤ b → ¬ b < a := @algebra.not_lt_of_le _ _
theorem le_of_not_lt : ∀{a b : ℕ}, ¬ a < b → b ≤ a := @algebra.le_of_not_lt _ _
theorem lt_of_not_le : ∀{a b : ℕ}, ¬ a ≤ b → b < a := @algebra.lt_of_not_le _ _
theorem lt_or_ge : ∀a b : ℕ, a < b ∨ a ≥ b := @algebra.lt_or_ge _ _
theorem le_or_gt : ∀a b : ℕ, a ≤ b ∨ a > b := @algebra.le_or_gt _ _
theorem lt_or_gt_of_ne : ∀{a b : ℕ}, a ≠ b → a < b ∨ a > b := @algebra.lt_or_gt_of_ne _ _
theorem add_le_add : ∀{a b c d : ℕ}, a ≤ b → c ≤ d → a + c ≤ b + d := @algebra.add_le_add _ _
theorem add_lt_add : ∀{a b c d : ℕ}, a < b → c < d → a + c < b + d := @algebra.add_lt_add _ _
theorem add_lt_add_of_le_of_lt : ∀{a b c d : ℕ}, a ≤ b → c < d → a + c < b + d :=
@algebra.add_lt_add_of_le_of_lt _ _
theorem add_lt_add_of_lt_of_le : ∀{a b c d : ℕ}, a < b → c ≤ d → a + c < b + d :=
@algebra.add_lt_add_of_lt_of_le _ _
theorem lt_add_of_pos_left : ∀{a b : ℕ}, b > 0 → a < b + a := @algebra.lt_add_of_pos_left _ _
theorem le_of_add_le_add_right : ∀{a b c : ℕ}, a + b ≤ c + b → a ≤ c :=
@algebra.le_of_add_le_add_right _ _
theorem lt_of_add_lt_add_left : ∀{a b c : ℕ}, a + b < a + c → b < c :=
@algebra.lt_of_add_lt_add_left _ _
theorem lt_of_add_lt_add_right : ∀{a b c : ℕ}, a + b < c + b → a < c :=
@algebra.lt_of_add_lt_add_right _ _
theorem add_le_add_left_iff : ∀a b c : ℕ, a + b ≤ a + c ↔ b ≤ c := algebra.add_le_add_left_iff
theorem add_le_add_right_iff : ∀a b c : ℕ, a + b ≤ c + b ↔ a ≤ c := algebra.add_le_add_right_iff
theorem add_lt_add_left_iff : ∀a b c : ℕ, a + b < a + c ↔ b < c := algebra.add_lt_add_left_iff
theorem add_lt_add_right_iff : ∀a b c : ℕ, a + b < c + b ↔ a < c := algebra.add_lt_add_right_iff
theorem add_pos_left : ∀{a : ℕ}, 0 < a → ∀b : ℕ, 0 < a + b :=
take a H b, @algebra.add_pos_of_pos_of_nonneg _ _ a b H !zero_le
theorem add_pos_right : ∀{a : ℕ}, 0 < a → ∀b : ℕ, 0 < b + a :=
take a H b, !add.comm ▸ add_pos_left H b
theorem add_eq_zero_iff_eq_zero_and_eq_zero : ∀{a b : ℕ},
a + b = 0 ↔ a = 0 ∧ b = 0 :=
take a b : ℕ,
@algebra.add_eq_zero_iff_eq_zero_and_eq_zero_of_nonneg_of_nonneg _ _ a b !zero_le !zero_le
theorem le_add_of_le_left : ∀{a b c : ℕ}, b ≤ c → b ≤ a + c :=
take a b c H, @algebra.le_add_of_nonneg_of_le _ _ a b c !zero_le H
theorem le_add_of_le_right : ∀{a b c : ℕ}, b ≤ c → b ≤ c + a :=
take a b c H, @algebra.le_add_of_le_of_nonneg _ _ a b c H !zero_le
theorem lt_add_of_pos_of_le : ∀{a b c : ℕ}, 0 < a → b ≤ c → b < a + c :=
@algebra.lt_add_of_pos_of_le _ _
theorem lt_add_of_le_of_pos : ∀{a b c : ℕ}, b ≤ c → 0 < a → b < c + a :=
@algebra.lt_add_of_le_of_pos _ _
theorem lt_add_of_lt_left : ∀{b c : ℕ}, b < c → ∀a, b < a + c :=
take b c H a, @algebra.lt_add_of_nonneg_of_lt _ _ a b c !zero_le H
theorem lt_add_of_lt_right : ∀{b c : ℕ}, b < c → ∀a, b < c + a :=
take b c H a, @algebra.lt_add_of_lt_of_nonneg _ _ a b c H !zero_le
theorem lt_add_of_pos_of_lt : ∀{a b c : ℕ}, 0 < a → b < c → b < a + c :=
@algebra.lt_add_of_pos_of_lt _ _
theorem lt_add_of_lt_of_pos : ∀{a b c : ℕ}, b < c → 0 < a → b < c + a :=
@algebra.lt_add_of_lt_of_pos _ _
theorem mul_pos : ∀{a b : ℕ}, 0 < a → 0 < b → 0 < a * b := @algebra.mul_pos _ _
theorem lt_of_mul_lt_mul_left : ∀{a b c : ℕ}, c * a < c * b → a < b :=
take a b c H, @algebra.lt_of_mul_lt_mul_left _ _ a b c H !zero_le
theorem lt_of_mul_lt_mul_right : ∀{a b c : ℕ}, a * c < b * c → a < b :=
take a b c H, @algebra.lt_of_mul_lt_mul_right _ _ a b c H !zero_le
theorem le_of_mul_le_mul_left : ∀{a b c : ℕ}, c * a ≤ c * b → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_left _ _
theorem le_of_mul_le_mul_right : ∀{a b c : ℕ}, a * c ≤ b * c → c > 0 → a ≤ b :=
@algebra.le_of_mul_le_mul_right _ _
theorem pos_of_mul_pos_left : ∀{a b : ℕ}, 0 < a * b → 0 < b :=
take a b H, @algebra.pos_of_mul_pos_left _ _ a b H !zero_le
theorem pos_of_mul_pos_right : ∀{a b : ℕ}, 0 < a * b → 0 < a :=
take a b H, @algebra.pos_of_mul_pos_right _ _ a b H !zero_le
end port_algebra
theorem zero_le_one : 0 ≤ 1 := dec_trivial
theorem zero_lt_one : 0 < 1 := dec_trivial
/- properties specific to nat -/
theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m :=
lt_of_succ_le (le.intro H)
theorem lt_elim {n m : ℕ} (H : n < m) : ∃k, succ n + k = m :=
le.elim (succ_le_of_lt H)
theorem lt_add_succ (n m : ℕ) : n < n + succ m :=
lt_intro !succ_add_eq_add_succ
theorem eq_zero_of_le_zero {n : ℕ} (H : n ≤ 0) : n = 0 :=
obtain (k : ℕ) (Hk : n + k = 0), from le.elim H,
eq_zero_of_add_eq_zero_right Hk
/- succ and pred -/
theorem lt_iff_succ_le (m n : nat) : m < n ↔ succ m ≤ n :=
iff.intro succ_le_of_lt lt_of_succ_le
theorem not_succ_le_zero (n : ℕ) : ¬ succ n ≤ 0 :=
(assume H : succ n ≤ 0,
have H2 : succ n = 0, from eq_zero_of_le_zero H,
absurd H2 !succ_ne_zero)
theorem succ_le_succ {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m :=
!add_one ▸ !add_one ▸ add_le_add_right H 1
theorem le_of_succ_le_succ {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m :=
le_of_add_le_add_right ((!add_one)⁻¹ ▸ (!add_one)⁻¹ ▸ H)
theorem self_le_succ (n : ℕ) : n ≤ succ n :=
le.intro !add_one
theorem succ_le_or_eq_of_le {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m :=
or.elim (lt_or_eq_of_le H)
(assume H1 : n < m, or.inl (succ_le_of_lt H1))
(assume H1 : n = m, or.inr H1)
theorem le_succ_of_pred_le {n m : ℕ} : pred n ≤ m → n ≤ succ m :=
nat.cases_on n
(assume H : pred 0 ≤ m, !zero_le)
(take n',
assume H : pred (succ n') ≤ m,
have H1 : n' ≤ m, from pred_succ n' ▸ H,
succ_le_succ H1)
theorem pred_le_of_le_succ {n m : ℕ} : n ≤ succ m → pred n ≤ m :=
nat.cases_on n
(assume H, !pred_zero⁻¹ ▸ zero_le m)
(take n',
assume H : succ n' ≤ succ m,
have H1 : n' ≤ m, from le_of_succ_le_succ H,
!pred_succ⁻¹ ▸ H1)
theorem succ_le_of_le_pred {n m : ℕ} : succ n ≤ m → n ≤ pred m :=
nat.cases_on m
(assume H, absurd H !not_succ_le_zero)
(take m',
assume H : succ n ≤ succ m',
have H1 : n ≤ m', from le_of_succ_le_succ H,
!pred_succ⁻¹ ▸ H1)
theorem pred_le_pred_of_le {n m : ℕ} : n ≤ m → pred n ≤ pred m :=
nat.cases_on n
(assume H, pred_zero⁻¹ ▸ zero_le (pred m))
(take n',
assume H : succ n' ≤ m,
!pred_succ⁻¹ ▸ succ_le_of_le_pred H)
theorem lt_of_pred_lt_pred {n m : ℕ} (H : pred n < pred m) : n < m :=
lt_of_not_le
(take H1 : m ≤ n,
not_lt_of_le (pred_le_pred_of_le H1) H)
theorem le_or_eq_succ_of_le_succ {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m :=
or_of_or_of_imp_left (succ_le_or_eq_of_le H)
(take H2 : succ n ≤ succ m, show n ≤ m, from le_of_succ_le_succ H2)
theorem le_pred_self (n : ℕ) : pred n ≤ n :=
cases_on n
(pred_zero⁻¹ ▸ !le.refl)
(take k : ℕ, (!pred_succ)⁻¹ ▸ !self_le_succ)
theorem succ_pos (n : ℕ) : 0 < succ n :=
!zero_lt_succ
theorem succ_pred_of_pos {n : ℕ} (H : n > 0) : succ (pred n) = n :=
(or_resolve_right (eq_zero_or_eq_succ_pred n) (ne.symm (ne_of_lt H)))⁻¹
theorem exists_eq_succ_of_lt {n m : ℕ} (H : n < m) : exists k, m = succ k :=
discriminate
(take (Hm : m = 0), absurd (Hm ▸ H) !not_lt_zero)
(take (l : ℕ) (Hm : m = succ l), exists.intro l Hm)
theorem self_lt_succ (n : ℕ) : n < succ n :=
lt.base n
theorem le_of_lt_succ {n m : ℕ} (H : n < succ m) : n ≤ m :=
le_of_succ_le_succ (succ_le_of_lt H)
/- other forms of induction -/
protected theorem strong_induction_on {P : nat → Prop} (n : ℕ) (H : ∀n, (∀m, m < n → P m) → P n) :
P n :=
have H1 : ∀ {n m : nat}, m < n → P m, from
take n,
induction_on n
(show ∀m, m < 0 → P m, from take m H, absurd H !not_lt_zero)
(take n',
assume IH : ∀ {m : nat}, m < n' → P m,
have H2: P n', from H n' @IH,
show ∀m, m < succ n' → P m, from
take m,
assume H3 : m < succ n',
or.elim (lt_or_eq_of_le (le_of_lt_succ H3))
(assume H4: m < n', IH H4)
(assume H4: m = n', H4⁻¹ ▸ H2)),
H1 !self_lt_succ
protected theorem case_strong_induction_on {P : nat → Prop} (a : nat) (H0 : P 0)
(Hind : ∀(n : nat), (∀m, m ≤ n → P m) → P (succ n)) : P a :=
strong_induction_on a (
take n,
show (∀m, m < n → P m) → P n, from
cases_on n
(assume H : (∀m, m < 0 → P m), show P 0, from H0)
(take n,
assume H : (∀m, m < succ n → P m),
show P (succ n), from
Hind n (take m, assume H1 : m ≤ n, H _ (lt_succ_of_le H1))))
/- pos -/
theorem by_cases_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀ {y : nat}, y > 0 → P y) : P y :=
cases_on y H0 (take y, H1 !succ_pos)
theorem zero_or_pos {n : ℕ} : n = 0 ∨ n > 0 :=
or_of_or_of_imp_left
(or.swap (lt_or_eq_of_le !zero_le))
(take H : 0 = n, H⁻¹)
theorem pos_of_ne_zero {n : ℕ} (H : n ≠ 0) : n > 0 :=
or.elim zero_or_pos (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2)
theorem ne_zero_of_pos {n : ℕ} (H : n > 0) : n ≠ 0 :=
ne.symm (ne_of_lt H)
theorem exists_eq_succ_of_pos {n : ℕ} (H : n > 0) : exists l, n = succ l :=
exists_eq_succ_of_lt H
/- multiplication -/
theorem mul_lt_mul_of_le_of_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) :
n * m < k * l :=
lt_of_le_of_lt (mul_le_mul_right H1 m) (mul_lt_mul_of_pos_left H2 Hk)
theorem mul_lt_mul_of_lt_of_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) :
n * m < k * l :=
lt_of_le_of_lt (mul_le_mul_left H2 n) (mul_lt_mul_of_pos_right H1 Hl)
theorem mul_lt_mul_of_le_of_le {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l :=
have H3 : n * m ≤ k * m, from mul_le_mul_right (le_of_lt H1) m,
have H4 : k * m < k * l, from mul_lt_mul_of_pos_left H2 (lt_of_le_of_lt !zero_le H1),
lt_of_le_of_lt H3 H4
theorem eq_of_mul_eq_mul_left {m k n : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k :=
have H2 : n * m ≤ n * k, from H ▸ !le.refl,
have H3 : n * k ≤ n * m, from H ▸ !le.refl,
have H4 : m ≤ k, from le_of_mul_le_mul_left H2 Hn,
have H5 : k ≤ m, from le_of_mul_le_mul_left H3 Hn,
le.antisymm H4 H5
theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k :=
eq_of_mul_eq_mul_left Hm (!mul.comm ▸ !mul.comm ▸ H)
theorem eq_zero_or_eq_of_mul_eq_mul_left {n m k : ℕ} (H : n * m = n * k) : n = 0 ∨ m = k :=
or_of_or_of_imp_right zero_or_pos
(assume Hn : n > 0, eq_of_mul_eq_mul_left Hn H)
theorem eq_zero_or_eq_of_mul_eq_mul_right {n m k : ℕ} (H : n * m = k * m) : m = 0 ∨ n = k :=
eq_zero_or_eq_of_mul_eq_mul_left (!mul.comm ▸ !mul.comm ▸ H)
theorem eq_one_of_mul_eq_one_right {n m : ℕ} (H : n * m = 1) : n = 1 :=
have H2 : n * m > 0, from H⁻¹ ▸ !succ_pos,
have H3 : n > 0, from pos_of_mul_pos_right H2,
have H4 : m > 0, from pos_of_mul_pos_left H2,
or.elim (le_or_gt n 1)
(assume H5 : n ≤ 1,
show n = 1, from le.antisymm H5 (succ_le_of_lt H3))
(assume H5 : n > 1,
have H6 : n * m ≥ 2 * 1, from mul_le_mul (succ_le_of_lt H5) (succ_le_of_lt H4),
have H7 : 1 ≥ 2, from !mul_one ▸ H ▸ H6,
absurd !self_lt_succ (not_lt_of_le H7))
theorem eq_one_of_mul_eq_one_left {n m : ℕ} (H : n * m = 1) : m = 1 :=
eq_one_of_mul_eq_one_right (!mul.comm ▸ H)
theorem eq_one_of_mul_eq_self_left {n m : ℕ} (Hpos : n > 0) (H : m * n = n) : m = 1 :=
eq_of_mul_eq_mul_right Hpos (H ⬝ !one_mul⁻¹)
theorem eq_one_of_mul_eq_self_right {n m : ℕ} (Hpos : m > 0) (H : m * n = m) : n = 1 :=
eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H)
end nat
|
2b08afc17b182d85d2468fbad65e601a52ee8276 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/ind_cnst_params.lean | 86c745fd9d740c4d19826b2dce7d8cac72665990 | [
"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 | 276 | lean | inductive foo
| mk (a : nat) (b : nat) : bool → foo
#print foo.mk
#check foo.mk 0 0 tt
universe variables u
inductive List (α : Type u)
| nil {} (a : nat) : List
| cons (hd : α) (tail : List) : List
#check List.cons "a" (List.nil 1)
#check List.cons "a" (List.nil 2)
|
e7b99d5db709e124c6e2e16efe0d463c932457d2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/auxDeclIssue.lean | f1e114499725be463e7cbb8b1abdfaa498ac3642 | [
"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 | 376 | lean | --
theorem ex1 : False :=
by {
assumption -- should not use the auxiliary declaration `ex1 : False`
}
variable (x y : Nat) in
theorem ex2 : x = y :=
by {
subst x; -- should not use the auxiliary declaration `ex2 : x = y`
exact rfl
}
set_option pp.auxDecls true in
theorem ex3 : False :=
by {
assumption -- should not use the auxiliary declaration `ex1 : False`
}
|
9d844fbaeb330214e89de1d9f43445223937ff50 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/data/real/nnreal.lean | 5a93d29ec1d57f12fcd8f48b42bfa98236d6f85c | [
"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 | 29,670 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.big_operators.ring
import data.real.basic
import algebra.indicator_function
import algebra.algebra.basic
import algebra.order.nonneg
/-!
# Nonnegative real numbers
In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers,
a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`:
* the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally
complete linear order with a bottom element, `conditionally_complete_linear_order_bot`;
* `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`;
these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a conditionally
complete linear ordered archimedean commutative semifield; we have no typeclass for this in
`mathlib` yet, so we define the following instances instead:
- `linear_ordered_semiring ℝ≥0`;
- `ordered_comm_semiring ℝ≥0`;
- `canonically_ordered_comm_semiring ℝ≥0`;
- `linear_ordered_comm_group_with_zero ℝ≥0`;
- `canonically_linear_ordered_add_monoid ℝ≥0`;
- `archimedean ℝ≥0`;
- `conditionally_complete_linear_order_bot ℝ≥0`.
These instances are derived from corresponding instances about the type `{x : α // 0 ≤ x}` in an
appropriate ordered field/ring/group/monoid `α`. See `algebra/order/nonneg`.
* `real.to_nnreal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(real.to_nnreal x) = x` when `0 ≤ x` and
`↑(real.to_nnreal x) = 0` otherwise.
We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to
replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences
of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis
`hf : ∀ x, 0 ≤ f x`.
## Notations
This file defines `ℝ≥0` as a localized notation for `nnreal`.
-/
open_locale classical big_operators
/-- Nonnegative real numbers. -/
@[derive [
ordered_semiring, comm_monoid_with_zero, -- to ensure these instance are computable
semilattice_inf_bot, densely_ordered,
canonically_linear_ordered_add_monoid, linear_ordered_comm_group_with_zero, archimedean,
linear_ordered_semiring, ordered_comm_semiring, canonically_ordered_comm_semiring,
has_sub, has_ordered_sub, has_div, inhabited]]
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 : ℝ≥0) : n.val = n := rfl
instance : can_lift ℝ ℝ≥0 :=
{ coe := coe,
cond := λ r, 0 ≤ r,
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
/-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/
noncomputable def _root_.real.to_nnreal (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩
lemma _root_.real.coe_to_nnreal (r : ℝ) (hr : 0 ≤ r) : (real.to_nnreal r : ℝ) = r :=
max_eq_left hr
lemma _root_.real.le_coe_to_nnreal (r : ℝ) : r ≤ real.to_nnreal r :=
le_max_left r 0
lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2
@[norm_cast]
theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl
example : has_zero ℝ≥0 := by apply_instance
example : has_one ℝ≥0 := by apply_instance
example : has_add ℝ≥0 := by apply_instance
noncomputable example : has_sub ℝ≥0 := by apply_instance
example : has_mul ℝ≥0 := by apply_instance
noncomputable example : has_inv ℝ≥0 := by apply_instance
noncomputable example : has_div ℝ≥0 := by apply_instance
noncomputable example : has_le ℝ≥0 := by apply_instance
example : has_bot ℝ≥0 := by apply_instance
example : inhabited ℝ≥0 := by apply_instance
example : nontrivial ℝ≥0 := by apply_instance
protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective
@[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ :=
nnreal.coe_injective.eq_iff
protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl
protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl
protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl
protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl
protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl
protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl
@[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl
@[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl
@[simp, norm_cast] 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, norm_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 :=
by rw [← nnreal.coe_zero, nnreal.coe_eq]
@[simp, norm_cast] protected lemma coe_eq_one (r : ℝ≥0) : ↑r = (1 : ℝ) ↔ r = 1 :=
by rw [← nnreal.coe_one, nnreal.coe_eq]
lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast
example : comm_semiring ℝ≥0 := by apply_instance
/-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/
def to_real_hom : ℝ≥0 →+* ℝ :=
⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩
@[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl
section actions
/-- A `mul_action` over `ℝ` restricts to a `mul_action` over `ℝ≥0`. -/
instance {M : Type*} [mul_action ℝ M] : mul_action ℝ≥0 M :=
mul_action.comp_hom M to_real_hom.to_monoid_hom
lemma smul_def {M : Type*} [mul_action ℝ M] (c : ℝ≥0) (x : M) :
c • x = (c : ℝ) • x := rfl
instance {M N : Type*} [mul_action ℝ M] [mul_action ℝ N] [has_scalar M N]
[is_scalar_tower ℝ M N] : is_scalar_tower ℝ≥0 M N :=
{ smul_assoc := λ r, (smul_assoc (r : ℝ) : _)}
instance smul_comm_class_left {M N : Type*} [mul_action ℝ N] [has_scalar M N]
[smul_comm_class ℝ M N] : smul_comm_class ℝ≥0 M N :=
{ smul_comm := λ r, (smul_comm (r : ℝ) : _)}
instance smul_comm_class_right {M N : Type*} [mul_action ℝ N] [has_scalar M N]
[smul_comm_class M ℝ N] : smul_comm_class M ℝ≥0 N :=
{ smul_comm := λ m r, (smul_comm m (r : ℝ) : _)}
/-- A `distrib_mul_action` over `ℝ` restricts to a `distrib_mul_action` over `ℝ≥0`. -/
instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ M] : distrib_mul_action ℝ≥0 M :=
distrib_mul_action.comp_hom M to_real_hom.to_monoid_hom
/-- A `module` over `ℝ` restricts to a `module` over `ℝ≥0`. -/
instance {M : Type*} [add_comm_monoid M] [module ℝ M] : module ℝ≥0 M :=
module.comp_hom M to_real_hom
/-- An `algebra` over `ℝ` restricts to an `algebra` over `ℝ≥0`. -/
instance {A : Type*} [semiring A] [algebra ℝ A] : algebra ℝ≥0 A :=
{ smul := (•),
commutes' := λ r x, by simp [algebra.commutes],
smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ) x, smul_def],
to_ring_hom := ((algebra_map ℝ A).comp (to_real_hom : ℝ≥0 →+* ℝ)) }
-- verify that the above produces instances we might care about
example : algebra ℝ≥0 ℝ := by apply_instance
example : distrib_mul_action (units ℝ≥0) ℝ := by apply_instance
end actions
example : monoid_with_zero ℝ≥0 := by apply_instance
example : comm_monoid_with_zero ℝ≥0 := by apply_instance
noncomputable example : comm_group_with_zero ℝ≥0 := by apply_instance
@[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) :
((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a :=
(to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _
@[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
to_real_hom.map_pow r n
@[simp, norm_cast] lemma coe_zpow (r : ℝ≥0) (n : ℤ) : ((r^n : ℝ≥0) : ℝ) = r^n :=
by cases n; simp
@[norm_cast] lemma coe_list_sum (l : list ℝ≥0) :
((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum :=
to_real_hom.map_list_sum l
@[norm_cast] lemma coe_list_prod (l : list ℝ≥0) :
((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod :=
to_real_hom.map_list_prod l
@[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) :
((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum :=
to_real_hom.map_multiset_sum s
@[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) :
((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod :=
to_real_hom.map_multiset_prod s
@[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} :
↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) :=
to_real_hom.map_sum _ _
lemma _root_.real.to_nnreal_sum_of_nonneg {α} {s : finset α} {f : α → ℝ}
(hf : ∀ a, a ∈ s → 0 ≤ f a) :
real.to_nnreal (∑ a in s, f a) = ∑ a in s, real.to_nnreal (f a) :=
begin
rw [←nnreal.coe_eq, nnreal.coe_sum, real.coe_to_nnreal _ (finset.sum_nonneg hf)],
exact finset.sum_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)),
end
@[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} :
↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) :=
to_real_hom.map_prod _ _
lemma _root_.real.to_nnreal_prod_of_nonneg {α} {s : finset α} {f : α → ℝ}
(hf : ∀ a, a ∈ s → 0 ≤ f a) :
real.to_nnreal (∏ a in s, f a) = ∏ a in s, real.to_nnreal (f a) :=
begin
rw [←nnreal.coe_eq, nnreal.coe_prod, real.coe_to_nnreal _ (finset.prod_nonneg hf)],
exact finset.prod_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)),
end
lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) :=
by norm_cast
@[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n :=
to_real_hom.map_nat_cast n
noncomputable example : linear_order ℝ≥0 := by apply_instance
@[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl
@[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl
@[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl
protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2
protected lemma _root_.real.to_nnreal_mono : monotone real.to_nnreal :=
λ x y h, max_le_max h (le_refl 0)
@[simp] lemma _root_.real.to_nnreal_coe {r : ℝ≥0} : real.to_nnreal r = r :=
nnreal.eq $ max_eq_left r.2
@[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n :=
nnreal.eq (nnreal.coe_nat_cast n).symm
@[simp] lemma to_nnreal_coe_nat (n : ℕ) : real.to_nnreal n = n :=
nnreal.eq $ by simp [real.coe_to_nnreal]
/-- `real.to_nnreal` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/
noncomputable def gi : galois_insertion real.to_nnreal coe :=
galois_insertion.monotone_intro nnreal.coe_mono real.to_nnreal_mono
real.le_coe_to_nnreal (λ _, real.to_nnreal_coe)
-- note that anything involving the (decidability of the) linear order, including `⊔`/`⊓` (min, max)
-- will be noncomputable, everything else should not be.
example : order_bot ℝ≥0 := by apply_instance
example : partial_order ℝ≥0 := by apply_instance
noncomputable example : canonically_linear_ordered_add_monoid ℝ≥0 := by apply_instance
noncomputable example : linear_ordered_add_comm_monoid ℝ≥0 := by apply_instance
noncomputable example : distrib_lattice ℝ≥0 := by apply_instance
noncomputable example : semilattice_inf_bot ℝ≥0 := by apply_instance
noncomputable example : semilattice_sup_bot ℝ≥0 := by apply_instance
noncomputable example : linear_ordered_semiring ℝ≥0 := by apply_instance
example : ordered_comm_semiring ℝ≥0 := by apply_instance
noncomputable example : linear_ordered_comm_monoid ℝ≥0 := by apply_instance
noncomputable example : linear_ordered_comm_monoid_with_zero ℝ≥0 := by apply_instance
noncomputable example : linear_ordered_comm_group_with_zero ℝ≥0 := by apply_instance
example : canonically_ordered_comm_semiring ℝ≥0 := by apply_instance
example : densely_ordered ℝ≥0 := by apply_instance
example : no_top_order ℝ≥0 := by apply_instance
lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s :=
iff.intro
(assume ⟨b, hb⟩, ⟨real.to_nnreal b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from
le_max_of_le_left $ 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 : ℝ≥0 → ℝ) '' s) :=
⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩
noncomputable instance : conditionally_complete_linear_order_bot ℝ≥0 :=
nonneg.conditionally_complete_linear_order_bot real.Sup_empty.le
lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) :=
eq.symm $ @subset_Sup_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $
real.Sup_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2
lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) :=
eq.symm $ @subset_Inf_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $
real.Inf_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2
example : archimedean ℝ≥0 := by apply_instance
lemma le_of_forall_pos_le_add {a b : ℝ≥0} (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
-- TODO: generalize to some ordered add_monoids, based on #6145
lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c :=
by { refine le_trans _ h, exact (le_add_iff_nonneg_right _).mpr zero_le' }
lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c :=
by { refine le_trans _ h, exact (le_add_iff_nonneg_left _).mpr zero_le' }
lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) :
a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ real.to_nnreal 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 [real.coe_to_nnreal _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩)
(assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb)
lemma bot_eq_zero : (⊥ : ℝ≥0) = 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
lemma finset_sup_div {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) :
s.sup f / r = s.sup (λ a, f a / r) :=
by simp only [div_eq_inv_mul, mul_finset_sup]
@[simp, norm_cast] lemma coe_max (x y : ℝ≥0) :
((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) :=
nnreal.coe_mono.map_max
@[simp, norm_cast] lemma coe_min (x y : ℝ≥0) :
((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) :=
nnreal.coe_mono.map_min
@[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2
end nnreal
namespace real
section to_nnreal
@[simp] lemma to_nnreal_zero : real.to_nnreal 0 = 0 :=
by simp [real.to_nnreal]; refl
@[simp] lemma to_nnreal_one : real.to_nnreal 1 = 1 :=
by simp [real.to_nnreal, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl
@[simp] lemma to_nnreal_pos {r : ℝ} : 0 < real.to_nnreal r ↔ 0 < r :=
by simp [real.to_nnreal, nnreal.coe_lt_coe.symm, lt_irrefl]
@[simp] lemma to_nnreal_eq_zero {r : ℝ} : real.to_nnreal r = 0 ↔ r ≤ 0 :=
by simpa [-to_nnreal_pos] using (not_iff_not.2 (@to_nnreal_pos r))
lemma to_nnreal_of_nonpos {r : ℝ} : r ≤ 0 → real.to_nnreal r = 0 :=
to_nnreal_eq_zero.2
@[simp] lemma coe_to_nnreal' (r : ℝ) : (real.to_nnreal r : ℝ) = max r 0 := rfl
@[simp] lemma to_nnreal_le_to_nnreal_iff {r p : ℝ} (hp : 0 ≤ p) :
real.to_nnreal r ≤ real.to_nnreal p ↔ r ≤ p :=
by simp [nnreal.coe_le_coe.symm, real.to_nnreal, hp]
@[simp] lemma to_nnreal_lt_to_nnreal_iff' {r p : ℝ} :
real.to_nnreal r < real.to_nnreal p ↔ r < p ∧ 0 < p :=
by simp [nnreal.coe_lt_coe.symm, real.to_nnreal, lt_irrefl]
lemma to_nnreal_lt_to_nnreal_iff {r p : ℝ} (h : 0 < p) :
real.to_nnreal r < real.to_nnreal p ↔ r < p :=
to_nnreal_lt_to_nnreal_iff'.trans (and_iff_left h)
lemma to_nnreal_lt_to_nnreal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) :
real.to_nnreal r < real.to_nnreal p ↔ r < p :=
to_nnreal_lt_to_nnreal_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩
@[simp] lemma to_nnreal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
real.to_nnreal (r + p) = real.to_nnreal r + real.to_nnreal p :=
nnreal.eq $ by simp [real.to_nnreal, hr, hp, add_nonneg]
lemma to_nnreal_add_to_nnreal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) :
real.to_nnreal r + real.to_nnreal p = real.to_nnreal (r + p) :=
(real.to_nnreal_add hr hp).symm
lemma to_nnreal_le_to_nnreal {r p : ℝ} (h : r ≤ p) :
real.to_nnreal r ≤ real.to_nnreal p :=
real.to_nnreal_mono h
lemma to_nnreal_add_le {r p : ℝ} :
real.to_nnreal (r + p) ≤ real.to_nnreal r + real.to_nnreal p :=
nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe
lemma to_nnreal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : real.to_nnreal r ≤ p ↔ r ≤ ↑p :=
nnreal.gi.gc r p
lemma le_to_nnreal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ real.to_nnreal p ↔ ↑r ≤ p :=
by rw [← nnreal.coe_le_coe, real.coe_to_nnreal p hp]
lemma le_to_nnreal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ real.to_nnreal p ↔ ↑r ≤ p :=
(le_or_lt 0 p).elim le_to_nnreal_iff_coe_le $ λ hp,
by simp only [(hp.trans_le r.coe_nonneg).not_le, to_nnreal_eq_zero.2 hp.le, hr.not_le]
lemma to_nnreal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : real.to_nnreal r < p ↔ r < ↑p :=
by rw [← nnreal.coe_lt_coe, real.coe_to_nnreal r ha]
lemma lt_to_nnreal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < real.to_nnreal p ↔ ↑r < p :=
begin
cases le_total 0 p,
{ rw [← nnreal.coe_lt_coe, real.coe_to_nnreal p h] },
{ rw [to_nnreal_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 (nnreal.coe_nonneg _) rp),
contradiction } }
end
@[simp] lemma to_nnreal_bit0 {r : ℝ} (hr : 0 ≤ r) :
real.to_nnreal (bit0 r) = bit0 (real.to_nnreal r) :=
real.to_nnreal_add hr hr
@[simp] lemma to_nnreal_bit1 {r : ℝ} (hr : 0 ≤ r) :
real.to_nnreal (bit1 r) = bit1 (real.to_nnreal r) :=
(real.to_nnreal_add (by simp [hr]) zero_le_one).trans (by simp [to_nnreal_one, bit1, hr])
end to_nnreal
end real
open real
namespace nnreal
section mul
lemma mul_eq_mul_left {a b c : ℝ≥0} (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 mul_left_cancel₀ (mt (@nnreal.eq_iff a 0).1 h) },
{ assume h, rw [h] }
end
lemma _root_.real.to_nnreal_mul {p q : ℝ} (hp : 0 ≤ p) :
real.to_nnreal (p * q) = real.to_nnreal p * real.to_nnreal q :=
begin
cases le_total 0 q with hq hq,
{ apply nnreal.eq,
simp [real.to_nnreal, hp, hq, max_eq_left, mul_nonneg] },
{ have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq,
rw [to_nnreal_eq_zero.2 hq, to_nnreal_eq_zero.2 hpq, mul_zero] }
end
end mul
section pow
lemma pow_antitone_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) :
a ^ n ≤ a ^ m :=
begin
rcases le_iff_exists_add.mp mn with ⟨k, rfl⟩,
rw [← mul_one (a ^ m), pow_add],
refine mul_le_mul rfl.le (pow_le_one _ (zero_le a) a1) _ _;
exact pow_nonneg (zero_le _) _,
end
lemma exists_mem_Ico_zpow
{x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) :
∃ n : ℤ, x ∈ set.Ico (y ^ n) (y ^ (n + 1)) :=
begin
obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, (y : ℝ) ^ n ≤ x ∧ (x : ℝ) < y ^ (n + 1) :=
exists_mem_Ico_zpow (bot_lt_iff_ne_bot.mpr hx) hy,
rw ← nnreal.coe_zpow at hn h'n,
exact ⟨n, hn, h'n⟩,
end
lemma exists_mem_Ioc_zpow
{x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) :
∃ n : ℤ, x ∈ set.Ioc (y ^ n) (y ^ (n + 1)) :=
begin
obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, (y : ℝ) ^ n < x ∧ (x : ℝ) ≤ y ^ (n + 1) :=
exists_mem_Ioc_zpow (bot_lt_iff_ne_bot.mpr hx) hy,
rw ← nnreal.coe_zpow at hn h'n,
exact ⟨n, hn, h'n⟩,
end
end pow
section sub
/-!
### Lemmas about subtraction
In this section we provide a few lemmas about subtraction that do not fit well into any other
typeclass. For lemmas about subtraction and addition see lemmas
about `has_ordered_sub` in the file `algebra.order.sub`. See also `mul_tsub` and `tsub_mul`. -/
lemma sub_def {r p : ℝ≥0} : r - p = real.to_nnreal (r - p) := rfl
lemma coe_sub_def {r p : ℝ≥0} : ↑(r - p) = max (r - p : ℝ) 0 := rfl
noncomputable example : has_ordered_sub ℝ≥0 := by apply_instance
lemma sub_div (a b c : ℝ≥0) : (a - b) / c = a / c - b / c :=
by simp only [div_eq_mul_inv, tsub_mul]
end sub
section inv
lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) :
(∑ i in s, f i) / b = ∑ i in s, (f i / b) :=
by simp only [div_eq_mul_inv, finset.sum_mul]
@[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r :=
by simp [pos_iff_ne_zero]
lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p :=
by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp)
protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev₀ _ _
lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 :=
if h : r = 0 then by simp [h] else by rw [div_self h]
@[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p :=
by rw [← mul_le_mul_left (pos_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 (pos_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 (pos_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_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm]
lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r :=
@div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr
lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b :=
@div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr
lemma div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b :=
if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h
lemma div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c :=
div_le_of_le_mul $ mul_comm b c ▸ h
lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b :=
@le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr
lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b :=
@le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr
lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r :=
lt_iff_lt_of_le_iff_le (le_div_iff hr)
lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b :=
lt_iff_lt_of_le_iff_le (le_div_iff' hr)
lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b :=
lt_iff_lt_of_le_iff_le (div_le_iff hr)
lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b :=
lt_iff_lt_of_le_iff_le (div_le_iff' hr)
lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b :=
begin
refine (lt_div_iff $ λ hr, false.elim _).1 h,
subst r,
simpa using h
end
lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) :
a / b ≤ a / c :=
begin
by_cases a0 : a = 0,
{ rw [a0, zero_div, zero_div] },
{ cases a with a ha,
replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)),
exact (div_le_div_left a0 b0 c0).mpr cb }
end
lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) :
a / b ≤ a / c ↔ c ≤ b :=
by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm,
mul_le_mul_left a0]
lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y :=
le_of_forall_ge_of_dense $ assume a ha,
have hx : x ≠ 0 := pos_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 using half_lt_self zero_ne_one.symm
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] 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 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 _root_.real.to_nnreal_inv {x : ℝ} :
real.to_nnreal x⁻¹ = (real.to_nnreal x)⁻¹ :=
begin
by_cases hx : 0 ≤ x,
{ nth_rewrite 0 ← real.coe_to_nnreal x hx,
rw [←nnreal.coe_inv, real.to_nnreal_coe], },
{ have hx' := le_of_not_ge hx,
rw [to_nnreal_eq_zero.mpr hx', inv_zero, to_nnreal_eq_zero.mpr (inv_nonpos.mpr hx')], },
end
lemma _root_.real.to_nnreal_div {x y : ℝ} (hx : 0 ≤ x) :
real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y :=
by rw [div_eq_mul_inv, div_eq_mul_inv, ← real.to_nnreal_inv, ← real.to_nnreal_mul hx]
lemma _root_.real.to_nnreal_div' {x y : ℝ} (hy : 0 ≤ y) :
real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y :=
by rw [div_eq_inv_mul, div_eq_inv_mul, real.to_nnreal_mul (inv_nonneg.2 hy), real.to_nnreal_inv]
lemma inv_lt_one_iff {x : ℝ≥0} (hx : x ≠ 0) : x⁻¹ < 1 ↔ 1 < x :=
by rwa [← one_div, div_lt_iff hx, one_mul]
lemma inv_lt_one {x : ℝ≥0} (hx : 1 < x) : x⁻¹ < 1 :=
(inv_lt_one_iff (zero_lt_one.trans hx).ne').2 hx
lemma zpow_pos {x : ℝ≥0} (hx : x ≠ 0) (n : ℤ) : 0 < x ^ n :=
begin
cases n,
{ exact pow_pos hx.bot_lt _ },
{ simp [pow_pos hx.bot_lt _] }
end
end inv
@[simp] lemma abs_eq (x : ℝ≥0) : |(x : ℝ)| = x :=
abs_of_nonneg x.property
end nnreal
namespace real
/-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/
@[pp_nodot] noncomputable def nnabs : monoid_with_zero_hom ℝ ℝ≥0 :=
{ to_fun := λ x, ⟨|x|, abs_nonneg x⟩,
map_zero' := by { ext, simp },
map_one' := by { ext, simp },
map_mul' := λ x y, by { ext, simp [abs_mul] } }
@[norm_cast, simp] lemma coe_nnabs (x : ℝ) : (nnabs x : ℝ) = |x| :=
rfl
@[simp] lemma nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : nnabs x = to_nnreal x :=
by { ext, simp [coe_to_nnreal x h, abs_of_nonneg h] }
lemma coe_to_nnreal_le (x : ℝ) : (to_nnreal x : ℝ) ≤ |x| :=
max_le (le_abs_self _) (abs_nonneg _)
lemma cast_nat_abs_eq_nnabs_cast (n : ℤ) :
(n.nat_abs : ℝ≥0) = nnabs n :=
by { ext, rw [nnreal.coe_nat_cast, int.cast_nat_abs, real.coe_nnabs] }
end real
|
11d52cb75cd4674df25aba6977e0819151a1238f | 9028d228ac200bbefe3a711342514dd4e4458bff | /src/algebra/algebra/basic.lean | 09c2879bf97411d486c750539d947beb681d9f8c | [
"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 | 44,770 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Yury Kudryashov
-/
import tactic.nth_rewrite
import data.matrix.basic
import linear_algebra.tensor_product
import ring_theory.subring
import deprecated.subring
/-!
# Algebra over Commutative Semiring (under category)
In this file we define algebra over commutative (semi)rings, algebra homomorphisms `alg_hom`,
algebra equivalences `alg_equiv`. We also define usual operations on `alg_hom`s
(`id`, `comp`).
`subalgebra`s are defined in `algebra.algebra.subalgebra`.
If `S` is an `R`-algebra and `A` is an `S`-algebra then `algebra.comap.algebra R S A` can be used
to provide `A` with a structure of an `R`-algebra. Other than that, `algebra.comap` is now
deprecated and replcaed with `is_scalar_tower`.
## Notations
* `A →ₐ[R] B` : `R`-algebra homomorphism from `A` to `B`.
* `A ≃ₐ[R] B` : `R`-algebra equivalence from `A` to `B`.
-/
universes u v w u₁ v₁
open_locale tensor_product big_operators
section prio
-- We set this priority to 0 later in this file
set_option extends_priority 200 /- control priority of
`instance [algebra R A] : has_scalar R A` -/
/-- The category of R-algebras where R is a commutative
ring is the under category R ↓ CRing. In the categorical
setting we have a forgetful functor R-Alg ⥤ R-Mod.
However here it extends module in order to preserve
definitional equality in certain cases. -/
@[nolint has_inhabited_instance]
class algebra (R : Type u) (A : Type v) [comm_semiring R] [semiring A]
extends has_scalar R A, R →+* A :=
(commutes' : ∀ r x, to_fun r * x = x * to_fun r)
(smul_def' : ∀ r x, r • x = to_fun r * x)
end prio
/-- Embedding `R →+* A` given by `algebra` structure. -/
def algebra_map (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : R →+* A :=
algebra.to_ring_hom
/-- Creating an algebra from a morphism to the center of a semiring. -/
def ring_hom.to_algebra' {R S} [comm_semiring R] [semiring S] (i : R →+* S)
(h : ∀ c x, i c * x = x * i c) :
algebra R S :=
{ smul := λ c x, i c * x,
commutes' := h,
smul_def' := λ c x, rfl,
to_ring_hom := i}
/-- Creating an algebra from a morphism to a commutative semiring. -/
def ring_hom.to_algebra {R S} [comm_semiring R] [comm_semiring S] (i : R →+* S) :
algebra R S :=
i.to_algebra' $ λ _, mul_comm _
lemma ring_hom.algebra_map_to_algebra {R S} [comm_semiring R] [comm_semiring S]
(i : R →+* S) :
@algebra_map R S _ _ i.to_algebra = i :=
rfl
namespace algebra
variables {R : Type u} {S : Type v} {A : Type w}
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • 1) * x = x * (r • 1) = r • x` for all `r : R` and `x : A`, then `A` is an `algebra`
over `R`. -/
def of_semimodule' [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x : A), (r • 1) * x = r • x)
(h₂ : ∀ (r : R) (x : A), x * (r • 1) = r • x) : algebra R A :=
{ to_fun := λ r, r • 1,
map_one' := one_smul _ _,
map_mul' := λ r₁ r₂, by rw [h₁, mul_smul],
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul r₁ r₂ 1,
commutes' := λ r x, by simp only [h₁, h₂],
smul_def' := λ r x, by simp only [h₁] }
/-- Let `R` be a commutative semiring, let `A` be a semiring with a `semimodule R` structure.
If `(r • x) * y = x * (r • y) = r • (x * y)` for all `r : R` and `x y : A`, then `A`
is an `algebra` over `R`. -/
def of_semimodule [comm_semiring R] [semiring A] [semimodule R A]
(h₁ : ∀ (r : R) (x y : A), (r • x) * y = r • (x * y))
(h₂ : ∀ (r : R) (x y : A), x * (r • y) = r • (x * y)) : algebra R A :=
of_semimodule' (λ r x, by rw [h₁, one_mul]) (λ r x, by rw [h₂, mul_one])
section semiring
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R A]
lemma smul_def'' (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
/--
To prove two algebra structures on a fixed `[comm_semiring R] [semiring A]` agree,
it suffices to check the `algebra_map`s agree.
-/
-- We'll later use this to show `algebra ℤ M` is a subsingleton.
@[ext]
lemma algebra_ext {R : Type*} [comm_semiring R] {A : Type*} [semiring A] (P Q : algebra R A)
(w : ∀ (r : R), by { haveI := P, exact algebra_map R A r } = by { haveI := Q, exact algebra_map R A r }) :
P = Q :=
begin
unfreezingI { rcases P with ⟨⟨P⟩⟩, rcases Q with ⟨⟨Q⟩⟩ },
congr,
{ funext r a,
replace w := congr_arg (λ s, s * a) (w r),
simp only [←algebra.smul_def''] at w,
apply w, },
{ ext r,
exact w r, },
{ apply proof_irrel_heq, },
{ apply proof_irrel_heq, },
end
@[priority 200] -- see Note [lower instance priority]
instance to_semimodule : semimodule R A :=
{ one_smul := by simp [smul_def''],
mul_smul := by simp [smul_def'', mul_assoc],
smul_add := by simp [smul_def'', mul_add],
smul_zero := by simp [smul_def''],
add_smul := by simp [smul_def'', add_mul],
zero_smul := by simp [smul_def''] }
-- from now on, we don't want to use the following instance anymore
attribute [instance, priority 0] algebra.to_has_scalar
lemma smul_def (r : R) (x : A) : r • x = algebra_map R A r * x :=
algebra.smul_def' r x
lemma algebra_map_eq_smul_one (r : R) : algebra_map R A r = r • 1 :=
calc algebra_map R A r = algebra_map R A r * 1 : (mul_one _).symm
... = r • 1 : (algebra.smul_def r 1).symm
theorem commutes (r : R) (x : A) : algebra_map R A r * x = x * algebra_map R A r :=
algebra.commutes' r x
theorem left_comm (r : R) (x y : A) : x * (algebra_map R A r * y) = algebra_map R A r * (x * y) :=
by rw [← mul_assoc, ← commutes, mul_assoc]
@[simp] lemma mul_smul_comm (s : R) (x y : A) :
x * (s • y) = s • (x * y) :=
by rw [smul_def, smul_def, left_comm]
@[simp] lemma smul_mul_assoc (r : R) (x y : A) :
(r • x) * y = r • (x * y) :=
by rw [smul_def, smul_def, mul_assoc]
section
variables (r : R) (a : A)
@[simp] lemma bit0_smul_one : bit0 r • (1 : A) = r • 2 :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit0 : bit0 r • bit0 a = r • (bit0 (bit0 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit0_smul_bit1 : bit0 r • bit1 a = r • (bit0 (bit1 a)) :=
by simp [bit0, add_smul, smul_add]
@[simp] lemma bit1_smul_one : bit1 r • (1 : A) = r • 2 + 1 :=
by simp [bit1, add_smul, smul_add]
@[simp] lemma bit1_smul_bit0 : bit1 r • bit0 a = r • (bit0 (bit0 a)) + bit0 a :=
by simp [bit1, add_smul, smul_add]
@[simp] lemma bit1_smul_bit1 : bit1 r • bit1 a = r • (bit0 (bit1 a)) + bit1 a :=
by { simp only [bit0, bit1, add_smul, smul_add, one_smul], abel }
end
variables (R A)
/--
The canonical ring homomorphism `algebra_map R A : R →* A` for any `R`-algebra `A`,
packaged as an `R`-linear map.
-/
protected def linear_map : R →ₗ[R] A :=
{ map_smul' := λ x y, begin dsimp, simp [algebra.smul_def], end,
..algebra_map R A }
@[simp]
lemma linear_map_apply (r : R) : algebra.linear_map R A r = algebra_map R A r := rfl
instance id : algebra R R := (ring_hom.id R).to_algebra
variables {R A}
namespace id
@[simp] lemma map_eq_self (x : R) : algebra_map R R x = x := rfl
@[simp] lemma smul_eq_mul (x y : R) : x • y = x * y := rfl
end id
/-- Algebra over a subsemiring. -/
instance of_subsemiring (S : subsemiring R) : algebra S A :=
{ smul := λ s x, (s : R) • x,
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp (subsemiring.subtype S) }
/-- Algebra over a subring. -/
instance of_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A]
(S : subring R) : algebra S A :=
{ smul := λ s x, (s : R) • x,
commutes' := λ r x, algebra.commutes r x,
smul_def' := λ r x, algebra.smul_def r x,
.. (algebra_map R A).comp (subring.subtype S) }
lemma algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S →+* R) = subring.subtype S := rfl
lemma coe_algebra_map_of_subring {R : Type*} [comm_ring R] (S : subring R) :
(algebra_map S R : S → R) = subtype.val := rfl
lemma algebra_map_of_subring_apply {R : Type*} [comm_ring R] (S : subring R) (x : S) :
algebra_map S R x = x := rfl
/-- Algebra over a set that is closed under the ring operations. -/
instance of_is_subring {R A : Type*} [comm_ring R] [ring A] [algebra R A]
(S : set R) [is_subring S] : algebra S A :=
algebra.of_subring S.to_subring
lemma is_subring_coe_algebra_map_hom {R : Type*} [comm_ring R] (S : set R) [is_subring S] :
(algebra_map S R : S →+* R) = is_subring.subtype S := rfl
lemma is_subring_coe_algebra_map {R : Type*} [comm_ring R] (S : set R) [is_subring S] :
(algebra_map S R : S → R) = subtype.val := rfl
lemma is_subring_algebra_map_apply {R : Type*} [comm_ring R] (S : set R) [is_subring S] (x : S) :
algebra_map S R x = x := rfl
lemma set_range_subset {R : Type*} [comm_ring R] {T₁ T₂ : set R} [is_subring T₁] (hyp : T₁ ⊆ T₂) :
set.range (algebra_map T₁ R) ⊆ T₂ :=
begin
rintros x ⟨⟨t, ht⟩, rfl⟩,
exact hyp ht,
end
variables (R A)
/-- The multiplication in an algebra is a bilinear map. -/
def lmul : A →ₗ A →ₗ A :=
linear_map.mk₂ R (*)
(λ x y z, add_mul x y z)
(λ c x y, by rw [smul_def, smul_def, mul_assoc _ x y])
(λ x y z, mul_add x y z)
(λ c x y, by rw [smul_def, smul_def, left_comm])
/-- The multiplication on the left in an algebra is a linear map. -/
def lmul_left (r : A) : A →ₗ A :=
lmul R A r
/-- The multiplication on the right in an algebra is a linear map. -/
def lmul_right (r : A) : A →ₗ A :=
(lmul R A).flip r
/-- Simultaneous multiplication on the left and right is a linear map. -/
def lmul_left_right (vw: A × A) : A →ₗ[R] A :=
(lmul_right R A vw.2).comp (lmul_left R A vw.1)
/-- The multiplication map on an algebra, as an `R`-linear map from `A ⊗[R] A` to `A`. -/
def lmul' : A ⊗[R] A →ₗ[R] A :=
tensor_product.lift (algebra.lmul R A)
variables {R A}
@[simp] lemma lmul_apply (p q : A) : lmul R A p q = p * q := rfl
@[simp] lemma lmul_left_apply (p q : A) : lmul_left R A p q = p * q := rfl
@[simp] lemma lmul_right_apply (p q : A) : lmul_right R A p q = q * p := rfl
@[simp] lemma lmul_left_right_apply (vw : A × A) (p : A) :
lmul_left_right R A vw p = vw.1 * p * vw.2 := rfl
@[simp] lemma lmul'_apply {x y} : algebra.lmul' R A (x ⊗ₜ y) = x * y :=
begin
dsimp [algebra.lmul'],
simp,
end
/-- Explicit characterization of the submonoid map in the case of an algebra.
`S` is made explicit to help with type inference -/
def algebra_map_submonoid (S : Type*) [semiring S] [algebra R S]
(M : submonoid R) : (submonoid S) :=
submonoid.map (algebra_map R S : R →* S) M
lemma mem_algebra_map_submonoid_of_mem [algebra R S] {M : submonoid R} (x : M) :
(algebra_map R S x) ∈ algebra_map_submonoid S M :=
set.mem_image_of_mem (algebra_map R S) x.2
instance linear_map.semimodule' (R : Type u) [comm_semiring R]
(M : Type v) [add_comm_monoid M] [semimodule R M]
(S : Type w) [comm_semiring S] [algebra R S] : semimodule S (M →ₗ[R] S) :=
{ smul := λ s f, linear_map.llcomp _ _ _ _ (algebra.lmul R S s) f,
one_smul := λ f, linear_map.ext $ λ x, one_mul _,
mul_smul := λ s₁ s₂ f, linear_map.ext $ λ x, mul_assoc _ _ _,
smul_add := λ s f g, linear_map.map_add _ _ _,
smul_zero := λ s, linear_map.map_zero _,
add_smul := λ s₁ s₂ f, linear_map.ext $ λ x, add_mul _ _ _,
zero_smul := λ f, linear_map.ext $ λ x, zero_mul _ }
end semiring
section ring
variables [comm_ring R]
variables (R)
/-- A `semiring` that is an `algebra` over a commutative ring carries a natural `ring` structure. -/
def semiring_to_ring [semiring A] [algebra R A] : ring A := {
..semimodule.add_comm_monoid_to_add_comm_group R,
..(infer_instance : semiring A) }
variables {R}
lemma mul_sub_algebra_map_commutes [ring A] [algebra R A] (x : A) (r : R) :
x * (x - algebra_map R A r) = (x - algebra_map R A r) * x :=
by rw [mul_sub, ←commutes, sub_mul]
lemma mul_sub_algebra_map_pow_commutes [ring A] [algebra R A] (x : A) (r : R) (n : ℕ) :
x * (x - algebra_map R A r) ^ n = (x - algebra_map R A r) ^ n * x :=
begin
induction n with n ih,
{ simp },
{ rw [pow_succ, ←mul_assoc, mul_sub_algebra_map_commutes,
mul_assoc, ih, ←mul_assoc], }
end
end ring
end algebra
namespace module
instance endomorphism_algebra (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] : algebra R (M →ₗ[R] M) :=
{ to_fun := λ r, r • linear_map.id,
map_one' := one_smul _ _,
map_zero' := zero_smul _ _,
map_add' := λ r₁ r₂, add_smul _ _ _,
map_mul' := λ r₁ r₂, by { ext x, simp [mul_smul] },
commutes' := by { intros, ext, simp },
smul_def' := by { intros, ext, simp } }
lemma algebra_map_End_eq_smul_id (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] (a : R) :
(algebra_map R (End R M)) a = a • linear_map.id := rfl
lemma algebra_map_End_apply (R : Type u) (M : Type v)
[comm_ring R] [add_comm_group M] [module R M] (a : R) (m : M) :
(algebra_map R (End R M)) a m = a • m := rfl
lemma ker_algebra_map_End (K : Type u) (V : Type v)
[field K] [add_comm_group V] [vector_space K V] (a : K) (ha : a ≠ 0) :
((algebra_map K (End K V)) a).ker = ⊥ :=
linear_map.ker_smul _ _ ha
end module
instance matrix_algebra (n : Type u) (R : Type v)
[decidable_eq n] [fintype n] [comm_semiring R] : algebra R (matrix n n R) :=
{ commutes' := by { intros, simp [matrix.scalar], },
smul_def' := by { intros, simp [matrix.scalar], },
..(matrix.scalar n) }
set_option old_structure_cmd true
/-- Defining the homomorphism in the category R-Alg. -/
@[nolint has_inhabited_instance]
structure alg_hom (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] extends ring_hom A B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
run_cmd tactic.add_doc_string `alg_hom.to_ring_hom "Reinterpret an `alg_hom` as a `ring_hom`"
infixr ` →ₐ `:25 := alg_hom _
notation A ` →ₐ[`:25 R `] ` B := alg_hom R A B
namespace alg_hom
variables {R : Type u} {A : Type v} {B : Type w} {C : Type u₁} {D : Type v₁}
section semiring
variables [comm_semiring R] [semiring A] [semiring B] [semiring C] [semiring D]
variables [algebra R A] [algebra R B] [algebra R C] [algebra R D]
instance : has_coe_to_fun (A →ₐ[R] B) := ⟨_, λ f, f.to_fun⟩
instance coe_ring_hom : has_coe (A →ₐ[R] B) (A →+* B) := ⟨alg_hom.to_ring_hom⟩
instance coe_monoid_hom : has_coe (A →ₐ[R] B) (A →* B) := ⟨λ f, ↑(f : A →+* B)⟩
instance coe_add_monoid_hom : has_coe (A →ₐ[R] B) (A →+ B) := ⟨λ f, ↑(f : A →+* B)⟩
@[simp, norm_cast] lemma coe_mk {f : A → B} (h₁ h₂ h₃ h₄ h₅) :
⇑(⟨f, h₁, h₂, h₃, h₄, h₅⟩ : A →ₐ[R] B) = f := rfl
@[simp, norm_cast] lemma coe_to_ring_hom (f : A →ₐ[R] B) : ⇑(f : A →+* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →* B) = f := rfl
-- as `simp` can already prove this lemma, it is not tagged with the `simp` attribute.
@[norm_cast] lemma coe_to_add_monoid_hom (f : A →ₐ[R] B) : ⇑(f : A →+ B) = f := rfl
variables (φ : A →ₐ[R] B)
theorem coe_fn_inj ⦃φ₁ φ₂ : A →ₐ[R] B⦄ (H : ⇑φ₁ = φ₂) : φ₁ = φ₂ :=
by { cases φ₁, cases φ₂, congr, exact H }
theorem coe_ring_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+* B)) :=
λ φ₁ φ₂ H, coe_fn_inj $ show ((φ₁ : (A →+* B)) : A → B) = ((φ₂ : (A →+* B)) : A → B),
from congr_arg _ H
theorem coe_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →* B)) :=
ring_hom.coe_monoid_hom_injective.comp coe_ring_hom_injective
theorem coe_add_monoid_hom_injective : function.injective (coe : (A →ₐ[R] B) → (A →+ B)) :=
ring_hom.coe_add_monoid_hom_injective.comp coe_ring_hom_injective
@[ext]
theorem ext {φ₁ φ₂ : A →ₐ[R] B} (H : ∀ x, φ₁ x = φ₂ x) : φ₁ = φ₂ :=
coe_fn_inj $ funext H
theorem ext_iff {φ₁ φ₂ : A →ₐ[R] B} : φ₁ = φ₂ ↔ ∀ x, φ₁ x = φ₂ x :=
⟨by { rintro rfl x, refl }, ext⟩
@[simp]
theorem commutes (r : R) : φ (algebra_map R A r) = algebra_map R B r := φ.commutes' r
theorem comp_algebra_map : (φ : A →+* B).comp (algebra_map R A) = algebra_map R B :=
ring_hom.ext $ φ.commutes
@[simp] lemma map_add (r s : A) : φ (r + s) = φ r + φ s :=
φ.to_ring_hom.map_add r s
@[simp] lemma map_zero : φ 0 = 0 :=
φ.to_ring_hom.map_zero
@[simp] lemma map_mul (x y) : φ (x * y) = φ x * φ y :=
φ.to_ring_hom.map_mul x y
@[simp] lemma map_one : φ 1 = 1 :=
φ.to_ring_hom.map_one
@[simp] lemma map_smul (r : R) (x : A) : φ (r • x) = r • φ x :=
by simp only [algebra.smul_def, map_mul, commutes]
@[simp] lemma map_pow (x : A) (n : ℕ) : φ (x ^ n) = (φ x) ^ n :=
φ.to_ring_hom.map_pow x n
lemma map_sum {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∑ x in s, f x) = ∑ x in s, φ (f x) :=
φ.to_ring_hom.map_sum f s
@[simp] lemma map_nat_cast (n : ℕ) : φ n = n :=
φ.to_ring_hom.map_nat_cast n
@[simp] lemma map_bit0 (x) : φ (bit0 x) = bit0 (φ x) :=
φ.to_ring_hom.map_bit0 x
@[simp] lemma map_bit1 (x) : φ (bit1 x) = bit1 (φ x) :=
φ.to_ring_hom.map_bit1 x
section
variables (R A)
/-- Identity map as an `alg_hom`. -/
protected def id : A →ₐ[R] A :=
{ commutes' := λ _, rfl,
..ring_hom.id A }
end
@[simp] lemma id_apply (p : A) : alg_hom.id R A p = p := rfl
/-- Composition of algebra homeomorphisms. -/
def comp (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) : A →ₐ[R] C :=
{ commutes' := λ r : R, by rw [← φ₁.commutes, ← φ₂.commutes]; refl,
.. φ₁.to_ring_hom.comp ↑φ₂ }
@[simp] lemma comp_apply (φ₁ : B →ₐ[R] C) (φ₂ : A →ₐ[R] B) (p : A) :
φ₁.comp φ₂ p = φ₁ (φ₂ p) := rfl
@[simp] theorem comp_id : φ.comp (alg_hom.id R A) = φ :=
ext $ λ x, rfl
@[simp] theorem id_comp : (alg_hom.id R B).comp φ = φ :=
ext $ λ x, rfl
theorem comp_assoc (φ₁ : C →ₐ[R] D) (φ₂ : B →ₐ[R] C) (φ₃ : A →ₐ[R] B) :
(φ₁.comp φ₂).comp φ₃ = φ₁.comp (φ₂.comp φ₃) :=
ext $ λ x, rfl
/-- R-Alg ⥤ R-Mod -/
def to_linear_map : A →ₗ B :=
{ to_fun := φ,
map_add' := φ.map_add,
map_smul' := φ.map_smul }
@[simp] lemma to_linear_map_apply (p : A) : φ.to_linear_map p = φ p := rfl
theorem to_linear_map_inj {φ₁ φ₂ : A →ₐ[R] B} (H : φ₁.to_linear_map = φ₂.to_linear_map) : φ₁ = φ₂ :=
ext $ λ x, show φ₁.to_linear_map x = φ₂.to_linear_map x, by rw H
@[simp] lemma comp_to_linear_map (f : A →ₐ[R] B) (g : B →ₐ[R] C) :
(g.comp f).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
end semiring
section comm_semiring
variables [comm_semiring R] [comm_semiring A] [comm_semiring B]
variables [algebra R A] [algebra R B]
variables (φ : A →ₐ[R] B)
lemma map_prod {ι : Type*} (f : ι → A) (s : finset ι) :
φ (∏ x in s, f x) = ∏ x in s, φ (f x) :=
φ.to_ring_hom.map_prod f s
end comm_semiring
section ring
variables [comm_ring R] [ring A] [ring B] [ring C]
variables [algebra R A] [algebra R B] [algebra R C] (φ : A →ₐ[R] B)
@[simp] lemma map_neg (x) : φ (-x) = -φ x :=
φ.to_ring_hom.map_neg x
@[simp] lemma map_sub (x y) : φ (x - y) = φ x - φ y :=
φ.to_ring_hom.map_sub x y
end ring
section division_ring
variables [comm_ring R] [division_ring A] [division_ring B]
variables [algebra R A] [algebra R B] (φ : A →ₐ[R] B)
@[simp] lemma map_inv (x) : φ (x⁻¹) = (φ x)⁻¹ :=
φ.to_ring_hom.map_inv x
@[simp] lemma map_div (x y) : φ (x / y) = φ x / φ y :=
φ.to_ring_hom.map_div x y
end division_ring
theorem injective_iff {R A B : Type*} [comm_semiring R] [ring A] [semiring B]
[algebra R A] [algebra R B] (f : A →ₐ[R] B) :
function.injective f ↔ (∀ x, f x = 0 → x = 0) :=
ring_hom.injective_iff (f : A →+* B)
end alg_hom
set_option old_structure_cmd true
/-- An equivalence of algebras is an equivalence of rings commuting with the actions of scalars. -/
structure alg_equiv (R : Type u) (A : Type v) (B : Type w)
[comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B]
extends A ≃ B, A ≃* B, A ≃+ B, A ≃+* B :=
(commutes' : ∀ r : R, to_fun (algebra_map R A r) = algebra_map R B r)
attribute [nolint doc_blame] alg_equiv.to_ring_equiv
attribute [nolint doc_blame] alg_equiv.to_equiv
attribute [nolint doc_blame] alg_equiv.to_add_equiv
attribute [nolint doc_blame] alg_equiv.to_mul_equiv
notation A ` ≃ₐ[`:50 R `] ` A' := alg_equiv R A A'
namespace alg_equiv
variables {R : Type u} {A₁ : Type v} {A₂ : Type w} {A₃ : Type u₁}
variables [comm_semiring R] [semiring A₁] [semiring A₂] [semiring A₃]
variables [algebra R A₁] [algebra R A₂] [algebra R A₃]
variables (e : A₁ ≃ₐ[R] A₂)
instance : has_coe_to_fun (A₁ ≃ₐ[R] A₂) := ⟨_, alg_equiv.to_fun⟩
@[ext]
lemma ext {f g : A₁ ≃ₐ[R] A₂} (h : ∀ a, f a = g a) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
lemma coe_fun_injective : @function.injective (A₁ ≃ₐ[R] A₂) (A₁ → A₂) (λ e, (e : A₁ → A₂)) :=
begin
intros f g w,
ext,
exact congr_fun w a,
end
instance has_coe_to_ring_equiv : has_coe (A₁ ≃ₐ[R] A₂) (A₁ ≃+* A₂) := ⟨alg_equiv.to_ring_equiv⟩
@[simp] lemma mk_apply {to_fun inv_fun left_inv right_inv map_mul map_add commutes a} :
(⟨to_fun, inv_fun, left_inv, right_inv, map_mul, map_add, commutes⟩ : A₁ ≃ₐ[R] A₂) a = to_fun a :=
rfl
@[simp] lemma to_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₁} : e.to_fun a = e a := rfl
@[simp, norm_cast] lemma coe_ring_equiv : ((e : A₁ ≃+* A₂) : A₁ → A₂) = e := rfl
lemma coe_ring_equiv_injective : function.injective (λ e : A₁ ≃ₐ[R] A₂, (e : A₁ ≃+* A₂)) :=
begin
intros f g w,
ext,
replace w : ((f : A₁ ≃+* A₂) : A₁ → A₂) = ((g : A₁ ≃+* A₂) : A₁ → A₂) :=
congr_arg (λ e : A₁ ≃+* A₂, (e : A₁ → A₂)) w,
exact congr_fun w a,
end
@[simp] lemma map_add : ∀ x y, e (x + y) = e x + e y := e.to_add_equiv.map_add
@[simp] lemma map_zero : e 0 = 0 := e.to_add_equiv.map_zero
@[simp] lemma map_mul : ∀ x y, e (x * y) = (e x) * (e y) := e.to_mul_equiv.map_mul
@[simp] lemma map_one : e 1 = 1 := e.to_mul_equiv.map_one
@[simp] lemma commutes : ∀ (r : R), e (algebra_map R A₁ r) = algebra_map R A₂ r :=
e.commutes'
@[simp] lemma map_neg {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x, e (-x) = -(e x) := e.to_add_equiv.map_neg
@[simp] lemma map_sub {A₁ : Type v} {A₂ : Type w}
[ring A₁] [ring A₂] [algebra R A₁] [algebra R A₂] (e : A₁ ≃ₐ[R] A₂) :
∀ x y, e (x - y) = e x - e y := e.to_add_equiv.map_sub
lemma map_sum {ι : Type*} (f : ι → A₁) (s : finset ι) :
e (∑ x in s, f x) = ∑ x in s, e (f x) :=
e.to_add_equiv.map_sum f s
/-- Interpret an algebra equivalence as an algebra homomorphism.
This definition is included for symmetry with the other `to_*_hom` projections.
The `simp` normal form is to use the coercion of the `has_coe_to_alg_hom` instance. -/
def to_alg_hom : A₁ →ₐ[R] A₂ :=
{ map_one' := e.map_one, map_zero' := e.map_zero, ..e }
instance has_coe_to_alg_hom : has_coe (A₁ ≃ₐ[R] A₂) (A₁ →ₐ[R] A₂) :=
⟨to_alg_hom⟩
@[simp] lemma to_alg_hom_eq_coe : e.to_alg_hom = e := rfl
@[simp, norm_cast] lemma coe_alg_hom : ((e : A₁ →ₐ[R] A₂) : A₁ → A₂) = e :=
rfl
lemma injective : function.injective e := e.to_equiv.injective
lemma surjective : function.surjective e := e.to_equiv.surjective
lemma bijective : function.bijective e := e.to_equiv.bijective
instance : has_one (A₁ ≃ₐ[R] A₁) := ⟨{commutes' := λ r, rfl, ..(1 : A₁ ≃+* A₁)}⟩
instance : inhabited (A₁ ≃ₐ[R] A₁) := ⟨1⟩
/-- Algebra equivalences are reflexive. -/
@[refl]
def refl : A₁ ≃ₐ[R] A₁ := 1
@[simp] lemma coe_refl : (@refl R A₁ _ _ _ : A₁ →ₐ[R] A₁) = alg_hom.id R A₁ :=
alg_hom.ext (λ x, rfl)
/-- Algebra equivalences are symmetric. -/
@[symm]
def symm (e : A₁ ≃ₐ[R] A₂) : A₂ ≃ₐ[R] A₁ :=
{ commutes' := λ r, by { rw ←e.to_ring_equiv.symm_apply_apply (algebra_map R A₁ r), congr,
change _ = e _, rw e.commutes, },
..e.to_ring_equiv.symm, }
@[simp] lemma inv_fun_apply {e : A₁ ≃ₐ[R] A₂} {a : A₂} : e.inv_fun a = e.symm a := rfl
@[simp] lemma symm_symm {e : A₁ ≃ₐ[R] A₂} : e.symm.symm = e :=
by { ext, refl, }
/-- Algebra equivalences are transitive. -/
@[trans]
def trans (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) : A₁ ≃ₐ[R] A₃ :=
{ commutes' := λ r, show e₂.to_fun (e₁.to_fun _) = _, by rw [e₁.commutes', e₂.commutes'],
..(e₁.to_ring_equiv.trans e₂.to_ring_equiv), }
@[simp] lemma apply_symm_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e (e.symm x) = x :=
e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : A₁ ≃ₐ[R] A₂) : ∀ x, e.symm (e x) = x :=
e.to_equiv.symm_apply_apply
@[simp] lemma trans_apply (e₁ : A₁ ≃ₐ[R] A₂) (e₂ : A₂ ≃ₐ[R] A₃) (x : A₁) :
(e₁.trans e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma comp_symm (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp (e : A₁ →ₐ[R] A₂) ↑e.symm = alg_hom.id R A₂ :=
by { ext, simp }
@[simp] lemma symm_comp (e : A₁ ≃ₐ[R] A₂) :
alg_hom.comp ↑e.symm (e : A₁ →ₐ[R] A₂) = alg_hom.id R A₁ :=
by { ext, simp }
/-- If an algebra morphism has an inverse, it is a algebra isomorphism. -/
def of_alg_hom (f : A₁ →ₐ[R] A₂) (g : A₂ →ₐ[R] A₁) (h₁ : f.comp g = alg_hom.id R A₂) (h₂ : g.comp f = alg_hom.id R A₁) : A₁ ≃ₐ[R] A₂ :=
{ inv_fun := g,
left_inv := alg_hom.ext_iff.1 h₂,
right_inv := alg_hom.ext_iff.1 h₁,
..f }
/-- Promotes a bijective algebra homomorphism to an algebra equivalence. -/
noncomputable def of_bijective (f : A₁ →ₐ[R] A₂) (hf : function.bijective f) : A₁ ≃ₐ[R] A₂ :=
{ .. ring_equiv.of_bijective (f : A₁ →+* A₂) hf, .. f }
/-- Forgetting the multiplicative structures, an equivalence of algebras is a linear equivalence. -/
def to_linear_equiv (e : A₁ ≃ₐ[R] A₂) : A₁ ≃ₗ[R] A₂ :=
{ to_fun := e.to_fun,
map_add' := λ x y, by simp,
map_smul' := λ r x, by simp [algebra.smul_def''],
inv_fun := e.symm.to_fun,
left_inv := e.left_inv,
right_inv := e.right_inv, }
@[simp] lemma to_linear_equiv_apply (e : A₁ ≃ₐ[R] A₂) (x : A₁) : e.to_linear_equiv x = e x := rfl
theorem to_linear_equiv_inj {e₁ e₂ : A₁ ≃ₐ[R] A₂} (H : e₁.to_linear_equiv = e₂.to_linear_equiv) :
e₁ = e₂ :=
ext $ λ x, show e₁.to_linear_equiv x = e₂.to_linear_equiv x, by rw H
/-- Interpret an algebra equivalence as a linear map. -/
def to_linear_map : A₁ →ₗ[R] A₂ :=
e.to_alg_hom.to_linear_map
@[simp] lemma to_alg_hom_to_linear_map :
(e : A₁ →ₐ[R] A₂).to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_equiv_to_linear_map :
e.to_linear_equiv.to_linear_map = e.to_linear_map := rfl
@[simp] lemma to_linear_map_apply (x : A₁) : e.to_linear_map x = e x := rfl
theorem to_linear_map_inj {e₁ e₂ : A₁ ≃ₐ[R] A₂} (H : e₁.to_linear_map = e₂.to_linear_map) :
e₁ = e₂ :=
ext $ λ x, show e₁.to_linear_map x = e₂.to_linear_map x, by rw H
@[simp] lemma trans_to_linear_map (f : A₁ ≃ₐ[R] A₂) (g : A₂ ≃ₐ[R] A₃) :
(f.trans g).to_linear_map = g.to_linear_map.comp f.to_linear_map := rfl
end alg_equiv
namespace algebra
variables (R : Type u) (S : Type v) (A : Type w)
include R S A
/-- `comap R S A` is a type alias for `A`, and has an R-algebra structure defined on it
when `algebra R S` and `algebra S A`. If `S` is an `R`-algebra and `A` is an `S`-algebra then
`algebra.comap.algebra R S A` can be used to provide `A` with a structure of an `R`-algebra.
Other than that, `algebra.comap` is now deprecated and replaced with `is_scalar_tower`. -/
/- This is done to avoid a type class search with meta-variables `algebra R ?m_1` and
`algebra ?m_1 A -/
/- The `nolint` attribute is added because it has unused arguments `R` and `S`, but these are necessary for synthesizing the
appropriate type classes -/
@[nolint unused_arguments]
def comap : Type w := A
instance comap.inhabited [h : inhabited A] : inhabited (comap R S A) := h
instance comap.semiring [h : semiring A] : semiring (comap R S A) := h
instance comap.ring [h : ring A] : ring (comap R S A) := h
instance comap.comm_semiring [h : comm_semiring A] : comm_semiring (comap R S A) := h
instance comap.comm_ring [h : comm_ring A] : comm_ring (comap R S A) := h
instance comap.algebra' [comm_semiring S] [semiring A] [h : algebra S A] :
algebra S (comap R S A) := h
/-- Identity homomorphism `A →ₐ[S] comap R S A`. -/
def comap.to_comap [comm_semiring S] [semiring A] [algebra S A] :
A →ₐ[S] comap R S A := alg_hom.id S A
/-- Identity homomorphism `comap R S A →ₐ[S] A`. -/
def comap.of_comap [comm_semiring S] [semiring A] [algebra S A] :
comap R S A →ₐ[S] A := alg_hom.id S A
variables [comm_semiring R] [comm_semiring S] [semiring A] [algebra R S] [algebra S A]
/-- `R ⟶ S` induces `S-Alg ⥤ R-Alg` -/
instance comap.algebra : algebra R (comap R S A) :=
{ smul := λ r x, (algebra_map R S r • x : A),
commutes' := λ r x, algebra.commutes _ _,
smul_def' := λ _ _, algebra.smul_def _ _,
.. (algebra_map S A).comp (algebra_map R S) }
/-- Embedding of `S` into `comap R S A`. -/
def to_comap : S →ₐ[R] comap R S A :=
{ commutes' := λ r, rfl,
.. algebra_map S A }
theorem to_comap_apply (x) : to_comap R S A x = algebra_map S A x := rfl
end algebra
namespace alg_hom
variables {R : Type u} {S : Type v} {A : Type w} {B : Type u₁}
variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B]
variables [algebra R S] [algebra S A] [algebra S B] (φ : A →ₐ[S] B)
include R
/-- R ⟶ S induces S-Alg ⥤ R-Alg -/
def comap : algebra.comap R S A →ₐ[R] algebra.comap R S B :=
{ commutes' := λ r, φ.commutes (algebra_map R S r)
..φ }
end alg_hom
namespace rat
instance algebra_rat {α} [division_ring α] [char_zero α] : algebra ℚ α :=
(rat.cast_hom α).to_algebra' $ λ r x, r.cast_commute x
end rat
namespace algebra
variables (R : Type u) (A : Type v)
variables [comm_semiring R] [semiring A] [algebra R A]
/-- `algebra_map` as an `alg_hom`. -/
def of_id : R →ₐ[R] A :=
{ commutes' := λ _, rfl, .. algebra_map R A }
variables {R}
theorem of_id_apply (r) : of_id R A r = algebra_map R A r := rfl
end algebra
section nat
variables (R : Type*) [semiring R]
/-- Reinterpret a `ring_hom` as an `ℕ`-algebra homomorphism. -/
def alg_hom_nat
{R : Type u} [semiring R] [algebra ℕ R]
{S : Type v} [semiring S] [algebra ℕ S]
(f : R →+* S) : R →ₐ[ℕ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- Semiring ⥤ ℕ-Alg -/
instance algebra_nat : algebra ℕ R :=
{ commutes' := nat.cast_commute,
smul_def' := λ _ _, nsmul_eq_mul _ _,
.. nat.cast_ring_hom R }
section span_nat
open submodule
lemma span_nat_eq_add_group_closure (s : set R) :
(span ℕ s).to_add_submonoid = add_submonoid.closure s :=
eq.symm $ add_submonoid.closure_eq_of_le subset_span $ λ x hx, span_induction hx
(λ x hx, add_submonoid.subset_closure hx) (add_submonoid.zero_mem _)
(λ _ _, add_submonoid.add_mem _) (λ _ _ _, add_submonoid.nsmul_mem _ ‹_› _)
@[simp] lemma span_nat_eq (s : add_submonoid R) : (span ℕ (s : set R)).to_add_submonoid = s :=
by rw [span_nat_eq_add_group_closure, s.closure_eq]
end span_nat
end nat
section int
variables (R : Type*) [ring R]
/-- Reinterpret a `ring_hom` as a `ℤ`-algebra homomorphism. -/
def alg_hom_int
{R : Type u} [comm_ring R] [algebra ℤ R]
{S : Type v} [comm_ring S] [algebra ℤ S]
(f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ i, show f _ = _, by simp, .. f }
/-- Ring ⥤ ℤ-Alg -/
instance algebra_int : algebra ℤ R :=
{ commutes' := int.cast_commute,
smul_def' := λ _ _, gsmul_eq_mul _ _,
.. int.cast_ring_hom R }
/--
Promote a ring homomorphisms to a `ℤ`-algebra homomorphism.
-/
def ring_hom.to_int_alg_hom {R S : Type*} [ring R] [ring S] (f : R →+* S) : R →ₐ[ℤ] S :=
{ commutes' := λ n, by simp,
.. f }
variables {R}
section
variables {S : Type*} [ring S]
instance int_algebra_subsingleton : subsingleton (algebra ℤ S) :=
⟨λ P Q, by { ext, simp, }⟩
end
section
variables {S : Type*} [semiring S]
instance nat_algebra_subsingleton : subsingleton (algebra ℕ S) :=
⟨λ P Q, by { ext, simp, }⟩
end
section span_int
open submodule
lemma span_int_eq_add_group_closure (s : set R) :
(span ℤ s).to_add_subgroup = add_subgroup.closure s :=
eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx
(λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _)
(λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _)
@[simp] lemma span_int_eq (s : add_subgroup R) : (span ℤ (s : set R)).to_add_subgroup = s :=
by rw [span_int_eq_add_group_closure, s.closure_eq]
end span_int
end int
/-!
The R-algebra structure on `Π i : I, A i` when each `A i` is an R-algebra.
We couldn't set this up back in `algebra.pi_instances` because this file imports it.
-/
namespace pi
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equipped with instances
variables (x y : Π i, f i) (i : I)
variables (I f)
instance algebra (α) {r : comm_semiring α}
[s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] :
algebra α (Π i : I, f i) :=
{ commutes' := λ a f, begin ext, simp [algebra.commutes], end,
smul_def' := λ a f, begin ext, simp [algebra.smul_def''], end,
..pi.ring_hom (λ i, algebra_map α (f i)) }
@[simp] lemma algebra_map_apply (α) {r : comm_semiring α}
[s : ∀ i, semiring (f i)] [∀ i, algebra α (f i)] (a : α) (i : I) :
algebra_map α (Π i, f i) a i = algebra_map α (f i) a := rfl
-- One could also build a `Π i, R i`-algebra structure on `Π i, A i`,
-- when each `A i` is an `R i`-algebra, although I'm not sure that it's useful.
end pi
section is_scalar_tower
variables {R : Type*} [comm_semiring R]
variables (A : Type*) [semiring A] [algebra R A]
variables {M : Type*} [add_comm_monoid M] [semimodule A M] [semimodule R M] [is_scalar_tower R A M]
variables {N : Type*} [add_comm_monoid N] [semimodule A N] [semimodule R N] [is_scalar_tower R A N]
lemma algebra_compatible_smul (r : R) (m : M) : r • m = ((algebra_map R A) r) • m :=
by rw [←(one_smul A m), ←smul_assoc, algebra.smul_def, mul_one, one_smul]
variable {A}
lemma smul_algebra_smul_comm (r : R) (a : A) (m : M) : a • r • m = r • a • m :=
by rw [algebra_compatible_smul A r (a • m), smul_smul, algebra.commutes, mul_smul, ←algebra_compatible_smul]
@[simp] lemma map_smul_eq_smul_map (f : M →ₗ[A] N) (r : R) (m : M) :
f (r • m) = r • f m :=
by rw [algebra_compatible_smul A r m, linear_map.map_smul, ←algebra_compatible_smul A r (f m)]
instance : has_coe (M →ₗ[A] N) (M →ₗ[R] N) :=
⟨λ f, ⟨f.to_fun, λ x y, f.map_add' x y, λ r n, map_smul_eq_smul_map _ _ _⟩⟩
end is_scalar_tower
section restrict_scalars
/- In this section, we describe restriction of scalars: if `S` is an algebra over `R`, then
`S`-modules are also `R`-modules. -/
section semimodule
variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S]
variables (E : Type*) [add_comm_monoid E] [semimodule S E]
variables {F : Type*} [add_comm_monoid F] [semimodule S F]
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, called `module.restrict_scalars' R S E`.
We do not register this as an instance as `S` can not be inferred.
-/
def semimodule.restrict_scalars' : semimodule R E :=
{ smul := λ c x, (algebra_map R S c) • x,
one_smul := by simp,
mul_smul := by simp [mul_smul],
smul_add := by simp [smul_add],
smul_zero := by simp [smul_zero],
add_smul := by simp [add_smul],
zero_smul := by simp [zero_smul] }
/--
When `E` is a module over a ring `S`, and `S` is an algebra over `R`, then `E` inherits a
module structure over `R`, provided as a type synonym `module.restrict_scalars R S E := E`.
When the `R`-module structure on `E` is registered directly (using `module.restrict_scalars'` for
instance, or for `S = ℂ` and `R = ℝ`), theorems on `module.restrict_scalars R S E` can be directly
applied to `E` as these types are the same for the kernel.
-/
@[nolint unused_arguments]
def semimodule.restrict_scalars (R : Type*) (S : Type*) (E : Type*) : Type* := E
instance (R : Type*) (S : Type*) (E : Type*) [I : inhabited E] :
inhabited (semimodule.restrict_scalars R S E) := I
instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_monoid E] :
add_comm_monoid (semimodule.restrict_scalars R S E) := I
instance semimodule.restrict_scalars.module_orig (R : Type*) (S : Type*) [semiring S]
(E : Type*) [add_comm_monoid E] [I : semimodule S E] :
semimodule S (semimodule.restrict_scalars R S E) := I
instance : semimodule R (semimodule.restrict_scalars R S E) :=
(semimodule.restrict_scalars' R S E : semimodule R E)
lemma semimodule.restrict_scalars_smul_def (c : R) (x : semimodule.restrict_scalars R S E) :
c • x = ((algebra_map R S c) • x : E) := rfl
/--
`module.restrict_scalars R S S` is `R`-linearly equivalent to the original algebra `S`.
Unfortunately these structures are not generally definitionally equal:
the `R`-module structure on `S` is part of the data of `S`,
while the `R`-module structure on `module.restrict_scalars R S S`
comes from the ring homomorphism `R →+* S`, which is a separate part of the data of `S`.
The field `algebra.smul_def'` gives the equation we need here.
-/
def algebra.restrict_scalars_equiv :
(semimodule.restrict_scalars R S S) ≃ₗ[R] S :=
{ to_fun := λ s, s,
inv_fun := λ s, s,
left_inv := λ s, rfl,
right_inv := λ s, rfl,
map_add' := λ x y, rfl,
map_smul' := λ c x, (algebra.smul_def' _ _).symm, }
@[simp]
lemma algebra.restrict_scalars_equiv_apply (s : S) :
algebra.restrict_scalars_equiv R S s = s := rfl
@[simp]
lemma algebra.restrict_scalars_equiv_symm_apply (s : S) :
(algebra.restrict_scalars_equiv R S).symm s = s := rfl
variables {S E}
open semimodule
instance : is_scalar_tower R S (restrict_scalars R S E) :=
⟨λ r s e, by { rw [algebra.smul_def, mul_smul], refl }⟩
/--
`V.restrict_scalars R` is the `R`-submodule of the `R`-module given by restriction of scalars,
corresponding to `V`, an `S`-submodule of the original `S`-module.
-/
@[simps]
def submodule.restrict_scalars (V : submodule S E) : submodule R (restrict_scalars R S E) :=
{ carrier := V.carrier,
zero_mem' := V.zero_mem,
smul_mem' := λ c e h, V.smul_mem _ h,
add_mem' := λ x y hx hy, V.add_mem hx hy, }
@[simp]
lemma submodule.restrict_scalars_mem (V : submodule S E) (e : E) :
e ∈ V.restrict_scalars R ↔ e ∈ V :=
iff.refl _
@[simp]
lemma submodule.restrict_scalars_bot :
submodule.restrict_scalars R (⊥ : submodule S E) = ⊥ :=
rfl
@[simp]
lemma submodule.restrict_scalars_top :
submodule.restrict_scalars R (⊤ : submodule S E) = ⊤ :=
rfl
/-- The `R`-linear map induced by an `S`-linear map when `S` is an algebra over `R`. -/
def linear_map.restrict_scalars (f : E →ₗ[S] F) :
(restrict_scalars R S E) →ₗ[R] (restrict_scalars R S F) :=
{ to_fun := f.to_fun,
map_add' := λx y, f.map_add x y,
map_smul' := λc x, f.map_smul (algebra_map R S c) x }
@[simp, norm_cast squash] lemma linear_map.coe_restrict_scalars_eq_coe (f : E →ₗ[S] F) :
(f.restrict_scalars R : E → F) = f := rfl
@[simp]
lemma restrict_scalars_ker (f : E →ₗ[S] F) :
(f.restrict_scalars R).ker = submodule.restrict_scalars R f.ker :=
rfl
/-- `A`-linearly coerce a `R`-linear map from `M` to `R` to a function, given an algebra `A` over
a commutative semiring `R` and `M` a semimodule over `R`. -/
def linear_map.lto_fun (R : Type u) (M : Type v) (A : Type w)
[comm_semiring R] [add_comm_monoid M] [semimodule R M] [comm_ring A] [algebra R A] :
(M →ₗ[R] A) →ₗ[A] (M → A) :=
{ to_fun := linear_map.to_fun,
map_add' := λ f g, rfl,
map_smul' := λ c f, rfl }
end semimodule
section module
instance (R : Type*) (S : Type*) (E : Type*) [I : add_comm_group E] :
add_comm_group (semimodule.restrict_scalars R S E) := I
end module
end restrict_scalars
section extend_scalars
/-! When `V` is an `R`-module and `W` is an `S`-module, where `S` is an algebra over `R`, then
the collection of `R`-linear maps from `V` to `W` admits an `S`-module structure, given by
multiplication in the target -/
variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S]
(V : Type*) [add_comm_monoid V] [semimodule R V]
(W : Type*) [add_comm_monoid W] [semimodule S W]
/-- The set of `R`-linear maps admits an `S`-action by left multiplication -/
instance linear_map.has_scalar_extend_scalars :
has_scalar S (V →ₗ[R] (semimodule.restrict_scalars R S W)) :=
{ smul := λ r f,
{ to_fun := λ v, r • f v,
map_add' := by simp [smul_add],
map_smul' := λ c x, by rw [linear_map.map_smul, smul_algebra_smul_comm] }}
/-- The set of `R`-linear maps is an `S`-module-/
instance linear_map.module_extend_scalars :
semimodule S (V →ₗ[R] (semimodule.restrict_scalars R S W)) :=
{ one_smul := λ f, by { ext v, simp [(•)] },
mul_smul := λ r r' f, by { ext v, simp [(•), smul_smul] },
smul_add := λ r f g, by { ext v, simp [(•), smul_add] },
smul_zero := λ r, by { ext v, simp [(•)] },
add_smul := λ r r' f, by { ext v, simp [(•), add_smul] },
zero_smul := λ f, by { ext v, simp [(•)] } }
variables {R S V W}
/-- When `f` is a linear map taking values in `S`, then `λb, f b • x` is a linear map. -/
def smul_algebra_right (f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) :
V →ₗ[R] (semimodule.restrict_scalars R S W) :=
{ to_fun := λb, f b • x,
map_add' := by simp [add_smul],
map_smul' := λ b y, by { simp [algebra.smul_def, ← smul_smul], refl } }
@[simp] theorem smul_algebra_right_apply
(f : V →ₗ[R] S) (x : semimodule.restrict_scalars R S W) (c : V) :
smul_algebra_right f x c = f c • x := rfl
end extend_scalars
/-!
When `V` and `W` are `S`-modules, for some `R`-algebra `S`,
the collection of `S`-linear maps from `V` to `W` forms an `R`-module.
(But not generally an `S`-module, because `S` may be non-commutative.)
-/
section module_of_linear_maps
variables (R : Type*) [comm_semiring R] (S : Type*) [semiring S] [algebra R S]
(V : Type*) [add_comm_monoid V] [semimodule S V]
(W : Type*) [add_comm_monoid W] [semimodule S W]
/--
For `r : R`, and `f : V →ₗ[S] W` (where `S` is an `R`-algebra) we define
`(r • f) v = f (r • v)`.
-/
def linear_map_algebra_has_scalar : has_scalar R (V →ₗ[S] W) :=
{ smul := λ r f,
{ to_fun := λ v, f ((algebra_map R S r) • v),
map_add' := λ x y, by simp [smul_add],
map_smul' := λ s v, by simp [smul_smul, algebra.commutes], } }
local attribute [instance] linear_map_algebra_has_scalar
/-- The `R`-module structure on `S`-linear maps, for `S` an `R`-algebra. -/
def linear_map_algebra_module : semimodule R (V →ₗ[S] W) :=
{ one_smul := λ f, begin ext v, dsimp [(•)], simp, end,
mul_smul := λ r r' f,
begin
ext v, dsimp [(•)],
rw [linear_map.map_smul, linear_map.map_smul, linear_map.map_smul, ring_hom.map_mul,
smul_smul, algebra.commutes],
end,
smul_zero := λ r, by { ext v, dsimp [(•)], refl, },
smul_add := λ r f g, by { ext v, dsimp [(•)], simp [linear_map.map_add], },
zero_smul := λ f, by { ext v, dsimp [(•)], simp, },
add_smul := λ r r' f, by { ext v, dsimp [(•)], simp [add_smul], }, }
local attribute [instance] linear_map_algebra_module
variables {R S V W}
@[simp]
lemma linear_map_algebra_module.smul_apply (c : R) (f : V →ₗ[S] W) (v : V) :
(c • f) v = (c • (f v) : semimodule.restrict_scalars R S W) :=
begin
erw [linear_map.map_smul],
refl,
end
end module_of_linear_maps
|
a140e80fa4d73cc5a43825d01c5c9acf0280337d | 6db8061629f55e774dd3d03be5bf005ffb485e48 | /BetterNumLits/Numerals.lean | cb6ff9a6a15ea4bd7f6151457c14516f23c179c0 | [] | no_license | tydeu/lean4-betterNumLits | 21fd5717d1b62ecb021c73e8cfaa0e3d19005690 | 45e3b79214b3e1f81f8e034dd12257e993ddc578 | refs/heads/master | 1,683,103,070,685 | 1,621,717,131,000 | 1,621,717,131,000 | 369,368,844 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,203 | lean | universe u
class Zero (A : Type u) := zero : A
class One (A : Type u) := one : A
class Two (A : Type u) := two : A
class Three (A : Type u) := three : A
class Four (A : Type u) := four : A
class Five (A : Type u) := five : A
class Six (A : Type u) := six : A
class Seven (A : Type u) := seven : A
class Eight (A : Type u) := eight : A
class Nine (A : Type u) := nine : A
class Ten (A : Type u) := ten : A
class Eleven (A : Type u) := eleven : A
class Twelve (A : Type u) := twelve : A
class Thirteen (A : Type u) := thirteen : A
class Fourteen (A : Type u) := fourteen : A
class Fifteen (A : Type u) := fifteen : A
class Sixteen (A : Type u) := sixteen : A
export Zero (zero)
export One (one)
export Two (two)
export Three (three)
export Four (four)
export Five (five)
export Six (six)
export Seven (seven)
export Eight (eight)
export Nine (nine)
export Ten (ten)
export Eleven (eleven)
export Twelve (twelve)
export Thirteen (thirteen)
export Fourteen (fourteen)
export Fifteen (fifteen)
export Sixteen (sixteen)
|
50c4e0a2764f47b184fa0b046d9f3ee5adcfc6bb | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/convex/basic.lean | 5a4cf4f7b91f8001e20eb9ec541e980b1a64e728 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 42,041 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies
-/
import algebra.order.invertible
import algebra.order.module
import linear_algebra.affine_space.midpoint
import linear_algebra.affine_space.affine_subspace
import linear_algebra.ray
/-!
# Convex sets and functions in vector spaces
In a 𝕜-vector space, we define the following objects and properties.
* `segment 𝕜 x y`: Closed segment joining `x` and `y`.
* `open_segment 𝕜 x y`: Open segment joining `x` and `y`.
* `convex 𝕜 s`: A set `s` is convex if for any two points `x y ∈ s` it includes `segment 𝕜 x y`.
* `std_simplex 𝕜 ι`: The standard simplex in `ι → 𝕜` (currently requires `fintype ι`). It is the
intersection of the positive quadrant with the hyperplane `s.sum = 1`.
We also provide various equivalent versions of the definitions above, prove that some specific sets
are convex.
## Notations
We provide the following notation:
* `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex`
## TODO
Generalize all this file to affine spaces.
Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also
define `clopen_segment`/`convex.Ico`/`convex.Ioc`?
-/
variables {𝕜 E F β : Type*}
open linear_map set
open_locale big_operators classical pointwise
/-! ### Segment -/
section ordered_semiring
variables [ordered_semiring 𝕜] [add_comm_monoid E]
section has_smul
variables (𝕜) [has_smul 𝕜 E]
/-- Segments in a vector space. -/
def segment (x y : E) : set E :=
{z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z}
/-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when
the base semiring has some element between `0` and `1`. -/
def open_segment (x y : E) : set E :=
{z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z}
localized "notation `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex
lemma segment_eq_image₂ (x y : E) :
[x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} :=
by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma open_segment_eq_image₂ (x y : E) :
open_segment 𝕜 x y =
(λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} :=
by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩,
λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩
lemma open_segment_symm (x y : E) :
open_segment 𝕜 x y = open_segment 𝕜 y x :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩,
λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩
lemma open_segment_subset_segment (x y : E) :
open_segment 𝕜 x y ⊆ [x -[𝕜] y] :=
λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩
lemma segment_subset_iff {x y : E} {s : set E} :
[x -[𝕜] y] ⊆ s ↔ ∀ a b : 𝕜, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s :=
⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩,
λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩
lemma open_segment_subset_iff {x y : E} {s : set E} :
open_segment 𝕜 x y ⊆ s ↔ ∀ a b : 𝕜, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s :=
⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩,
λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩
end has_smul
open_locale convex
section mul_action_with_zero
variables (𝕜) [mul_action_with_zero 𝕜 E]
lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] :=
⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩
lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] :=
segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x
end mul_action_with_zero
section module
variables (𝕜) [module 𝕜 E] {x y z : E} {s : set E}
@[simp] lemma segment_same (x : E) : [x -[𝕜] x] = {x} :=
set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩,
by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩
lemma insert_endpoints_open_segment (x y : E) :
insert x (insert y (open_segment 𝕜 x y)) = [x -[𝕜] y] :=
begin
simp only [subset_antisymm_iff, insert_subset, left_mem_segment, right_mem_segment,
open_segment_subset_segment, true_and],
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
refine hb.eq_or_gt.imp _ (λ hb', ha.eq_or_gt.imp _ _),
{ rintro rfl,
rw add_zero at hab,
rw [hab, one_smul, zero_smul, add_zero] },
{ rintro rfl,
rw zero_add at hab,
rw [hab, one_smul, zero_smul, zero_add] },
{ exact λ ha', ⟨a, b, ha', hb', hab, rfl⟩ }
end
variables {𝕜}
lemma mem_open_segment_of_ne_left_right (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) :
z ∈ open_segment 𝕜 x y :=
begin
rw [← insert_endpoints_open_segment] at hz,
exact ((hz.resolve_left hx.symm).resolve_left hy.symm)
end
lemma open_segment_subset_iff_segment_subset (hx : x ∈ s) (hy : y ∈ s) :
open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s :=
by simp only [← insert_endpoints_open_segment, insert_subset, *, true_and]
end module
end ordered_semiring
open_locale convex
section ordered_ring
variables [ordered_ring 𝕜]
section add_comm_group
variables (𝕜) [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
section densely_ordered
variables [nontrivial 𝕜] [densely_ordered 𝕜]
@[simp] lemma open_segment_same (x : E) :
open_segment 𝕜 x x = {x} :=
set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩,
by simpa only [← add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
λ (h : z = x), begin
obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one,
refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩,
rw [←add_smul, add_sub_cancel'_right, one_smul, h],
end⟩
end densely_ordered
lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, hz⟩,
⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩,
λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩
lemma open_segment_eq_image (x y : E) :
open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 :=
set.ext $ λ z,
⟨λ ⟨a, b, ha, hb, hab, hz⟩,
⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩,
λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩
lemma segment_eq_image' (x y : E) :
[x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 :=
by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma open_segment_eq_image' (x y : E) :
open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 :=
by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma segment_eq_image_line_map (x y : E) :
[x -[𝕜] y] = affine_map.line_map x y '' Icc (0 : 𝕜) 1 :=
by { convert segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ }
lemma open_segment_eq_image_line_map (x y : E) :
open_segment 𝕜 x y = affine_map.line_map x y '' Ioo (0 : 𝕜) 1 :=
by { convert open_segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ }
lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] :=
set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul])
@[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) :
f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) :=
set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add,
map_smul])
lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] :=
begin
rw [segment_eq_image', segment_eq_image'],
refine exists_congr (λ θ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj],
end
@[simp] lemma mem_open_segment_translate (a : E) {x b c : E} :
a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c :=
begin
rw [open_segment_eq_image', open_segment_eq_image'],
refine exists_congr (λ θ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj],
end
lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] :=
set.ext $ λ x, mem_segment_translate 𝕜 a
lemma open_segment_translate_preimage (a b c : E) :
(λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c :=
set.ext $ λ x, mem_open_segment_translate 𝕜 a
lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] :=
segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a
lemma open_segment_translate_image (a b c : E) :
(λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) :=
open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a
end add_comm_group
end ordered_ring
lemma same_ray_of_mem_segment [ordered_comm_ring 𝕜] [add_comm_group E] [module 𝕜 E]
{x y z : E} (h : x ∈ [y -[𝕜] z]) : same_ray 𝕜 (x - y) (z - x) :=
begin
rw segment_eq_image' at h,
rcases h with ⟨θ, ⟨hθ₀, hθ₁⟩, rfl⟩,
simpa only [add_sub_cancel', ← sub_sub, sub_smul, one_smul]
using (same_ray_nonneg_smul_left (z - y) hθ₀).nonneg_smul_right (sub_nonneg.2 hθ₁)
end
section linear_ordered_ring
variables [linear_ordered_ring 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F]
lemma midpoint_mem_segment [invertible (2 : 𝕜)] (x y : E) :
midpoint 𝕜 x y ∈ [x -[𝕜] y] :=
begin
rw segment_eq_image_line_map,
exact ⟨⅟2, ⟨inv_of_nonneg.mpr zero_le_two, inv_of_le_one one_le_two⟩, rfl⟩,
end
lemma mem_segment_sub_add [invertible (2 : 𝕜)] (x y : E) :
x ∈ [x-y -[𝕜] x+y] :=
begin
convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _,
rw midpoint_sub_add
end
lemma mem_segment_add_sub [invertible (2 : 𝕜)] (x y : E) :
x ∈ [x+y -[𝕜] x-y] :=
begin
convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _,
rw midpoint_add_sub
end
@[simp] lemma left_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {x y : E} :
x ∈ open_segment 𝕜 x y ↔ x = y :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, hx⟩,
refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _),
rw [hx, ←add_smul, hab, one_smul] },
{ rintro rfl,
rw open_segment_same,
exact mem_singleton _ }
end
@[simp] lemma right_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] {x y : E} :
y ∈ open_segment 𝕜 x y ↔ x = y :=
by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm]
end add_comm_group
end linear_ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {x y z : E}
lemma mem_segment_iff_same_ray : x ∈ [y -[𝕜] z] ↔ same_ray 𝕜 (x - y) (z - x) :=
begin
refine ⟨same_ray_of_mem_segment, λ h, _⟩,
rcases h.exists_eq_smul_add with ⟨a, b, ha, hb, hab, hxy, hzx⟩,
rw [add_comm, sub_add_sub_cancel] at hxy hzx,
rw [← mem_segment_translate _ (-x), neg_add_self],
refine ⟨b, a, hb, ha, add_comm a b ▸ hab, _⟩,
rw [← sub_eq_neg_add, ← neg_sub, hxy, ← sub_eq_neg_add, hzx, smul_neg, smul_comm, neg_add_self]
end
lemma mem_segment_iff_div : x ∈ [y -[𝕜] z] ↔
∃ a b : 𝕜, 0 ≤ a ∧ 0 ≤ b ∧ 0 < a + b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
use [a, b, ha, hb],
simp * },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
refine ⟨a / (a + b), b / (a + b), div_nonneg ha hab.le, div_nonneg hb hab.le, _, rfl⟩,
rw [← add_div, div_self hab.ne'] }
end
lemma mem_open_segment_iff_div : x ∈ open_segment 𝕜 y z ↔
∃ a b : 𝕜, 0 < a ∧ 0 < b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x :=
begin
split,
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
use [a, b, ha, hb],
rw [hab, div_one, div_one] },
{ rintro ⟨a, b, ha, hb, rfl⟩,
have hab : 0 < a + b, from add_pos ha hb,
refine ⟨a / (a + b), b / (a + b), div_pos ha hab, div_pos hb hab, _, rfl⟩,
rw [← add_div, div_self hab.ne'] }
end
end add_comm_group
end linear_ordered_field
/-!
#### Segments in an ordered space
Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo`
-/
section ordered_semiring
variables [ordered_semiring 𝕜]
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E]
lemma segment_subset_Icc {x y : E} (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y :=
begin
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
split,
calc
x = a • x + b • x :(convex.combo_self hab _).symm
... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _,
calc
a • x + b • y
≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _
... = y : convex.combo_self hab _,
end
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E]
lemma open_segment_subset_Ioo {x y : E} (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y :=
begin
rintro z ⟨a, b, ha, hb, hab, rfl⟩,
split,
calc
x = a • x + b • x : (convex.combo_self hab _).symm
... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _,
calc
a • x + b • y
< a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _
... = y : convex.combo_self hab _,
end
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜}
lemma segment_subset_interval (x y : E) : [x -[𝕜] y] ⊆ interval x y :=
begin
cases le_total x y,
{ rw interval_of_le h,
exact segment_subset_Icc h },
{ rw [interval_of_ge h, segment_symm],
exact segment_subset_Icc h }
end
lemma convex.min_le_combo (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min x y ≤ a • x + b • y :=
(segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).1
lemma convex.combo_le_max (x y : E) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
a • x + b • y ≤ max x y :=
(segment_subset_interval x y ⟨_, _, ha, hb, hab, rfl⟩).2
end linear_ordered_add_comm_monoid
end ordered_semiring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
lemma Icc_subset_segment {x y : 𝕜} : Icc x y ⊆ [x -[𝕜] y] :=
begin
rintro z ⟨hxz, hyz⟩,
obtain rfl | h := (hxz.trans hyz).eq_or_lt,
{ rw segment_same,
exact hyz.antisymm hxz },
rw ←sub_nonneg at hxz hyz,
rw ←sub_pos at h,
refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩,
{ rw [←add_div, sub_add_sub_cancel, div_self h.ne'] },
{ rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div,
div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] }
end
@[simp] lemma segment_eq_Icc {x y : 𝕜} (h : x ≤ y) : [x -[𝕜] y] = Icc x y :=
(segment_subset_Icc h).antisymm Icc_subset_segment
lemma Ioo_subset_open_segment {x y : 𝕜} : Ioo x y ⊆ open_segment 𝕜 x y :=
λ z hz, mem_open_segment_of_ne_left_right hz.1.ne hz.2.ne'
(Icc_subset_segment $ Ioo_subset_Icc_self hz)
@[simp] lemma open_segment_eq_Ioo {x y : 𝕜} (h : x < y) : open_segment 𝕜 x y = Ioo x y :=
(open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment
lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) :=
begin
cases le_total x y,
{ rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] },
{ rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] }
end
lemma open_segment_eq_Ioo' {x y : 𝕜} (hxy : x ≠ y) :
open_segment 𝕜 x y = Ioo (min x y) (max x y) :=
begin
cases hxy.lt_or_lt,
{ rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] },
{ rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] }
end
lemma segment_eq_interval (x y : 𝕜) : [x -[𝕜] y] = interval x y :=
segment_eq_Icc' _ _
/-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Icc {x y : 𝕜} (h : x ≤ y) {z : 𝕜} :
z ∈ Icc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
rw ←segment_eq_Icc h,
simp_rw [←exists_prop],
refl,
end
/-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints.
-/
lemma convex.mem_Ioo {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ioo x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
rw ←open_segment_eq_Ioo h,
simp_rw [←exists_prop],
refl,
end
/-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the
endpoints. -/
lemma convex.mem_Ioc {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ioc x y ↔ ∃ (a b : 𝕜), 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
split,
{ rintro hz,
obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz),
obtain rfl | hb' := hb.eq_or_lt,
{ rw add_zero at hab,
rw [hab, one_mul, zero_mul, add_zero] at hz,
exact (hz.1.ne rfl).elim },
{ exact ⟨a, b, ha, hb', hab, rfl⟩ } },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] },
{ exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } }
end
/-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the
endpoints. -/
lemma convex.mem_Ico {x y : 𝕜} (h : x < y) {z : 𝕜} :
z ∈ Ico x y ↔ ∃ (a b : 𝕜), 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
split,
{ rintro hz,
obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz),
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rw [hab, one_mul, zero_mul, zero_add] at hz,
exact (hz.2.ne rfl).elim },
{ exact ⟨a, b, ha', hb, hab, rfl⟩ } },
{ rintro ⟨a, b, ha, hb, hab, rfl⟩,
obtain rfl | hb' := hb.eq_or_lt,
{ rw add_zero at hab,
rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] },
{ exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } }
end
end linear_ordered_field
/-! ### Convexity of sets -/
section ordered_semiring
variables [ordered_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F]
section has_smul
variables (𝕜) [has_smul 𝕜 E] [has_smul 𝕜 F] (s : set E)
/-- Convexity of sets. -/
def convex : Prop :=
∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 →
a • x + b • y ∈ s
variables {𝕜 s}
lemma convex_iff_segment_subset :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → [x -[𝕜] y] ⊆ s :=
forall₄_congr $ λ x y hx hy, (segment_subset_iff _).symm
lemma convex.segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) :
[x -[𝕜] y] ⊆ s :=
convex_iff_segment_subset.1 h hx hy
lemma convex.open_segment_subset (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s) :
open_segment 𝕜 x y ⊆ s :=
(open_segment_subset_segment 𝕜 x y).trans (h.segment_subset hx hy)
/-- Alternative definition of set convexity, in terms of pointwise set operations. -/
lemma convex_iff_pointwise_add_subset :
convex 𝕜 s ↔ ∀ ⦃a b : 𝕜⦄, 0 ≤ a → 0 ≤ b → a + b = 1 → a • s + b • s ⊆ s :=
iff.intro
begin
rintro hA a b ha hb hab w ⟨au, bv, ⟨u, hu, rfl⟩, ⟨v, hv, rfl⟩, rfl⟩,
exact hA hu hv ha hb hab
end
(λ h x y hx hy a b ha hb hab,
(h ha hb hab) (set.add_mem_add ⟨_, hx, rfl⟩ ⟨_, hy, rfl⟩))
alias convex_iff_pointwise_add_subset ↔ convex.set_combo_subset _
lemma convex_empty : convex 𝕜 (∅ : set E) :=
λ x y, false.elim
lemma convex_univ : convex 𝕜 (set.univ : set E) := λ _ _ _ _ _ _ _ _ _, trivial
lemma convex.inter {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s ∩ t) :=
λ x y (hx : x ∈ s ∩ t) (hy : y ∈ s ∩ t) a b (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1),
⟨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb hab⟩
lemma convex_sInter {S : set (set E)} (h : ∀ s ∈ S, convex 𝕜 s) : convex 𝕜 (⋂₀ S) :=
assume x y hx hy a b ha hb hab s hs,
h s hs (hx s hs) (hy s hs) ha hb hab
lemma convex_Inter {ι : Sort*} {s : ι → set E} (h : ∀ i, convex 𝕜 (s i)) : convex 𝕜 (⋂ i, s i) :=
(sInter_range s) ▸ convex_sInter $ forall_range_iff.2 h
lemma convex_Inter₂ {ι : Sort*} {κ : ι → Sort*} {s : Π i, κ i → set E}
(h : ∀ i j, convex 𝕜 (s i j)) :
convex 𝕜 (⋂ i j, s i j) :=
convex_Inter $ λ i, convex_Inter $ h i
lemma convex.prod {s : set E} {t : set F} (hs : convex 𝕜 s) (ht : convex 𝕜 t) :
convex 𝕜 (s ×ˢ t) :=
begin
intros x y hx hy a b ha hb hab,
apply mem_prod.2,
exact ⟨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab,
ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb hab⟩
end
lemma convex_pi {ι : Type*} {E : ι → Type*} [Π i, add_comm_monoid (E i)]
[Π i, has_smul 𝕜 (E i)] {s : set ι} {t : Π i, set (E i)} (ht : ∀ i, convex 𝕜 (t i)) :
convex 𝕜 (s.pi t) :=
λ x y hx hy a b ha hb hab i hi, ht i (hx i hi) (hy i hi) ha hb hab
lemma directed.convex_Union {ι : Sort*} {s : ι → set E} (hdir : directed (⊆) s)
(hc : ∀ ⦃i : ι⦄, convex 𝕜 (s i)) :
convex 𝕜 (⋃ i, s i) :=
begin
rintro x y hx hy a b ha hb hab,
rw mem_Union at ⊢ hx hy,
obtain ⟨i, hx⟩ := hx,
obtain ⟨j, hy⟩ := hy,
obtain ⟨k, hik, hjk⟩ := hdir i j,
exact ⟨k, hc (hik hx) (hjk hy) ha hb hab⟩,
end
lemma directed_on.convex_sUnion {c : set (set E)} (hdir : directed_on (⊆) c)
(hc : ∀ ⦃A : set E⦄, A ∈ c → convex 𝕜 A) :
convex 𝕜 (⋃₀c) :=
begin
rw sUnion_eq_Union,
exact (directed_on_iff_directed.1 hdir).convex_Union (λ A, hc A.2),
end
end has_smul
section module
variables [module 𝕜 E] [module 𝕜 F] {s : set E}
lemma convex_iff_open_segment_subset :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → open_segment 𝕜 x y ⊆ s :=
convex_iff_segment_subset.trans $ forall₄_congr $ λ x y hx hy,
(open_segment_subset_iff_segment_subset hx hy).symm
lemma convex_iff_forall_pos :
convex 𝕜 s ↔ ∀ ⦃x y⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1
→ a • x + b • y ∈ s :=
convex_iff_open_segment_subset.trans $ forall₄_congr $ λ x y hx hy,
open_segment_subset_iff 𝕜
lemma convex_iff_pairwise_pos :
convex 𝕜 s ↔ s.pairwise (λ x y, ∀ ⦃a b : 𝕜⦄, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s) :=
begin
refine convex_iff_forall_pos.trans ⟨λ h x hx y hy _, h hx hy, _⟩,
intros h x y hx hy a b ha hb hab,
obtain rfl | hxy := eq_or_ne x y,
{ rwa convex.combo_self hab },
{ exact h hx hy hxy ha hb hab },
end
protected lemma set.subsingleton.convex {s : set E} (h : s.subsingleton) : convex 𝕜 s :=
convex_iff_pairwise_pos.mpr (h.pairwise _)
lemma convex_singleton (c : E) : convex 𝕜 ({c} : set E) :=
subsingleton_singleton.convex
lemma convex_segment (x y : E) : convex 𝕜 [x -[𝕜] y] :=
begin
rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ a b ha hb hab,
refine ⟨a * ap + b * aq, a * bp + b * bq,
add_nonneg (mul_nonneg ha hap) (mul_nonneg hb haq),
add_nonneg (mul_nonneg ha hbp) (mul_nonneg hb hbq), _, _⟩,
{ rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] },
{ simp_rw [add_smul, mul_smul, smul_add],
exact add_add_add_comm _ _ _ _ }
end
lemma convex_open_segment (a b : E) : convex 𝕜 (open_segment 𝕜 a b) :=
begin
rw convex_iff_open_segment_subset,
rintro p q ⟨ap, bp, hap, hbp, habp, rfl⟩ ⟨aq, bq, haq, hbq, habq, rfl⟩ z ⟨a, b, ha, hb, hab, rfl⟩,
refine ⟨a * ap + b * aq, a * bp + b * bq,
add_pos (mul_pos ha hap) (mul_pos hb haq),
add_pos (mul_pos ha hbp) (mul_pos hb hbq), _, _⟩,
{ rw [add_add_add_comm, ←mul_add, ←mul_add, habp, habq, mul_one, mul_one, hab] },
{ simp_rw [add_smul, mul_smul, smul_add],
exact add_add_add_comm _ _ _ _ }
end
lemma convex.linear_image (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) : convex 𝕜 (f '' s) :=
begin
intros x y hx hy a b ha hb hab,
obtain ⟨x', hx', rfl⟩ := mem_image_iff_bex.1 hx,
obtain ⟨y', hy', rfl⟩ := mem_image_iff_bex.1 hy,
exact ⟨a • x' + b • y', hs hx' hy' ha hb hab, by rw [f.map_add, f.map_smul, f.map_smul]⟩,
end
lemma convex.is_linear_image (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) :
convex 𝕜 (f '' s) :=
hs.linear_image $ hf.mk' f
lemma convex.linear_preimage {s : set F} (hs : convex 𝕜 s) (f : E →ₗ[𝕜] F) :
convex 𝕜 (f ⁻¹' s) :=
begin
intros x y hx hy a b ha hb hab,
rw [mem_preimage, f.map_add, f.map_smul, f.map_smul],
exact hs hx hy ha hb hab,
end
lemma convex.is_linear_preimage {s : set F} (hs : convex 𝕜 s) {f : E → F} (hf : is_linear_map 𝕜 f) :
convex 𝕜 (f ⁻¹' s) :=
hs.linear_preimage $ hf.mk' f
lemma convex.add {t : set E} (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s + t) :=
by { rw ← add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add }
lemma convex.vadd (hs : convex 𝕜 s) (z : E) : convex 𝕜 (z +ᵥ s) :=
by { simp_rw [←image_vadd, vadd_eq_add, ←singleton_add], exact (convex_singleton _).add hs }
lemma convex.translate (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) '' s) := hs.vadd _
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_right (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, z + x) ⁻¹' s) :=
begin
intros x y hx hy a b ha hb hab,
have h := hs hx hy ha hb hab,
rwa [smul_add, smul_add, add_add_add_comm, ←add_smul, hab, one_smul] at h,
end
/-- The translation of a convex set is also convex. -/
lemma convex.translate_preimage_left (hs : convex 𝕜 s) (z : E) : convex 𝕜 ((λ x, x + z) ⁻¹' s) :=
by simpa only [add_comm] using hs.translate_preimage_right z
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_Iic (r : β) : convex 𝕜 (Iic r) :=
λ x y hx hy a b ha hb hab,
calc
a • x + b • y
≤ a • r + b • r
: add_le_add (smul_le_smul_of_nonneg hx ha) (smul_le_smul_of_nonneg hy hb)
... = r : convex.combo_self hab _
lemma convex_Ici (r : β) : convex 𝕜 (Ici r) := @convex_Iic 𝕜 βᵒᵈ _ _ _ _ r
lemma convex_Icc (r s : β) : convex 𝕜 (Icc r s) :=
Ici_inter_Iic.subst ((convex_Ici r).inter $ convex_Iic s)
lemma convex_halfspace_le {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w ≤ r} :=
(convex_Iic r).is_linear_preimage h
lemma convex_halfspace_ge {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | r ≤ f w} :=
(convex_Ici r).is_linear_preimage h
lemma convex_hyperplane {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w = r} :=
begin
simp_rw le_antisymm_iff,
exact (convex_halfspace_le h r).inter (convex_halfspace_ge h r),
end
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_Iio (r : β) : convex 𝕜 (Iio r) :=
begin
intros x y hx hy a b ha hb hab,
obtain rfl | ha' := ha.eq_or_lt,
{ rw zero_add at hab,
rwa [zero_smul, zero_add, hab, one_smul] },
rw mem_Iio at hx hy,
calc
a • x + b • y
< a • r + b • r
: add_lt_add_of_lt_of_le (smul_lt_smul_of_pos hx ha') (smul_le_smul_of_nonneg hy.le hb)
... = r : convex.combo_self hab _
end
lemma convex_Ioi (r : β) : convex 𝕜 (Ioi r) := @convex_Iio 𝕜 βᵒᵈ _ _ _ _ r
lemma convex_Ioo (r s : β) : convex 𝕜 (Ioo r s) :=
Ioi_inter_Iio.subst ((convex_Ioi r).inter $ convex_Iio s)
lemma convex_Ico (r s : β) : convex 𝕜 (Ico r s) :=
Ici_inter_Iio.subst ((convex_Ici r).inter $ convex_Iio s)
lemma convex_Ioc (r s : β) : convex 𝕜 (Ioc r s) :=
Ioi_inter_Iic.subst ((convex_Ioi r).inter $ convex_Iic s)
lemma convex_halfspace_lt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | f w < r} :=
(convex_Iio r).is_linear_preimage h
lemma convex_halfspace_gt {f : E → β} (h : is_linear_map 𝕜 f) (r : β) :
convex 𝕜 {w | r < f w} :=
(convex_Ioi r).is_linear_preimage h
end ordered_cancel_add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid β] [module 𝕜 β] [ordered_smul 𝕜 β]
lemma convex_interval (r s : β) : convex 𝕜 (interval r s) :=
convex_Icc _ _
end linear_ordered_add_comm_monoid
end module
end add_comm_monoid
section linear_ordered_add_comm_monoid
variables [linear_ordered_add_comm_monoid E] [ordered_add_comm_monoid β] [module 𝕜 E]
[ordered_smul 𝕜 E] {s : set E} {f : E → β}
lemma monotone_on.convex_le (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab,
(hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans
(max_rec' _ hx.2 hy.2)⟩
lemma monotone_on.convex_lt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x < r} :=
λ x y hx hy a b ha hb hab, ⟨hs hx.1 hy.1 ha hb hab,
(hf (hs hx.1 hy.1 ha hb hab) (max_rec' s hx.1 hy.1) (convex.combo_le_max x y ha hb hab)).trans_lt
(max_rec' _ hx.2 hy.2)⟩
lemma monotone_on.convex_ge (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
@monotone_on.convex_le 𝕜 Eᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual hs r
lemma monotone_on.convex_gt (hf : monotone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r < f x} :=
@monotone_on.convex_lt 𝕜 Eᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual hs r
lemma antitone_on.convex_le (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x ≤ r} :=
@monotone_on.convex_ge 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_lt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | f x < r} :=
@monotone_on.convex_gt 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_ge (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r ≤ f x} :=
@monotone_on.convex_le 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma antitone_on.convex_gt (hf : antitone_on f s) (hs : convex 𝕜 s) (r : β) :
convex 𝕜 {x ∈ s | r < f x} :=
@monotone_on.convex_lt 𝕜 E βᵒᵈ _ _ _ _ _ _ _ hf hs r
lemma monotone.convex_le (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma monotone.convex_lt (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma monotone.convex_ge (hf : monotone f ) (r : β) :
convex 𝕜 {x | r ≤ f x} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_ge convex_univ r)
lemma monotone.convex_gt (hf : monotone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.monotone_on univ).convex_le convex_univ r)
lemma antitone.convex_le (hf : antitone f) (r : β) :
convex 𝕜 {x | f x ≤ r} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_le convex_univ r)
lemma antitone.convex_lt (hf : antitone f) (r : β) :
convex 𝕜 {x | f x < r} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_lt convex_univ r)
lemma antitone.convex_ge (hf : antitone f) (r : β) :
convex 𝕜 {x | r ≤ f x} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_ge convex_univ r)
lemma antitone.convex_gt (hf : antitone f) (r : β) :
convex 𝕜 {x | r < f x} :=
set.sep_univ.subst ((hf.antitone_on univ).convex_gt convex_univ r)
end linear_ordered_add_comm_monoid
section add_comm_group
variables [add_comm_group E] [module 𝕜 E] {s t : set E}
lemma convex.combo_eq_vadd {a b : 𝕜} {x y : E} (h : a + b = 1) :
a • x + b • y = b • (y - x) + x :=
calc
a • x + b • y = (b • y - b • x) + (a • x + b • x) : by abel
... = b • (y - x) + x : by rw [smul_sub, convex.combo_self h]
end add_comm_group
end ordered_semiring
section ordered_comm_semiring
variables [ordered_comm_semiring 𝕜]
section add_comm_monoid
variables [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F] {s : set E}
lemma convex.smul (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 (c • s) :=
hs.linear_image (linear_map.lsmul _ _ c)
lemma convex.smul_preimage (hs : convex 𝕜 s) (c : 𝕜) : convex 𝕜 ((λ z, c • z) ⁻¹' s) :=
hs.linear_preimage (linear_map.lsmul _ _ c)
lemma convex.affinity (hs : convex 𝕜 s) (z : E) (c : 𝕜) : convex 𝕜 ((λ x, z + c • x) '' s) :=
by simpa only [←image_smul, ←image_vadd, image_image] using (hs.smul c).vadd z
end add_comm_monoid
end ordered_comm_semiring
section ordered_ring
variables [ordered_ring 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s t : set E}
lemma convex.add_smul_mem (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • y ∈ s :=
begin
have h : x + t • y = (1 - t) • x + t • (x + y),
{ rw [smul_add, ←add_assoc, ←add_smul, sub_add_cancel, one_smul] },
rw h,
exact hs hx hy (sub_nonneg_of_le ht.2) ht.1 (sub_add_cancel _ _),
end
lemma convex.smul_mem_of_zero_mem (hs : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s) (hx : x ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : t • x ∈ s :=
by simpa using hs.add_smul_mem zero_mem (by simpa using hx) ht
lemma convex.add_smul_sub_mem (h : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ s)
{t : 𝕜} (ht : t ∈ Icc (0 : 𝕜) 1) : x + t • (y - x) ∈ s :=
begin
apply h.segment_subset hx hy,
rw segment_eq_image',
exact mem_image_of_mem _ ht,
end
/-- Affine subspaces are convex. -/
lemma affine_subspace.convex (Q : affine_subspace 𝕜 E) : convex 𝕜 (Q : set E) :=
begin
intros x y hx hy a b ha hb hab,
rw [eq_sub_of_add_eq hab, ← affine_map.line_map_apply_module],
exact affine_map.line_map_mem b hx hy,
end
/--
Applying an affine map to an affine combination of two points yields
an affine combination of the images.
-/
lemma convex.combo_affine_apply {a b : 𝕜} {x y : E} {f : E →ᵃ[𝕜] F} (h : a + b = 1) :
f (a • x + b • y) = a • f x + b • f y :=
begin
simp only [convex.combo_eq_vadd h, ← vsub_eq_sub],
exact f.apply_line_map _ _ _,
end
/-- The preimage of a convex set under an affine map is convex. -/
lemma convex.affine_preimage (f : E →ᵃ[𝕜] F) {s : set F} (hs : convex 𝕜 s) :
convex 𝕜 (f ⁻¹' s) :=
begin
intros x y xs ys a b ha hb hab,
rw [mem_preimage, convex.combo_affine_apply hab],
exact hs xs ys ha hb hab,
end
/-- The image of a convex set under an affine map is convex. -/
lemma convex.affine_image (f : E →ᵃ[𝕜] F) (hs : convex 𝕜 s) : convex 𝕜 (f '' s) :=
begin
rintro x y ⟨x', ⟨hx', hx'f⟩⟩ ⟨y', ⟨hy', hy'f⟩⟩ a b ha hb hab,
refine ⟨a • x' + b • y', ⟨hs hx' hy' ha hb hab, _⟩⟩,
rw [convex.combo_affine_apply hab, hx'f, hy'f]
end
lemma convex.neg (hs : convex 𝕜 s) : convex 𝕜 (-s) :=
hs.is_linear_preimage is_linear_map.is_linear_map_neg
lemma convex.sub (hs : convex 𝕜 s) (ht : convex 𝕜 t) : convex 𝕜 (s - t) :=
by { rw sub_eq_add_neg, exact hs.add ht.neg }
end add_comm_group
end ordered_ring
section linear_ordered_field
variables [linear_ordered_field 𝕜]
section add_comm_group
variables [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] {s : set E}
/-- Alternative definition of set convexity, using division. -/
lemma convex_iff_div :
convex 𝕜 s ↔ ∀ ⦃x y : E⦄, x ∈ s → y ∈ s → ∀ ⦃a b : 𝕜⦄,
0 ≤ a → 0 ≤ b → 0 < a + b → (a / (a + b)) • x + (b / (a + b)) • y ∈ s :=
begin
simp only [convex_iff_segment_subset, subset_def, mem_segment_iff_div],
refine forall₄_congr (λ x y hx hy, ⟨λ H a b ha hb hab, H _ ⟨a, b, ha, hb, hab, rfl⟩, _⟩),
rintro H _ ⟨a, b, ha, hb, hab, rfl⟩,
exact H ha hb hab
end
lemma convex.mem_smul_of_zero_mem (h : convex 𝕜 s) {x : E} (zero_mem : (0 : E) ∈ s)
(hx : x ∈ s) {t : 𝕜} (ht : 1 ≤ t) :
x ∈ t • s :=
begin
rw mem_smul_set_iff_inv_smul_mem₀ (zero_lt_one.trans_le ht).ne',
exact h.smul_mem_of_zero_mem zero_mem hx ⟨inv_nonneg.2 (zero_le_one.trans ht), inv_le_one ht⟩,
end
lemma convex.add_smul (h_conv : convex 𝕜 s) {p q : 𝕜} (hp : 0 ≤ p) (hq : 0 ≤ q) :
(p + q) • s = p • s + q • s :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ simp_rw [smul_set_empty, add_empty] },
obtain rfl | hp' := hp.eq_or_lt,
{ rw [zero_add, zero_smul_set hs, zero_add] },
obtain rfl | hq' := hq.eq_or_lt,
{ rw [add_zero, zero_smul_set hs, add_zero] },
ext,
split,
{ rintro ⟨v, hv, rfl⟩,
exact ⟨p • v, q • v, smul_mem_smul_set hv, smul_mem_smul_set hv, (add_smul _ _ _).symm⟩ },
{ rintro ⟨v₁, v₂, ⟨v₁₁, h₁₂, rfl⟩, ⟨v₂₁, h₂₂, rfl⟩, rfl⟩,
have hpq := add_pos hp' hq',
exact mem_smul_set.2 ⟨_, h_conv h₁₂ h₂₂ (div_pos hp' hpq).le (div_pos hq' hpq).le
(by rw [←div_self hpq.ne', add_div] : p / (p + q) + q / (p + q) = 1),
by simp only [← mul_smul, smul_add, mul_div_cancel' _ hpq.ne']⟩ }
end
end add_comm_group
end linear_ordered_field
/-!
#### Convex sets in an ordered space
Relates `convex` and `ord_connected`.
-/
section
lemma set.ord_connected.convex_of_chain [ordered_semiring 𝕜] [ordered_add_comm_monoid E]
[module 𝕜 E] [ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) (h : is_chain (≤) s) :
convex 𝕜 s :=
begin
refine convex_iff_segment_subset.mpr (λ x y hx hy, _),
obtain hxy | hyx := h.total hx hy,
{ exact (segment_subset_Icc hxy).trans (hs.out hx hy) },
{ rw segment_symm,
exact (segment_subset_Icc hyx).trans (hs.out hy hx) }
end
lemma set.ord_connected.convex [ordered_semiring 𝕜] [linear_ordered_add_comm_monoid E] [module 𝕜 E]
[ordered_smul 𝕜 E] {s : set E} (hs : s.ord_connected) :
convex 𝕜 s :=
hs.convex_of_chain $ is_chain_of_trichotomous s
lemma convex_iff_ord_connected [linear_ordered_field 𝕜] {s : set 𝕜} :
convex 𝕜 s ↔ s.ord_connected :=
begin
simp_rw [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset],
exact forall_congr (λ x, forall_swap)
end
alias convex_iff_ord_connected ↔ convex.ord_connected _
end
/-! #### Convexity of submodules/subspaces -/
section submodule
open submodule
lemma submodule.convex [ordered_semiring 𝕜] [add_comm_monoid E] [module 𝕜 E] (K : submodule 𝕜 E) :
convex 𝕜 (↑K : set E) :=
by { repeat {intro}, refine add_mem (smul_mem _ _ _) (smul_mem _ _ _); assumption }
lemma subspace.convex [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] (K : subspace 𝕜 E) :
convex 𝕜 (↑K : set E) :=
K.convex
end submodule
/-! ### Simplex -/
section simplex
variables (𝕜) (ι : Type*) [ordered_semiring 𝕜] [fintype ι]
/-- The standard simplex in the space of functions `ι → 𝕜` is the set of vectors with non-negative
coordinates with total sum `1`. This is the free object in the category of convex spaces. -/
def std_simplex : set (ι → 𝕜) :=
{f | (∀ x, 0 ≤ f x) ∧ ∑ x, f x = 1}
lemma std_simplex_eq_inter :
std_simplex 𝕜 ι = (⋂ x, {f | 0 ≤ f x}) ∩ {f | ∑ x, f x = 1} :=
by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] }
lemma convex_std_simplex : convex 𝕜 (std_simplex 𝕜 ι) :=
begin
refine λ f g hf hg a b ha hb hab, ⟨λ x, _, _⟩,
{ apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] },
{ erw [finset.sum_add_distrib, ← finset.smul_sum, ← finset.smul_sum, hf.2, hg.2,
smul_eq_mul, smul_eq_mul, mul_one, mul_one],
exact hab }
end
variable {ι}
lemma ite_eq_mem_std_simplex (i : ι) : (λ j, ite (i = j) (1:𝕜) 0) ∈ std_simplex 𝕜 ι :=
⟨λ j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)]⟩
end simplex
|
607b77f4f8b199631671ef7c11612dda2c7e1436 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/779.hlean | 204cc370a5c30054089dfcaac23d637835b4fb78 | [
"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 | 78 | hlean | definition foo (x : empty) : empty :=
by try exact _;contradiction
print foo
|
471c317b79f831aef45ee7f749400a3512cfaed6 | 618003631150032a5676f229d13a079ac875ff77 | /src/tactic/lint/frontend.lean | ce2225e8e8fabed9cdc91010105aad8d89666f59 | [
"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 | 12,696 | 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, Robert Y. Lewis, Gabriel Ebner
-/
import tactic.lint.basic
/-!
# Linter frontend and commands
This file defines the linter commands which spot common mistakes in the code.
* `#lint`: check all declarations in the current file
* `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects,
and also excluding the current file)
* `#lint_all`: check all declarations in the environment (the current file and all
imported files)
For a list of default / non-default linters, see the "Linting Commands" user command doc entry.
The command `#list_linters` prints a list of the names of all available linters.
You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4).
You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint
that suppresses the output of passing checks.
A silent lint will fail if any test fails.
You can append a sequence of linter names to any command to run extra tests, in addition to the
default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`.
You can append `only name1 name2 ...` to any command to run a subset of linters, e.g.
`#lint only unused_arguments`
You can add custom linters by defining a term of type `linter` in the `linter` namespace.
A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check`
or `lint only my_new_check`.
If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default.
Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration
omits it from only the specified linter checks.
## Tags
sanity check, lint, cleanup, command, tactic
-/
reserve notation `#lint`
reserve notation `#lint_mathlib`
reserve notation `#lint_all`
reserve notation `#list_linters`
open tactic expr native
setup_tactic_parser
/-- `get_checks slow extra use_only` produces a list of linters.
`extras` is a list of names that should resolve to declarations with type `linter`.
If `use_only` is true, it only uses the linters in `extra`.
Otherwise, it uses all linters in the environment tagged with `@[linter]`.
If `slow` is false, it only uses the fast default tests. -/
meta def get_checks (slow : bool) (extra : list name) (use_only : bool) :
tactic (list (name × linter)) := do
default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters,
let default := if slow then default else default.filter (λ l, l.2.is_fast),
list.append default <$> get_linters extra
/--
`lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations.
If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`.
If `auto_decls` is true, then it is applied to `all_decls`.
The resulting list has one element for each linter, containing the linter as
well as a map from declaration name to warning.
-/
meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name × linter)) :
tactic (list (name × linter × rb_map name string)) := do
checks.mmap $ λ ⟨linter_name, linter⟩, do
let test_decls := if linter.auto_decls then all_decls else non_auto_decls,
results ← test_decls.mfoldl (λ (results : rb_map name string) decl, do
tt ← should_be_linted linter_name decl.to_name | pure results,
s ← read,
let linter_warning : option string :=
match linter.test decl s with
| result.success w _ := w
| result.exception msg _ _ :=
some $ "LINTER FAILED:\n" ++ msg.elim "(no message)" (λ msg, to_string $ msg ())
end,
match linter_warning with
| some w := pure $ results.insert decl.to_name w
| none := pure results
end) mk_rb_map,
pure (linter_name, linter, results)
/-- Sorts a map with declaration keys as names by line number. -/
meta def sort_results {α} (e : environment) (results : rb_map name α) : list (name × α) :=
list.reverse $ rb_lmap.values $ rb_lmap.of_list $
results.fold [] $ λ decl linter_warning results,
(((e.decl_pos decl).get_or_else ⟨0,0⟩).line, (decl, linter_warning)) :: results
/-- Formats a linter warning as `#print` command with comment. -/
meta def print_warning (decl_name : name) (warning : string) : format :=
"#print " ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/"
/-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/
meta def print_warnings (env : environment) (results : rb_map name string) : format :=
format.intercalate format.line $ (sort_results env results).map $
λ ⟨decl_name, warning⟩, print_warning decl_name warning
/--
Formats a map of linter warnings grouped by filename with `-- filename` comments.
The first `drop_fn_chars` characters are stripped from the filename.
-/
meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0)
(formatter: rb_map name string → format) : format :=
let results := results.fold (rb_map.mk string (rb_map name string)) $
λ decl_name linter_warning results,
let fn := (e.decl_olean decl_name).get_or_else "" in
results.insert fn (((results.find fn).get_or_else mk_rb_map).insert
decl_name linter_warning) in
let l := results.to_list.reverse.map (λ ⟨fn, results⟩,
("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in
format.intercalate "\n\n" l ++ "\n"
/--
Formats the linter results as Lean code with comments and `#print` commands.
-/
meta def format_linter_results
(env : environment)
(results : list (name × linter × rb_map name string))
(decls non_auto_decls : list declaration)
(group_by_filename : option nat)
(where_desc : string) (slow verbose : bool) :
format := do
let formatted_results := results.map $ λ ⟨linter_name, linter, results⟩,
let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in
if ¬ results.empty then do
let warnings := match group_by_filename with
| none := print_warnings env results
| some dropped := grouped_by_filename env results dropped (print_warnings env)
end in
report_str ++ "/- " ++ linter.errors_found ++ ": -/\n" ++ warnings ++ "\n"
else
if verbose then "/- OK: " ++ linter.no_errors_found ++ ". -/" else format.nil,
let s := format.intercalate "\n" (formatted_results.filter (λ f, ¬ f.is_nil)),
let s := if ¬ verbose then s else
format!"/- Checking {non_auto_decls.length} declarations (plus {decls.length - non_auto_decls.length} automatically generated ones) {where_desc} -/\n\n" ++ s,
let s := if slow then s else s ++ "/- (slow tests skipped) -/\n",
s
/-- The common denominator of `#lint[|mathlib|all]`.
The different commands have different configurations for `l`,
`group_by_filename` and `where_desc`.
If `slow` is false, doesn't do the checks that take a lot of time.
If `verbose` is false, it will suppress messages from passing checks.
By setting `checks` you can customize which checks are performed.
Returns a `name_set` containing the names of all declarations that fail any check in `check`,
and a `format` object describing the failures. -/
meta def lint_aux (decls : list declaration) (group_by_filename : option nat)
(where_desc : string) (slow verbose : bool) (checks : list (name × linter)) :
tactic (name_set × format) := do
e ← get_env,
let non_auto_decls := decls.filter (λ d, ¬ d.is_auto_or_internal e),
results ← lint_core decls non_auto_decls checks,
let s := format_linter_results e results decls non_auto_decls
group_by_filename where_desc slow verbose,
let ns := name_set.of_list (do (_,_,rs) ← results, rs.keys),
pure (ns, s)
/-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/
meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
let l := e.filter (λ d, e.in_current_file' d.to_name),
lint_aux l none "in the current file" slow verbose checks
/-- Returns the declarations considered by the mathlib linter. -/
meta def lint_mathlib_decls : tactic (list declaration) := do
e ← get_env,
ml ← get_mathlib_dir,
pure $ e.filter $ λ d, e.is_prefix_of_file ml d.to_name
/-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations
that fail. -/
meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
decls ← lint_mathlib_decls,
mathlib_path_len ← string.length <$> get_mathlib_dir,
lint_aux decls mathlib_path_len "in mathlib (only in imported files)" slow verbose checks
/-- Return the message printed by `#lint_all` and a `name_set` containing all declarations
that fail. -/
meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := [])
(use_only : bool := ff) : tactic (name_set × format) := do
checks ← get_checks slow extra use_only,
e ← get_env,
let l := e.get_decls,
lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks
/-- Parses an optional `only`, followed by a sequence of zero or more identifiers.
Prepends `linter.` to each of these identifiers. -/
private meta def parse_lint_additions : parser (bool × list name) :=
prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*)
/-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/
private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) :
parser unit :=
do silent ← optional (tk "-"),
fast_only ← optional (tk "*"),
silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *-
(use_only, extra) ← parse_lint_additions,
(failed, s) ← scope fast_only.is_none silent.is_none extra use_only,
when (¬ s.is_nil) $ trace s,
when (silent.is_some ∧ ¬ failed.empty) $
fail "Linting did not succeed"
/-- The command `#lint` at the bottom of a file will warn you about some common mistakes
in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`.
`#lint-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit :=
lint_cmd_aux @lint
/-- The command `#lint_mathlib` checks all of mathlib for certain mistakes.
Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`.
`#lint_mathlib-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit :=
lint_cmd_aux @lint_mathlib
/-- The command `#lint_all` checks all imported files for certain mistakes.
Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`.
`#lint_all-` will suppress the output of passing checks.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit :=
lint_cmd_aux @lint_all
/-- The command `#list_linters` prints a list of all available linters. -/
@[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit :=
do env ← get_env,
let ns := env.decl_filter_map $ λ dcl,
if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none,
trace "Available linters:\n linters marked with (*) are in the default lint set\n",
ns.mmap' $ λ n, do
b ← has_attribute' `linter n,
trace $ n.pop_prefix.to_string ++ if b then " (*)" else ""
/--
Invoking the hole command `lint` ("Find common mistakes in current file") will print text that
indicates mistakes made in the file above the command. It is equivalent to copying and pasting the
output of `#lint`. On large files, it may take some time before the output appears.
-/
@[hole_command] meta def lint_hole_cmd : hole_command :=
{ name := "Lint",
descr := "Lint: Find common mistakes in current file.",
action := λ es, do (_, s) ← lint, return [(s.to_string,"")] }
add_tactic_doc
{ name := "Lint",
category := doc_category.hole_cmd,
decl_names := [`lint_hole_cmd],
tags := ["linting"] }
|
94ad692bbfdbde34a7a17c60c0806b4c16d3d30f | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/order/order_iso_nat.lean | 6db6b072f1d94645cfe21943d8e02b396cf71793 | [
"Apache-2.0"
] | permissive | stjordanis/mathlib | 51e286d19140e3788ef2c470bc7b953e4991f0c9 | 2568d41bca08f5d6bf39d915434c8447e21f42ee | refs/heads/master | 1,631,748,053,501 | 1,627,938,886,000 | 1,627,938,886,000 | 228,728,358 | 0 | 0 | Apache-2.0 | 1,576,630,588,000 | 1,576,630,587,000 | null | UTF-8 | Lean | false | false | 8,963 | 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.equiv.denumerable
import order.preorder_hom
import order.conditionally_complete_lattice
/-!
# Relation embeddings from the naturals
This file allows translation from monotone functions `ℕ → α` to order embeddings `ℕ ↪ α` and
defines the limit value of an eventually-constant sequence.
## Main declarations
* `nat_lt`/`nat_gt`: Make an order embedding `ℕ ↪ α` from an increasing/decreasing function `ℕ → α`.
* `monotonic_sequence_limit`: The limit of an eventually-constant monotone sequence `ℕ →ₘ α`.
* `monotonic_sequence_limit_index`: The index of the first occurence of `monotonic_sequence_limit`
in the sequence.
-/
namespace rel_embedding
variables {α : Type*} {r : α → α → Prop} [is_strict_order α r]
/-- If `f` is a strictly `r`-increasing sequence, then this returns `f` as an order embedding. -/
def nat_lt (f : ℕ → α) (H : ∀ n : ℕ, r (f n) (f (n + 1))) :
((<) : ℕ → ℕ → Prop) ↪r r :=
of_monotone f $ λ a b h, begin
induction b with b IH, {exact (nat.not_lt_zero _ h).elim},
cases nat.lt_succ_iff_lt_or_eq.1 h with h e,
{ exact trans (IH h) (H _) },
{ subst b, apply H }
end
@[simp]
lemma nat_lt_apply {f : ℕ → α} {H : ∀ n : ℕ, r (f n) (f (n + 1))} {n : ℕ} :
nat_lt f H n = f n :=
rfl
/-- If `f` is a strictly `r`-decreasing sequence, then this returns `f` as an order embedding. -/
def nat_gt (f : ℕ → α) (H : ∀ n : ℕ, r (f (n + 1)) (f n)) :
((>) : ℕ → ℕ → Prop) ↪r r :=
by haveI := is_strict_order.swap r; exact rel_embedding.swap (nat_lt f H)
theorem well_founded_iff_no_descending_seq :
well_founded r ↔ ¬ nonempty (((>) : ℕ → ℕ → Prop) ↪r r) :=
⟨λ ⟨h⟩ ⟨⟨f, o⟩⟩,
suffices ∀ a, acc r a → ∀ n, a ≠ f n, from this (f 0) (h _) 0 rfl,
λ a ac, begin
induction ac with a _ IH, intros n h, subst a,
exact IH (f (n+1)) (o.2 (nat.lt_succ_self _)) _ rfl
end,
λ N, ⟨λ a, classical.by_contradiction $ λ na,
let ⟨f, h⟩ := classical.axiom_of_choice $
show ∀ x : {a // ¬ acc r a}, ∃ y : {a // ¬ acc r a}, r y.1 x.1,
from λ ⟨x, h⟩, classical.by_contradiction $ λ hn, h $
⟨_, λ y h, classical.by_contradiction $ λ na, hn ⟨⟨y, na⟩, h⟩⟩ in
N ⟨nat_gt (λ n, (f^[n] ⟨a, na⟩).1) $ λ n,
by { rw [function.iterate_succ'], apply h }⟩⟩⟩
end rel_embedding
namespace nat
variables (s : set ℕ) [decidable_pred (∈ s)] [infinite s]
/-- An order embedding from `ℕ` to itself with a specified range -/
def order_embedding_of_set : ℕ ↪o ℕ :=
(rel_embedding.order_embedding_of_lt_embedding
(rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _))).trans
(order_embedding.subtype s)
/-- `nat.subtype.of_nat` as an order isomorphism between `ℕ` and an infinite decidable subset. -/
noncomputable def subtype.order_iso_of_nat :
ℕ ≃o s :=
rel_iso.of_surjective (rel_embedding.order_embedding_of_lt_embedding
(rel_embedding.nat_lt (nat.subtype.of_nat s) (λ n, nat.subtype.lt_succ_self _)))
nat.subtype.of_nat_surjective
variable {s}
@[simp]
lemma order_embedding_of_set_apply {n : ℕ} : order_embedding_of_set s n = subtype.of_nat s n :=
rfl
@[simp]
lemma subtype.order_iso_of_nat_apply {n : ℕ} :
subtype.order_iso_of_nat s n = subtype.of_nat s n :=
by { simp [subtype.order_iso_of_nat] }
variable (s)
@[simp]
lemma order_embedding_of_set_range : set.range (nat.order_embedding_of_set s) = s :=
begin
ext x,
rw [set.mem_range, nat.order_embedding_of_set],
split; intro h,
{ obtain ⟨y, rfl⟩ := h,
simp },
{ refine ⟨(nat.subtype.order_iso_of_nat s).symm ⟨x, h⟩, _⟩,
simp only [rel_embedding.coe_trans, rel_embedding.order_embedding_of_lt_embedding_apply,
rel_embedding.nat_lt_apply, function.comp_app, order_embedding.subtype_apply],
rw [← subtype.order_iso_of_nat_apply, order_iso.apply_symm_apply, subtype.coe_mk] }
end
end nat
theorem exists_increasing_or_nonincreasing_subseq' {α : Type*} (r : α → α → Prop) (f : ℕ → α) :
∃ (g : ℕ ↪o ℕ), (∀ n : ℕ, r (f (g n)) (f (g (n + 1)))) ∨
(∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) :=
begin
classical,
let bad : set ℕ := { m | ∀ n, m < n → ¬ r (f m) (f n) },
by_cases hbad : infinite bad,
{ haveI := hbad,
refine ⟨nat.order_embedding_of_set bad, or.intro_right _ (λ m n mn, _)⟩,
have h := set.mem_range_self m,
rw nat.order_embedding_of_set_range bad at h,
exact h _ ((order_embedding.lt_iff_lt _).2 mn) },
{ rw [set.infinite_coe_iff, set.infinite, not_not] at hbad,
obtain ⟨m, hm⟩ : ∃ m, ∀ n, m ≤ n → ¬ n ∈ bad,
{ by_cases he : hbad.to_finset.nonempty,
{ refine ⟨(hbad.to_finset.max' he).succ, λ n hn nbad, nat.not_succ_le_self _
(hn.trans (hbad.to_finset.le_max' n (hbad.mem_to_finset.2 nbad)))⟩ },
{ exact ⟨0, λ n hn nbad, he ⟨n, hbad.mem_to_finset.2 nbad⟩⟩ } },
have h : ∀ (n : ℕ), ∃ (n' : ℕ), n < n' ∧ r (f (n + m)) (f (n' + m)),
{ intro n,
have h := hm _ (le_add_of_nonneg_left n.zero_le),
simp only [exists_prop, not_not, set.mem_set_of_eq, not_forall] at h,
obtain ⟨n', hn1, hn2⟩ := h,
obtain ⟨x, hpos, rfl⟩ := exists_pos_add_of_lt hn1,
refine ⟨n + x, add_lt_add_left hpos n, _⟩,
rw [add_assoc, add_comm x m, ← add_assoc],
exact hn2 },
let g' : ℕ → ℕ := @nat.rec (λ _, ℕ) m (λ n gn, nat.find (h gn)),
exact ⟨(rel_embedding.nat_lt (λ n, g' n + m)
(λ n, nat.add_lt_add_right (nat.find_spec (h (g' n))).1 m)).order_embedding_of_lt_embedding,
or.intro_left _ (λ n, (nat.find_spec (h (g' n))).2)⟩ }
end
theorem exists_increasing_or_nonincreasing_subseq
{α : Type*} (r : α → α → Prop) [is_trans α r] (f : ℕ → α) :
∃ (g : ℕ ↪o ℕ), (∀ m n : ℕ, m < n → r (f (g m)) (f (g n))) ∨
(∀ m n : ℕ, m < n → ¬ r (f (g m)) (f (g n))) :=
begin
obtain ⟨g, hr | hnr⟩ := exists_increasing_or_nonincreasing_subseq' r f,
{ refine ⟨g, or.intro_left _ (λ m n mn, _)⟩,
obtain ⟨x, rfl⟩ := le_iff_exists_add.1 (nat.succ_le_iff.2 mn),
induction x with x ih,
{ apply hr },
{ apply is_trans.trans _ _ _ _ (hr _),
exact ih (lt_of_lt_of_le m.lt_succ_self (nat.le_add_right _ _)) } },
{ exact ⟨g, or.intro_right _ hnr⟩ }
end
/-- The "monotone chain condition" below is sometimes a convenient form of well foundedness. -/
lemma well_founded.monotone_chain_condition (α : Type*) [partial_order α] :
well_founded ((>) : α → α → Prop) ↔ ∀ (a : ℕ →ₘ α), ∃ n, ∀ m, n ≤ m → a n = a m :=
begin
split; intros h,
{ rw well_founded.well_founded_iff_has_max' at h,
intros a, have hne : (set.range a).nonempty, { use a 0, simp, },
obtain ⟨x, ⟨n, hn⟩, range_bounded⟩ := h _ hne,
use n, intros m hm, rw ← hn at range_bounded, symmetry,
apply range_bounded (a m) (set.mem_range_self _) (a.monotone hm), },
{ rw rel_embedding.well_founded_iff_no_descending_seq, rintros ⟨a⟩,
obtain ⟨n, hn⟩ := h (a.swap : ((<) : ℕ → ℕ → Prop) →r ((<) : α → α → Prop)).to_preorder_hom,
exact n.succ_ne_self.symm (rel_embedding.to_preorder_hom_injective _ (hn _ n.le_succ)), },
end
/-- Given an eventually-constant monotonic sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a partially-ordered
type, `monotonic_sequence_limit_index a` is the least natural number `n` for which `aₙ` reaches the
constant value. For sequences that are not eventually constant, `monotonic_sequence_limit_index a`
is defined, but is a junk value. -/
noncomputable def monotonic_sequence_limit_index {α : Type*} [partial_order α] (a : ℕ →ₘ α) : ℕ :=
Inf { n | ∀ m, n ≤ m → a n = a m }
/-- The constant value of an eventually-constant monotonic sequence `a₀ ≤ a₁ ≤ a₂ ≤ ...` in a
partially-ordered type. -/
noncomputable def monotonic_sequence_limit {α : Type*} [partial_order α] (a : ℕ →ₘ α) :=
a (monotonic_sequence_limit_index a)
lemma well_founded.supr_eq_monotonic_sequence_limit {α : Type*} [complete_lattice α]
(h : well_founded ((>) : α → α → Prop)) (a : ℕ →ₘ α) :
(⨆ m, a m) = monotonic_sequence_limit a :=
begin
suffices : (⨆ (m : ℕ), a m) ≤ monotonic_sequence_limit a,
{ exact le_antisymm this (le_supr a _), },
apply supr_le,
intros m,
by_cases hm : m ≤ monotonic_sequence_limit_index a,
{ exact a.monotone hm, },
{ replace hm := le_of_not_le hm,
let S := { n | ∀ m, n ≤ m → a n = a m },
have hInf : Inf S ∈ S,
{ refine nat.Inf_mem _, rw well_founded.monotone_chain_condition at h, exact h a, },
change Inf S ≤ m at hm,
change a m ≤ a (Inf S),
rw hInf m hm, },
end
|
125b05aaacea69f0a3484af2953399f016d96814 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /library/init/char.lean | f9654c3c0a24dee7a5c8c0bb39515938532c0abf | [
"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 | 851 | 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.fin
open nat
definition char_sz : nat := succ 255
definition char := fin char_sz
namespace char
/- We cannot use tactic dec_trivial here because the tactic framework has not been defined yet. -/
private lemma zero_lt_char_sz : 0 < char_sz :=
zero_lt_succ _
attribute [pattern]
definition of_nat (n : nat) : char :=
if H : n < char_sz then fin.mk n H else fin.mk 0 zero_lt_char_sz
definition to_nat (c : char) : nat :=
fin.val c
end char
attribute [instance]
definition char_has_decidable_eq : decidable_eq char :=
have decidable_eq (fin char_sz), from fin.has_decidable_eq _,
this
attribute [instance]
definition char_is_inhabited : inhabited char :=
⟨'A'⟩
|
0738bace51a7f5070db9671f19815453a59dbea9 | 0c1546a496eccfb56620165cad015f88d56190c5 | /library/init/meta/converter.lean | 220a2ad0ab6670528deb43903dbee3e2a9e3b3cf | [
"Apache-2.0"
] | permissive | Solertis/lean | 491e0939957486f664498fbfb02546e042699958 | 84188c5aa1673fdf37a082b2de8562dddf53df3f | refs/heads/master | 1,610,174,257,606 | 1,486,263,620,000 | 1,486,263,620,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,025 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Converter monad for building simplifiers.
-/
prelude
import init.meta.tactic init.meta.simp_tactic
import init.meta.congr_lemma init.meta.match_tactic
open tactic
meta structure conv_result (α : Type) :=
(val : α) (rhs : expr) (proof : option expr)
meta def conv (α : Type) : Type :=
name → expr → tactic (conv_result α)
namespace conv
meta def lhs : conv expr :=
λ r e, return ⟨e, e, none⟩
meta def change (new_p : pexpr) : conv unit :=
λ r e, do
new_e ← to_expr new_p,
unify e new_e,
return ⟨(), new_e, none⟩
protected meta def pure {α : Type} : α → conv α :=
λ a r e, return ⟨a, e, none⟩
private meta def join_proofs (r : name) (o₁ o₂ : option expr) : tactic (option expr) :=
match o₁, o₂ with
| none, _ := return o₂
| _, none := return o₁
| some p₁, some p₂ := do
env ← get_env,
match (environment.trans_for env r) with
| (some trans) := do pr ← mk_app trans [p₁, p₂], return $ some pr
| none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not transitive"
end
end
protected meta def seq {α β : Type} (c₁ : conv (α → β)) (c₂ : conv α) : conv β :=
λ r e, do
⟨fn, e₁, pr₁⟩ ← c₁ r e,
⟨a, e₂, pr₂⟩ ← c₂ r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨fn a, e₂, pr⟩
protected meta def fail {α : Type} : conv α :=
λ r e, failed
protected meta def orelse {α : Type} (c₁ : conv α) (c₂ : conv α) : conv α :=
λ r e, c₁ r e <|> c₂ r e
protected meta def map {α β : Type} (f : α → β) (c : conv α) : conv β :=
λ r e, do
⟨a, e₁, pr⟩ ← c r e,
return ⟨f a, e₁, pr⟩
protected meta def bind {α β : Type} (c₁ : conv α) (c₂ : α → conv β) : conv β :=
λ r e, do
⟨a, e₁, pr₁⟩ ← c₁ r e,
⟨b, e₂, pr₂⟩ ← c₂ a r e₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨b, e₂, pr⟩
meta instance : monad conv :=
{ map := @conv.map,
ret := @conv.pure,
bind := @conv.bind }
meta instance : alternative conv :=
{ map := @conv.map,
pure := @conv.pure,
seq := @conv.seq,
failure := @conv.fail,
orelse := @conv.orelse }
meta def whnf_core (m : transparency) : conv unit :=
λ r e, do n ← tactic.whnf_core m e, return ⟨(), n, none⟩
meta def whnf : conv unit :=
conv.whnf_core reducible
meta def dsimp : conv unit :=
λ r e, do s ← simp_lemmas.mk_default, n ← s^.dsimplify e, return ⟨(), n, none⟩
meta def try (c : conv unit) : conv unit :=
c <|> return ()
meta def tryb (c : conv unit) : conv bool :=
(c >> return tt) <|> return ff
meta def trace {α : Type} [has_to_tactic_format α] (a : α) : conv unit :=
λ r e, tactic.trace a >> return ⟨(), e, none⟩
meta def trace_lhs : conv unit :=
lhs >>= trace
meta def apply_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
(new_e, pr) ← s^.rewrite prove r e,
return ⟨(), new_e, some pr⟩
meta def apply_lemmas (s : simp_lemmas) : conv unit :=
apply_lemmas_core s failed
/- αdapter for using iff-lemmas as eq-lemmas -/
meta def apply_propext_lemmas_core (s : simp_lemmas) (prove : tactic unit) : conv unit :=
λ r e, do
guard (r = `eq),
(new_e, pr) ← s^.rewrite prove `iff e,
new_pr ← mk_app `propext [pr],
return ⟨(), new_e, some new_pr⟩
meta def apply_propext_lemmas (s : simp_lemmas) : conv unit :=
apply_propext_lemmas_core s failed
private meta def mk_refl_proof (r : name) (e : expr) : tactic expr :=
do env ← get_env,
match (environment.refl_for env r) with
| (some refl) := do pr ← mk_app refl [e], return pr
| none := fail $ "converter failed, relation '" ++ r^.to_string ++ "' is not reflexive"
end
meta def to_tactic (c : conv unit) : name → expr → tactic (expr × expr) :=
λ r e, do
⟨u, e₁, o⟩ ← c r e,
match o with
| none := do p ← mk_refl_proof r e, return (e₁, p)
| some p := return (e₁, p)
end
meta def lift_tactic {α : Type} (t : tactic α) : conv α :=
λ r e, do a ← t, return ⟨a, e, none⟩
meta def apply_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_lemmas
meta def apply_propext_simp_set (attr_name : name) : conv unit :=
lift_tactic (get_user_simp_lemmas attr_name) >>= apply_propext_lemmas
meta def skip : conv unit :=
return ()
meta def repeat : conv unit → conv unit
| c r lhs :=
(do
⟨_, rhs₁, pr₁⟩ ← c r lhs,
guard (¬ lhs =ₐ rhs₁),
⟨_, rhs₂, pr₂⟩ ← repeat c r rhs₁,
pr ← join_proofs r pr₁ pr₂,
return ⟨(), rhs₂, pr⟩)
<|> return ⟨(), lhs, none⟩
meta def first {α : Type} : list (conv α) → conv α
| [] := conv.fail
| (c::cs) := c <|> first cs
meta def match_pattern (p : pattern) : conv unit :=
λ r e, tactic.match_pattern p e >> return ⟨(), e, none⟩
meta def mk_match_expr (p : pexpr) : tactic (conv unit) :=
do new_p ← pexpr_to_pattern p,
return (λ r e, tactic.match_pattern new_p e >> return ⟨(), e, none⟩)
meta def match_expr (p : pexpr) : conv unit :=
λ r e, do
new_p ← pexpr_to_pattern p,
tactic.match_pattern new_p e >> return ⟨(), e, none⟩
meta def funext (c : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.lam n bi d b) ← return lhs | failed,
aux_type ← return $ (expr.pi n bi d (expr.const `true [])),
(result, _) ← solve_aux aux_type $ do {
x ← intro1,
c_result ← c r (b^.instantiate_var x),
rhs ← return $ expr.lam n bi d (c_result^.rhs^.abstract x),
match c_result^.proof : _ → tactic (conv_result unit) with
| some pr := do
aux_pr ← return $ expr.lam n bi d (pr^.abstract x),
new_pr ← mk_app `funext [lhs, rhs, aux_pr],
return ⟨(), rhs, some new_pr⟩
| none := return ⟨(), rhs, none⟩
end },
return result
meta def congr_core (c_f c_a : conv unit) : conv unit :=
λ r lhs, do
guard (r = `eq),
(expr.app f a) ← return lhs | failed,
f_type ← infer_type f >>= tactic.whnf,
guard (f_type^.is_arrow),
⟨(), new_f, of⟩ ← try c_f r f,
⟨(), new_a, oa⟩ ← try c_a r a,
rhs ← return $ new_f new_a,
match of, oa with
| none, none :=
return ⟨(), rhs, none⟩
| none, some pr_a := do
pr ← mk_app `congr_arg [a, new_a, f, pr_a],
return ⟨(), new_f new_a, some pr⟩
| some pr_f, none := do
pr ← mk_app `congr_fun [f, new_f, pr_f, a],
return ⟨(), rhs, some pr⟩
| some pr_f, some pr_a := do
pr ← mk_app `congr [f, new_f, a, new_a, pr_f, pr_a],
return ⟨(), rhs, some pr⟩
end
meta def congr (c : conv unit) : conv unit :=
congr_core c c
meta def bottom_up (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, failed)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
r e,
return ⟨(), new_e, some pr⟩
meta def top_down (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e,
(do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff))
<|>
return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def find_pattern (pat : pattern) (c : conv unit) : conv unit :=
λ r e, do
s ← simp_lemmas.mk_default,
(a, new_e, pr) ←
ext_simplify_core () {} s
(λ u, return u)
(λ a s r p e, do
matched ← (tactic.match_pattern pat e >> return tt) <|> return ff,
if matched
then do ⟨u, new_e, pr⟩ ← c r e, return ((), new_e, pr, ff)
else return ((), e, none, tt))
(λ a s r p e, failed)
r e,
return ⟨(), new_e, some pr⟩
meta def findp : pexpr → conv unit → conv unit :=
λ p c r e, do
pat ← pexpr_to_pattern p,
find_pattern pat c r e
meta def conversion (c : conv unit) : tactic unit :=
do (r, lhs, rhs) ← (target_lhs_rhs <|> fail "conversion failed, target is not of the form 'lhs R rhs'"),
(new_lhs, pr) ← to_tactic c r lhs,
(unify new_lhs rhs <|>
do new_lhs_fmt ← pp new_lhs,
rhs_fmt ← pp rhs,
fail (to_fmt "conversion failed, expected" ++
rhs_fmt^.indent 4 ++ format.line ++ "provided" ++
new_lhs_fmt^.indent 4)),
exact pr
end conv
|
062da5acd8d596f7e554db020e47dc1175c2bd3e | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/geometry/manifold/complex.lean | 506672ce6f86f30c04ccb408111cdc484d41932a | [
"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 | 6,006 | lean | /-
Copyright (c) 2022 Heather Macbeth. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Heather Macbeth
-/
import analysis.complex.abs_max
import analysis.locally_convex.with_seminorms
import geometry.manifold.mfderiv
import topology.locally_constant.basic
/-! # Holomorphic functions on complex manifolds
Thanks to the rigidity of complex-differentiability compared to real-differentiability, there are
many results about complex manifolds with no analogue for manifolds over a general normed field. For
now, this file contains just two (closely related) such results:
## Main results
* `mdifferentiable.is_locally_constant`: A complex-differentiable function on a compact complex
manifold is locally constant.
* `mdifferentiable.exists_eq_const_of_compact_space`: A complex-differentiable function on a compact
preconnected complex manifold is constant.
## TODO
There is a whole theory to develop here. Maybe a next step would be to develop a theory of
holomorphic vector/line bundles, including:
* the finite-dimensionality of the space of sections of a holomorphic vector bundle
* Siegel's theorem: for any `n + 1` formal ratios `g 0 / h 0`, `g 1 / h 1`, .... `g n / h n` of
sections of a fixed line bundle `L` over a complex `n`-manifold, there exists a polynomial
relationship `P (g 0 / h 0, g 1 / h 1, .... g n / h n) = 0`
Another direction would be to develop the relationship with sheaf theory, building the sheaves of
holomorphic and meromorphic functions on a complex manifold and proving algebraic results about the
stalks, such as the Weierstrass preparation theorem.
-/
open_locale manifold topological_space
open complex
namespace mdifferentiable
variables {E : Type*} [normed_add_comm_group E] [normed_space ℂ E]
variables {F : Type*} [normed_add_comm_group F] [normed_space ℂ F] [strict_convex_space ℝ F]
variables {M : Type*} [topological_space M] [compact_space M] [charted_space E M]
[smooth_manifold_with_corners 𝓘(ℂ, E) M]
/-- A holomorphic function on a compact complex manifold is locally constant. -/
protected lemma is_locally_constant {f : M → F} (hf : mdifferentiable 𝓘(ℂ, E) 𝓘(ℂ, F) f) :
is_locally_constant f :=
begin
haveI : locally_connected_space M := charted_space.locally_connected_space E M,
apply is_locally_constant.of_constant_on_preconnected_clopens,
intros s hs₂ hs₃ a ha b hb,
have hs₁ : is_compact s := hs₃.2.is_compact,
-- for an empty set this fact is trivial
rcases s.eq_empty_or_nonempty with rfl | hs',
{ exact false.rec _ ha },
-- otherwise, let `p₀` be a point where the value of `f` has maximal norm
obtain ⟨p₀, hp₀s, hp₀⟩ := hs₁.exists_forall_ge hs' hf.continuous.norm.continuous_on,
-- we will show `f` agrees everywhere with `f p₀`
suffices : s ⊆ {r : M | f r = f p₀} ∩ s,
{ exact (this hb).1.trans (this ha).1.symm }, clear ha hb a b,
refine hs₂.subset_clopen _ ⟨p₀, hp₀s, ⟨rfl, hp₀s⟩⟩,
-- closedness of the set of points sent to `f p₀`
refine ⟨_, (is_closed_singleton.preimage hf.continuous).inter hs₃.2⟩,
-- we will show this set is open by showing it is a neighbourhood of each of its members
rw is_open_iff_mem_nhds,
rintros p ⟨hp : f p = _, hps⟩, -- let `p` be in this set
have hps' : s ∈ 𝓝 p := hs₃.1.mem_nhds hps,
have key₁ : (chart_at E p).symm ⁻¹' s ∈ 𝓝 (chart_at E p p),
{ rw [← filter.mem_map, (chart_at E p).symm_map_nhds_eq (mem_chart_source E p)],
exact hps' },
have key₂ : (chart_at E p).target ∈ 𝓝 (chart_at E p p) :=
(local_homeomorph.open_target _).mem_nhds (mem_chart_target E p),
-- `f` pulled back by the chart at `p` is differentiable around `chart_at E p p`
have hf' : ∀ᶠ (z : E) in 𝓝 (chart_at E p p), differentiable_at ℂ (f ∘ (chart_at E p).symm) z,
{ refine filter.eventually_of_mem key₂ (λ z hz, _),
have H₁ : (chart_at E p).symm z ∈ (chart_at E p).source := (chart_at E p).map_target hz,
have H₂ : f ((chart_at E p).symm z) ∈ (chart_at F (0:F)).source := trivial,
have H := (mdifferentiable_at_iff_of_mem_source H₁ H₂).mp (hf ((chart_at E p).symm z)),
simp only [differentiable_within_at_univ] with mfld_simps at H,
simpa [local_homeomorph.right_inv _ hz] using H.2, },
-- `f` pulled back by the chart at `p` has a local max at `chart_at E p p`
have hf'' : is_local_max (norm ∘ f ∘ (chart_at E p).symm) (chart_at E p p),
{ refine filter.eventually_of_mem key₁ (λ z hz, _),
refine (hp₀ ((chart_at E p).symm z) hz).trans (_ : ∥f p₀∥ ≤ ∥f _∥),
rw [← hp, local_homeomorph.left_inv _ (mem_chart_source E p)] },
-- so by the maximum principle `f` is equal to `f p` near `p`
obtain ⟨U, hU, hUf⟩ := (complex.eventually_eq_of_is_local_max_norm hf' hf'').exists_mem,
have H₁ : (chart_at E p) ⁻¹' U ∈ 𝓝 p := (chart_at E p).continuous_at (mem_chart_source E p) hU,
have H₂ : (chart_at E p).source ∈ 𝓝 p :=
(local_homeomorph.open_source _).mem_nhds (mem_chart_source E p),
apply filter.mem_of_superset (filter.inter_mem hps' (filter.inter_mem H₁ H₂)),
rintros q ⟨hqs, hq : chart_at E p q ∈ _, hq'⟩,
refine ⟨_, hqs⟩,
simpa [local_homeomorph.left_inv _ hq', hp, -norm_eq_abs] using hUf (chart_at E p q) hq,
end
/-- A holomorphic function on a compact connected complex manifold is constant. -/
lemma apply_eq_of_compact_space [preconnected_space M]
{f : M → F} (hf : mdifferentiable 𝓘(ℂ, E) 𝓘(ℂ, F) f) (a b : M) :
f a = f b :=
hf.is_locally_constant.apply_eq_of_preconnected_space _ _
/-- A holomorphic function on a compact connected complex manifold is the constant function `f ≡ v`,
for some value `v`. -/
lemma exists_eq_const_of_compact_space [preconnected_space M]
{f : M → F} (hf : mdifferentiable 𝓘(ℂ, E) 𝓘(ℂ, F) f) :
∃ v : F, f = function.const M v :=
hf.is_locally_constant.exists_eq_const
end mdifferentiable
|
33f901537ca196caae6a8da99011360c9228e9d6 | 367134ba5a65885e863bdc4507601606690974c1 | /src/order/galois_connection.lean | 8927c76e47835dd88095ec64705d678544c1a9ba | [
"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 | 25,266 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import order.complete_lattice
import order.rel_iso
/-!
# Galois connections, insertions and coinsertions
Galois connections are order theoretic adjoints, i.e. a pair of functions `u` and `l`,
such that `∀a b, l a ≤ b ↔ a ≤ u b`.
## Main definitions
* `galois_connection`: A Galois connection is a pair of functions `l` and `u` satisfying
`l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory,
but do not depend on the category theory library in mathlib.
* `galois_insertion`: A Galois insertion is a Galois connection where `l ∘ u = id`
* `galois_coinsertion`: A Galois coinsertion is a Galois connection where `u ∘ l = id`
## Implementation details
Galois insertions can be used to lift order structures from one type to another.
For example if `α` is a complete lattice, and `l : α → β`, and `u : β → α` form
a Galois insertion, then `β` is also a complete lattice. `l` is the lower adjoint and
`u` is the upper adjoint.
An example of this is the Galois insertion is in group thery. If `G` is a topological space,
then there is a Galois insertion between the set of subsets of `G`, `set G`, and the
set of subgroups of `G`, `subgroup G`. The left adjoint is `subgroup.closure`,
taking the `subgroup` generated by a `set`, The right adjoint is the coercion from `subgroup G` to
`set G`, taking the underlying set of a subgroup.
Naively lifting a lattice structure along this Galois insertion would mean that the definition
of `inf` on subgroups would be `subgroup.closure (↑S ∩ ↑T)`. This is an undesirable definition
because the intersection of subgroups is already a subgroup, so there is no need to take the
closure. For this reason a `choice` function is added as a field to the `galois_insertion`
structure. It has type `Π S : set G, ↑(closure S) ≤ S → subgroup G`. When `↑(closure S) ≤ S`, then
`S` is already a subgroup, so this function can be defined using `subgroup.mk` and not `closure`.
This means the infimum of subgroups will be defined to be the intersection of sets, paired
with a proof that intersection of subgroups is a subgroup, rather than the closure of the
intersection.
-/
open function set
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a a₁ a₂ : α} {b b₁ b₂ : β}
/-- A Galois connection is a pair of functions `l` and `u` satisfying
`l a ≤ b ↔ a ≤ u b`. They are special cases of adjoint functors in category theory,
but do not depend on the category theory library in mathlib. -/
def galois_connection [preorder α] [preorder β] (l : α → β) (u : β → α) := ∀a b, l a ≤ b ↔ a ≤ u b
/-- Makes a Galois connection from an order-preserving bijection. -/
theorem order_iso.to_galois_connection [preorder α] [preorder β] (oi : α ≃o β) :
galois_connection oi oi.symm :=
λ b g, oi.rel_symm_apply.symm
namespace galois_connection
section
variables [preorder α] [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u)
lemma monotone_intro (hu : monotone u) (hl : monotone l)
(hul : ∀ a, a ≤ u (l a)) (hlu : ∀ a, l (u a) ≤ a) : galois_connection l u :=
assume a b, ⟨assume h, le_trans (hul _) (hu h), assume h, le_trans (hl h) (hlu _)⟩
include gc
lemma l_le {a : α} {b : β} : a ≤ u b → l a ≤ b :=
(gc _ _).mpr
lemma le_u {a : α} {b : β} : l a ≤ b → a ≤ u b :=
(gc _ _).mp
lemma le_u_l (a) : a ≤ u (l a) :=
gc.le_u $ le_refl _
lemma l_u_le (a) : l (u a) ≤ a :=
gc.l_le $ le_refl _
lemma monotone_u : monotone u :=
assume a b H, gc.le_u (le_trans (gc.l_u_le a) H)
lemma monotone_l : monotone l :=
assume a b H, gc.l_le (le_trans H (gc.le_u_l b))
lemma upper_bounds_l_image_subset {s : set α} : upper_bounds (l '' s) ⊆ u ⁻¹' upper_bounds s :=
assume b hb c, assume : c ∈ s, gc.le_u (hb (mem_image_of_mem _ ‹c ∈ s›))
lemma lower_bounds_u_image_subset {s : set β} : lower_bounds (u '' s) ⊆ l ⁻¹' lower_bounds s :=
assume a ha c, assume : c ∈ s, gc.l_le (ha (mem_image_of_mem _ ‹c ∈ s›))
lemma is_lub_l_image {s : set α} {a : α} (h : is_lub s a) : is_lub (l '' s) (l a) :=
⟨gc.monotone_l.mem_upper_bounds_image $ and.elim_left ‹is_lub s a›,
assume b hb, gc.l_le $ and.elim_right ‹is_lub s a› $ gc.upper_bounds_l_image_subset hb⟩
lemma is_glb_u_image {s : set β} {b : β} (h : is_glb s b) : is_glb (u '' s) (u b) :=
⟨gc.monotone_u.mem_lower_bounds_image $ and.elim_left ‹is_glb s b›,
assume a ha, gc.le_u $ and.elim_right ‹is_glb s b› $ gc.lower_bounds_u_image_subset ha⟩
lemma is_glb_l {a : α} : is_glb { b | a ≤ u b } (l a) :=
⟨assume b, gc.l_le, assume b h, h $ gc.le_u_l _⟩
lemma is_lub_u {b : β} : is_lub { a | l a ≤ b } (u b) :=
⟨assume b, gc.le_u, assume b h, h $ gc.l_u_le _⟩
end
section partial_order
variables [partial_order α] [partial_order β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_l_u_eq_u : u ∘ l ∘ u = u :=
funext (assume x, le_antisymm (gc.monotone_u (gc.l_u_le _)) (gc.le_u_l _))
lemma l_u_l_eq_l : l ∘ u ∘ l = l :=
funext (assume x, le_antisymm (gc.l_u_le _) (gc.monotone_l (gc.le_u_l _)))
lemma l_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u')
(hu : ∀ b, u b = u' b) {a : α} : l a = l' a :=
le_antisymm (gc.l_le $ (hu (l' a)).symm ▸ gc'.le_u_l _)
(gc'.l_le $ hu (l a) ▸ gc.le_u_l _)
lemma u_unique {l' : α → β} {u' : β → α} (gc' : galois_connection l' u')
(hl : ∀ a, l a = l' a) {b : β} : u b = u' b :=
le_antisymm (gc'.le_u $ hl (u b) ▸ gc.l_u_le _)
(gc.le_u $ (hl (u' b)).symm ▸ gc'.l_u_le _)
end partial_order
section order_top
variables [order_top α] [order_top β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_top : u ⊤ = ⊤ :=
(gc.is_glb_u_image is_glb_empty).unique $ by simp only [is_glb_empty, image_empty]
end order_top
section order_bot
variables [order_bot α] [order_bot β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_bot : l ⊥ = ⊥ :=
(gc.is_lub_l_image is_lub_empty).unique $ by simp only [is_lub_empty, image_empty]
end order_bot
section semilattice_sup
variables [semilattice_sup α] [semilattice_sup β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_sup : l (a₁ ⊔ a₂) = l a₁ ⊔ l a₂ :=
(gc.is_lub_l_image is_lub_pair).unique $ by simp only [image_pair, is_lub_pair]
end semilattice_sup
section semilattice_inf
variables [semilattice_inf α] [semilattice_inf β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma u_inf : u (b₁ ⊓ b₂) = u b₁ ⊓ u b₂ :=
(gc.is_glb_u_image is_glb_pair).unique $ by simp only [image_pair, is_glb_pair]
end semilattice_inf
section complete_lattice
variables [complete_lattice α] [complete_lattice β] {l : α → β} {u : β → α} (gc : galois_connection l u)
include gc
lemma l_supr {f : ι → α} : l (supr f) = (⨆i, l (f i)) :=
eq.symm $ is_lub.supr_eq $ show is_lub (range (l ∘ f)) (l (supr f)),
by rw [range_comp, ← Sup_range]; exact gc.is_lub_l_image (is_lub_Sup _)
lemma u_infi {f : ι → β} : u (infi f) = (⨅i, u (f i)) :=
eq.symm $ is_glb.infi_eq $ show is_glb (range (u ∘ f)) (u (infi f)),
by rw [range_comp, ← Inf_range]; exact gc.is_glb_u_image (is_glb_Inf _)
lemma l_Sup {s : set α} : l (Sup s) = (⨆a∈s, l a) :=
by simp only [Sup_eq_supr, gc.l_supr]
lemma u_Inf {s : set β} : u (Inf s) = (⨅a∈s, u a) :=
by simp only [Inf_eq_infi, gc.u_infi]
end complete_lattice
/- Constructing Galois connections -/
section constructions
protected lemma id [pα : preorder α] : @galois_connection α α pα pα id id :=
assume a b, iff.intro (λx, x) (λx, x)
protected lemma compose [preorder α] [preorder β] [preorder γ]
(l1 : α → β) (u1 : β → α) (l2 : β → γ) (u2 : γ → β)
(gc1 : galois_connection l1 u1) (gc2 : galois_connection l2 u2) :
galois_connection (l2 ∘ l1) (u1 ∘ u2) :=
by intros a b; rw [gc2, gc1]
protected lemma dual [pα : preorder α] [pβ : preorder β]
{l : α → β} {u : β → α} (gc : galois_connection l u) :
@galois_connection (order_dual β) (order_dual α) _ _ u l :=
assume a b, (gc _ _).symm
protected lemma dfun {ι : Type u} {α : ι → Type v} {β : ι → Type w}
[∀i, preorder (α i)] [∀i, preorder (β i)]
(l : Πi, α i → β i) (u : Πi, β i → α i) (gc : ∀i, galois_connection (l i) (u i)) :
@galois_connection (Π i, α i) (Π i, β i) _ _ (λa i, l i (a i)) (λb i, u i (b i)) :=
assume a b, forall_congr $ assume i, gc i (a i) (b i)
end constructions
end galois_connection
namespace nat
lemma galois_connection_mul_div {k : ℕ} (h : 0 < k) : galois_connection (λn, n * k) (λn, n / k) :=
assume x y, (le_div_iff_mul_le x y h).symm
end nat
/-- A Galois insertion is a Galois connection where `l ∘ u = id`. It also contains a constructive
choice function, to give better definitional equalities when lifting order structures. Dual
to `galois_coinsertion` -/
@[nolint has_inhabited_instance]
structure galois_insertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) :=
(choice : Πx:α, u (l x) ≤ x → β)
(gc : galois_connection l u)
(le_l_u : ∀x, x ≤ l (u x))
(choice_eq : ∀a h, choice a h = l a)
/-- A constructor for a Galois insertion with the trivial `choice` function. -/
def galois_insertion.monotone_intro {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α}
(hu : monotone u) (hl : monotone l) (hul : ∀ a, a ≤ u (l a)) (hlu : ∀ b, l (u b) = b) :
galois_insertion l u :=
{ choice := λ x _, l x,
gc := galois_connection.monotone_intro hu hl hul (λ b, le_of_eq (hlu b)),
le_l_u := λ b, le_of_eq $ (hlu b).symm,
choice_eq := λ _ _, rfl }
/-- Makes a Galois insertion from an order-preserving bijection. -/
protected def rel_iso.to_galois_insertion [preorder α] [preorder β] (oi : α ≃o β) :
@galois_insertion α β _ _ (oi) (oi.symm) :=
{ choice := λ b h, oi b,
gc := oi.to_galois_connection,
le_l_u := λ g, le_of_eq (oi.right_inv g).symm,
choice_eq := λ b h, rfl }
/-- Make a `galois_insertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/
def galois_connection.to_galois_insertion {α β : Type*} [preorder α] [preorder β]
{l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ b, b ≤ l (u b)) :
galois_insertion l u :=
{ choice := λ x _, l x,
gc := gc,
le_l_u := h,
choice_eq := λ _ _, rfl }
/-- Lift the bottom along a Galois connection -/
def galois_connection.lift_order_bot {α β : Type*} [order_bot α] [partial_order β]
{l : α → β} {u : β → α} (gc : galois_connection l u) :
order_bot β :=
{ bot := l ⊥,
bot_le := assume b, gc.l_le $ bot_le,
.. ‹partial_order β› }
namespace galois_insertion
variables {l : α → β} {u : β → α}
lemma l_u_eq [preorder α] [partial_order β] (gi : galois_insertion l u) (b : β) :
l (u b) = b :=
le_antisymm (gi.gc.l_u_le _) (gi.le_l_u _)
lemma l_surjective [preorder α] [partial_order β] (gi : galois_insertion l u) :
surjective l :=
assume b, ⟨u b, gi.l_u_eq b⟩
lemma u_injective [preorder α] [partial_order β] (gi : galois_insertion l u) :
injective u :=
assume a b h,
calc a = l (u a) : (gi.l_u_eq a).symm
... = l (u b) : congr_arg l h
... = b : gi.l_u_eq b
lemma l_sup_u [semilattice_sup α] [semilattice_sup β] (gi : galois_insertion l u) (a b : β) :
l (u a ⊔ u b) = a ⊔ b :=
calc l (u a ⊔ u b) = l (u a) ⊔ l (u b) : gi.gc.l_sup
... = a ⊔ b : by simp only [gi.l_u_eq]
lemma l_supr_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u)
{ι : Sort x} (f : ι → β) :
l (⨆ i, u (f i)) = ⨆ i, (f i) :=
calc l (⨆ (i : ι), u (f i)) = ⨆ (i : ι), l (u (f i)) : gi.gc.l_supr
... = ⨆ (i : ι), f i : congr_arg _ $ funext $ λ i, gi.l_u_eq (f i)
lemma l_supr_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u)
{ι : Sort x} (f : ι → α) (hf : ∀ i, u (l (f i)) = f i) :
l (⨆ i, (f i)) = ⨆ i, l (f i) :=
calc l (⨆ (i : ι), (f i)) = l ⨆ (i : ι), (u (l (f i))) : by simp [hf]
... = ⨆ (i : ι), l (f i) : gi.l_supr_u _
lemma l_inf_u [semilattice_inf α] [semilattice_inf β] (gi : galois_insertion l u) (a b : β) :
l (u a ⊓ u b) = a ⊓ b :=
calc l (u a ⊓ u b) = l (u (a ⊓ b)) : congr_arg l gi.gc.u_inf.symm
... = a ⊓ b : by simp only [gi.l_u_eq]
lemma l_infi_u [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u)
{ι : Sort x} (f : ι → β) :
l (⨅ i, u (f i)) = ⨅ i, (f i) :=
calc l (⨅ (i : ι), u (f i)) = l (u (⨅ (i : ι), (f i))) : congr_arg l gi.gc.u_infi.symm
... = ⨅ (i : ι), f i : gi.l_u_eq _
lemma l_infi_of_ul_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_insertion l u)
{ι : Sort x} (f : ι → α) (hf : ∀ i, u (l (f i)) = f i) :
l (⨅ i, (f i)) = ⨅ i, l (f i) :=
calc l (⨅ i, (f i)) = l ⨅ (i : ι), (u (l (f i))) : by simp [hf]
... = ⨅ i, l (f i) : gi.l_infi_u _
lemma u_le_u_iff [preorder α] [preorder β] (gi : galois_insertion l u) {a b} :
u a ≤ u b ↔ a ≤ b :=
⟨λ h, le_trans (gi.le_l_u _) (gi.gc.l_le h),
λ h, gi.gc.monotone_u h⟩
lemma strict_mono_u [preorder α] [partial_order β] (gi : galois_insertion l u) : strict_mono u :=
strict_mono_of_le_iff_le $ λ _ _, gi.u_le_u_iff.symm
section lift
variables [partial_order β]
/-- Lift the suprema along a Galois insertion -/
def lift_semilattice_sup [semilattice_sup α] (gi : galois_insertion l u) : semilattice_sup β :=
{ sup := λa b, l (u a ⊔ u b),
le_sup_left := assume a b, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_sup_left,
le_sup_right := assume a b, le_trans (gi.le_l_u b) $ gi.gc.monotone_l $ le_sup_right,
sup_le := assume a b c hac hbc, gi.gc.l_le $ sup_le (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc),
.. ‹partial_order β› }
/-- Lift the infima along a Galois insertion -/
def lift_semilattice_inf [semilattice_inf α] (gi : galois_insertion l u) : semilattice_inf β :=
{ inf := λa b, gi.choice (u a ⊓ u b) $
(le_inf (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_left) (gi.gc.monotone_u $ gi.gc.l_le $ inf_le_right)),
inf_le_left := by simp only [gi.choice_eq]; exact assume a b, gi.gc.l_le inf_le_left,
inf_le_right := by simp only [gi.choice_eq]; exact assume a b, gi.gc.l_le inf_le_right,
le_inf := by simp only [gi.choice_eq]; exact assume a b c hac hbc,
le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_inf (gi.gc.monotone_u hac) (gi.gc.monotone_u hbc),
.. ‹partial_order β› }
/-- Lift the suprema and infima along a Galois insertion -/
def lift_lattice [lattice α] (gi : galois_insertion l u) : lattice β :=
{ .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf }
/-- Lift the top along a Galois insertion -/
def lift_order_top [order_top α] (gi : galois_insertion l u) : order_top β :=
{ top := gi.choice ⊤ $ le_top,
le_top := by simp only [gi.choice_eq]; exact assume b, le_trans (gi.le_l_u b) (gi.gc.monotone_l le_top),
.. ‹partial_order β› }
/-- Lift the top, bottom, suprema, and infima along a Galois insertion -/
def lift_bounded_lattice [bounded_lattice α] (gi : galois_insertion l u) : bounded_lattice β :=
{ .. gi.lift_lattice, .. gi.lift_order_top, .. gi.gc.lift_order_bot }
/-- Lift all suprema and infima along a Galois insertion -/
def lift_complete_lattice [complete_lattice α] (gi : galois_insertion l u) : complete_lattice β :=
{ Sup := λs, l (⨆ b∈s, u b),
Sup_le := assume s a hs, gi.gc.l_le $ supr_le $ assume b, supr_le $ assume hb, gi.gc.monotone_u $ hs _ hb,
le_Sup := assume s a ha, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_supr_of_le a $ le_supr_of_le ha $ le_refl _,
Inf := λs, gi.choice (⨅ b∈s, u b) $ le_infi $ assume b, le_infi $ assume hb,
gi.gc.monotone_u $ gi.gc.l_le $ infi_le_of_le b $ infi_le_of_le hb $ le_refl _,
Inf_le := by simp only [gi.choice_eq]; exact
assume s a ha, gi.gc.l_le $ infi_le_of_le a $ infi_le_of_le ha $ le_refl _,
le_Inf := by simp only [gi.choice_eq]; exact
assume s a hs, le_trans (gi.le_l_u a) $ gi.gc.monotone_l $ le_infi $ assume b,
show u a ≤ ⨅ (H : b ∈ s), u b, from le_infi $ assume hb, gi.gc.monotone_u $ hs _ hb,
.. gi.lift_bounded_lattice }
end lift
end galois_insertion
/-- A Galois coinsertion is a Galois connection where `u ∘ l = id`. It also contains a constructive
choice function, to give better definitional equalities when lifting order structures. Dual to
`galois_insertion` -/
@[nolint has_inhabited_instance]
structure galois_coinsertion {α β : Type*} [preorder α] [preorder β] (l : α → β) (u : β → α) :=
(choice : Πx:β, x ≤ l (u x) → α)
(gc : galois_connection l u)
(u_l_le : ∀x, u (l x) ≤ x)
(choice_eq : ∀a h, choice a h = u a)
/-- Make a `galois_insertion u l` in the `order_dual`, from a `galois_coinsertion l u` -/
def galois_coinsertion.dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} :
galois_coinsertion l u → @galois_insertion (order_dual β) (order_dual α) _ _ u l :=
λ x, ⟨x.1, x.2.dual, x.3, x.4⟩
/-- Make a `galois_coinsertion u l` in the `order_dual`, from a `galois_insertion l u` -/
def galois_insertion.dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} :
galois_insertion l u → @galois_coinsertion (order_dual β) (order_dual α) _ _ u l :=
λ x, ⟨x.1, x.2.dual, x.3, x.4⟩
/-- Make a `galois_coinsertion l u` from a `galois_insertion l u` in the `order_dual` -/
def galois_coinsertion.of_dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} :
@galois_insertion (order_dual β) (order_dual α) _ _ u l → galois_coinsertion l u :=
λ x, ⟨x.1, x.2.dual, x.3, x.4⟩
/-- Make a `galois_insertion l u` from a `galois_coinsertion l u` in the `order_dual` -/
def galois_insertion.of_dual {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α} :
@galois_coinsertion (order_dual β) (order_dual α) _ _ u l → galois_insertion l u :=
λ x, ⟨x.1, x.2.dual, x.3, x.4⟩
/-- Makes a Galois coinsertion from an order-preserving bijection. -/
protected def rel_iso.to_galois_coinsertion [preorder α] [preorder β] (oi : α ≃o β) :
@galois_coinsertion α β _ _ (oi) (oi.symm) :=
{ choice := λ b h, oi.symm b,
gc := oi.to_galois_connection,
u_l_le := λ g, le_of_eq (oi.left_inv g),
choice_eq := λ b h, rfl }
/-- A constructor for a Galois coinsertion with the trivial `choice` function. -/
def galois_coinsertion.monotone_intro {α β : Type*} [preorder α] [preorder β] {l : α → β} {u : β → α}
(hu : monotone u) (hl : monotone l) (hlu : ∀ b, l (u b) ≤ b) (hul : ∀ a, u (l a) = a) :
galois_coinsertion l u :=
galois_coinsertion.of_dual (galois_insertion.monotone_intro hl.order_dual hu.order_dual hlu hul)
/-- Make a `galois_coinsertion l u` from a `galois_connection l u` such that `∀ b, b ≤ l (u b)` -/
def galois_connection.to_galois_coinsertion {α β : Type*} [preorder α] [preorder β]
{l : α → β} {u : β → α} (gc : galois_connection l u) (h : ∀ a, u (l a) ≤ a) :
galois_coinsertion l u :=
{ choice := λ x _, u x,
gc := gc,
u_l_le := h,
choice_eq := λ _ _, rfl }
/-- Lift the top along a Galois connection -/
def galois_connection.lift_order_top {α β : Type*} [partial_order α] [order_top β]
{l : α → β} {u : β → α} (gc : galois_connection l u) :
order_top α :=
{ top := u ⊤,
le_top := assume b, gc.le_u $ le_top,
.. ‹partial_order α› }
namespace galois_coinsertion
variables {l : α → β} {u : β → α}
lemma u_l_eq [partial_order α] [preorder β] (gi : galois_coinsertion l u) (a : α) :
u (l a) = a :=
gi.dual.l_u_eq a
lemma u_surjective [partial_order α] [preorder β] (gi : galois_coinsertion l u) :
surjective u :=
gi.dual.l_surjective
lemma l_injective [partial_order α] [preorder β] (gi : galois_coinsertion l u) :
injective l :=
gi.dual.u_injective
lemma u_inf_l [semilattice_inf α] [semilattice_inf β] (gi : galois_coinsertion l u) (a b : α) :
u (l a ⊓ l b) = a ⊓ b :=
gi.dual.l_sup_u a b
lemma u_infi_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u)
{ι : Sort x} (f : ι → α) :
u (⨅ i, l (f i)) = ⨅ i, (f i) :=
gi.dual.l_supr_u _
lemma u_infi_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u)
{ι : Sort x} (f : ι → β) (hf : ∀ i, l (u (f i)) = f i) :
u (⨅ i, (f i)) = ⨅ i, u (f i) :=
gi.dual.l_supr_of_ul_eq_self _ hf
lemma u_sup_l [semilattice_sup α] [semilattice_sup β] (gi : galois_coinsertion l u) (a b : α) :
u (l a ⊔ l b) = a ⊔ b :=
gi.dual.l_inf_u _ _
lemma u_supr_l [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u)
{ι : Sort x} (f : ι → α) :
u (⨆ i, l (f i)) = ⨆ i, (f i) :=
gi.dual.l_infi_u _
lemma u_supr_of_lu_eq_self [complete_lattice α] [complete_lattice β] (gi : galois_coinsertion l u)
{ι : Sort x} (f : ι → β) (hf : ∀ i, l (u (f i)) = f i) :
u (⨆ i, (f i)) = ⨆ i, u (f i) :=
gi.dual.l_infi_of_ul_eq_self _ hf
lemma l_le_l_iff [preorder α] [preorder β] (gi : galois_coinsertion l u) {a b} :
l a ≤ l b ↔ a ≤ b :=
gi.dual.u_le_u_iff
lemma strict_mono_l [partial_order α] [preorder β] (gi : galois_coinsertion l u) : strict_mono l :=
λ a b h, gi.dual.strict_mono_u h
section lift
variables [partial_order α]
/-- Lift the infima along a Galois coinsertion -/
def lift_semilattice_inf [semilattice_inf β] (gi : galois_coinsertion l u) : semilattice_inf α :=
{ inf := λa b, u (l a ⊓ l b),
inf_le_left := assume a b, le_trans (gi.gc.monotone_u $ inf_le_left) (gi.u_l_le a),
inf_le_right := assume a b, le_trans (gi.gc.monotone_u $ inf_le_right) (gi.u_l_le b),
le_inf := assume a b c hac hbc, gi.gc.le_u $ le_inf (gi.gc.monotone_l hac) (gi.gc.monotone_l hbc),
.. ‹partial_order α› }
/-- Lift the suprema along a Galois coinsertion -/
def lift_semilattice_sup [semilattice_sup β] (gi : galois_coinsertion l u) : semilattice_sup α :=
{ sup := λa b, gi.choice (l a ⊔ l b) $
(sup_le (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_left) (gi.gc.monotone_l $ gi.gc.le_u $ le_sup_right)),
le_sup_left := by simp only [gi.choice_eq]; exact assume a b, gi.gc.le_u le_sup_left,
le_sup_right := by simp only [gi.choice_eq]; exact assume a b, gi.gc.le_u le_sup_right,
sup_le := by simp only [gi.choice_eq]; exact assume a b c hac hbc,
le_trans (gi.gc.monotone_u $ sup_le (gi.gc.monotone_l hac) (gi.gc.monotone_l hbc)) (gi.u_l_le c),
.. ‹partial_order α› }
/-- Lift the suprema and infima along a Galois coinsertion -/
def lift_lattice [lattice β] (gi : galois_coinsertion l u) : lattice α :=
{ .. gi.lift_semilattice_sup, .. gi.lift_semilattice_inf }
/-- Lift the bot along a Galois coinsertion -/
def lift_order_bot [order_bot β] (gi : galois_coinsertion l u) : order_bot α :=
{ bot := gi.choice ⊥ $ bot_le,
bot_le := by simp only [gi.choice_eq]; exact assume b, le_trans (gi.gc.monotone_u bot_le) (gi.u_l_le b),
.. ‹partial_order α› }
/-- Lift the top, bottom, suprema, and infima along a Galois coinsertion -/
def lift_bounded_lattice [bounded_lattice β] (gi : galois_coinsertion l u) : bounded_lattice α :=
{ .. gi.lift_lattice, .. gi.lift_order_bot, .. gi.gc.lift_order_top }
/-- Lift all suprema and infima along a Galois coinsertion -/
def lift_complete_lattice [complete_lattice β] (gi : galois_coinsertion l u) : complete_lattice α :=
{ Inf := λs, u (⨅ a∈s, l a),
le_Inf := assume s a hs, gi.gc.le_u $ le_infi $ assume b, le_infi $ assume hb, gi.gc.monotone_l $ hs _ hb,
Inf_le := assume s a ha, le_trans (gi.gc.monotone_u $ infi_le_of_le a $
infi_le_of_le ha $ le_refl _) (gi.u_l_le a),
Sup := λs, gi.choice (⨆ a∈s, l a) $ supr_le $ assume b, supr_le $ assume hb,
gi.gc.monotone_l $ gi.gc.le_u $ le_supr_of_le b $ le_supr_of_le hb $ le_refl _,
le_Sup := by simp only [gi.choice_eq]; exact
assume s a ha, gi.gc.le_u $ le_supr_of_le a $ le_supr_of_le ha $ le_refl _,
Sup_le := by simp only [gi.choice_eq]; exact
assume s a hs, le_trans (gi.gc.monotone_u $ supr_le $ assume b,
show (⨆ (hb : b ∈ s), l b) ≤ l a, from supr_le $ assume hb, gi.gc.monotone_l $ hs b hb)
(gi.u_l_le a),
.. gi.lift_bounded_lattice }
end lift
end galois_coinsertion
/-- If `α` is a partial order with bottom element (e.g., `ℕ`, `ℝ≥0`), then
`λ o : with_bot α, o.get_or_else ⊥` and coercion form a Galois insertion. -/
def with_bot.gi_get_or_else_bot [order_bot α] :
galois_insertion (λ o : with_bot α, o.get_or_else ⊥) coe :=
{ gc := λ a b, with_bot.get_or_else_bot_le_iff,
le_l_u := λ a, le_rfl,
choice := λ o ho, _,
choice_eq := λ _ _, rfl }
|
ba4971f943838ab0601c7a54160c383dda47e488 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/quadratic_discriminant.lean | a1f62bd32b9ebe3a1accf8c62d9beb815282d3af | [
"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 | 5,750 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou
-/
import algebra.char_p.invertible
import order.filter.at_top_bot
import tactic.linarith
/-!
# Quadratic discriminants and roots of a quadratic
This file defines the discriminant of a quadratic and gives the solution to a quadratic equation.
## Main definition
- `discrim a b c`: the discriminant of a quadratic `a * x * x + b * x + c` is `b * b - 4 * a * c`.
## Main statements
- `quadratic_eq_zero_iff`: roots of a quadratic can be written as
`(-b + s) / (2 * a)` or `(-b - s) / (2 * a)`, where `s` is a square root of the discriminant.
- `quadratic_ne_zero_of_discrim_ne_sq`: if the discriminant has no square root,
then the corresponding quadratic has no root.
- `discrim_le_zero`: if a quadratic is always non-negative, then its discriminant is non-positive.
## Tags
polynomial, quadratic, discriminant, root
-/
open filter
section ring
variables {R : Type*}
/-- Discriminant of a quadratic -/
def discrim [ring R] (a b c : R) : R := b^2 - 4 * a * c
variables [integral_domain R] {a b c : R}
/--
A quadratic has roots if and only if its discriminant equals some square.
-/
lemma quadratic_eq_zero_iff_discrim_eq_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0) (x : R) :
a * x * x + b * x + c = 0 ↔ discrim a b c = (2 * a * x + b) ^ 2 :=
begin
split,
{ assume h,
calc discrim a b c
= 4 * a * (a * x * x + b * x + c) + b * b - 4 * a * c : by { rw [h, discrim], ring }
... = (2*a*x + b)^2 : by ring },
{ assume h,
have ha : 2 * 2 * a ≠ 0 := mul_ne_zero (mul_ne_zero h2 h2) ha,
apply mul_left_cancel' ha,
calc
2 * 2 * a * (a * x * x + b * x + c) = (2 * a * x + b) ^ 2 - (b ^ 2 - 4 * a * c) : by ring
... = 0 : by { rw [← h, discrim], ring }
... = 2*2*a*0 : by ring }
end
/-- A quadratic has no root if its discriminant has no square root. -/
lemma quadratic_ne_zero_of_discrim_ne_sq (h2 : (2 : R) ≠ 0) (ha : a ≠ 0)
(h : ∀ s : R, discrim a b c ≠ s * s) (x : R) :
a * x * x + b * x + c ≠ 0 :=
begin
assume h',
rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, sq] at h',
exact h _ h'
end
end ring
section field
variables {K : Type*} [field K] [invertible (2 : K)] {a b c x : K}
/-- Roots of a quadratic -/
lemma quadratic_eq_zero_iff (ha : a ≠ 0) {s : K} (h : discrim a b c = s * s) (x : K) :
a * x * x + b * x + c = 0 ↔ x = (-b + s) / (2 * a) ∨ x = (-b - s) / (2 * a) :=
begin
have h2 : (2 : K) ≠ 0 := nonzero_of_invertible 2,
rw [quadratic_eq_zero_iff_discrim_eq_sq h2 ha, h, sq, mul_self_eq_mul_self_iff],
have ne : 2 * a ≠ 0 := mul_ne_zero h2 ha,
have : x = 2 * a * x / (2 * a) := (mul_div_cancel_left x ne).symm,
have h₁ : 2 * a * ((-b + s) / (2 * a)) = -b + s := mul_div_cancel' _ ne,
have h₂ : 2 * a * ((-b - s) / (2 * a)) = -b - s := mul_div_cancel' _ ne,
split,
{ intro h', rcases h',
{ left, rw h', simpa [add_comm] },
{ right, rw h', simpa [add_comm, sub_eq_add_neg] } },
{ intro h', rcases h', { left, rw [h', h₁], ring }, { right, rw [h', h₂], ring } }
end
/-- A quadratic has roots if its discriminant has square roots -/
lemma exists_quadratic_eq_zero (ha : a ≠ 0) (h : ∃ s, discrim a b c = s * s) :
∃ x, a * x * x + b * x + c = 0 :=
begin
rcases h with ⟨s, hs⟩,
use (-b + s) / (2 * a),
rw quadratic_eq_zero_iff ha hs,
simp
end
/-- Root of a quadratic when its discriminant equals zero -/
lemma quadratic_eq_zero_iff_of_discrim_eq_zero (ha : a ≠ 0) (h : discrim a b c = 0) (x : K) :
a * x * x + b * x + c = 0 ↔ x = -b / (2 * a) :=
begin
have : discrim a b c = 0 * 0, by rw [h, mul_zero],
rw [quadratic_eq_zero_iff ha this, add_zero, sub_zero, or_self]
end
end field
section linear_ordered_field
variables {K : Type*} [linear_ordered_field K] {a b c : K}
/-- If a polynomial of degree 2 is always nonnegative, then its discriminant is nonpositive -/
lemma discrim_le_zero (h : ∀ x : K, 0 ≤ a * x * x + b * x + c) : discrim a b c ≤ 0 :=
begin
rw [discrim, sq],
obtain ha|rfl|ha : a < 0 ∨ a = 0 ∨ 0 < a := lt_trichotomy a 0,
-- if a < 0
{ have : tendsto (λ x, (a * x + b) * x + c) at_top at_bot :=
tendsto_at_bot_add_const_right _ c ((tendsto_at_bot_add_const_right _ b
(tendsto_id.neg_const_mul_at_top ha)).at_bot_mul_at_top tendsto_id),
rcases (this.eventually (eventually_lt_at_bot 0)).exists with ⟨x, hx⟩,
exact false.elim ((h x).not_lt $ by rwa ← add_mul) },
-- if a = 0
{ rcases em (b = 0) with (rfl|hb),
{ simp },
{ have := h ((-c - 1) / b), rw [mul_div_cancel' _ hb] at this, linarith } },
-- if a > 0
{ have := calc
4 * a * (a * (-(b / a) * (1 / 2)) * (-(b / a) * (1 / 2)) + b * (-(b / a) * (1 / 2)) + c)
= (a * (b / a)) * (a * (b / a)) - 2 * (a * (b / a)) * b + 4 * a * c : by ring
... = -(b * b - 4 * a * c) : by { simp only [mul_div_cancel' b (ne_of_gt ha)], ring },
have ha' : 0 ≤ 4 * a, by linarith,
have h := (mul_nonneg ha' (h (-(b / a) * (1 / 2)))),
rw this at h, rwa ← neg_nonneg }
end
/--
If a polynomial of degree 2 is always positive, then its discriminant is negative,
at least when the coefficient of the quadratic term is nonzero.
-/
lemma discrim_lt_zero (ha : a ≠ 0) (h : ∀ x : K, 0 < a * x * x + b * x + c) : discrim a b c < 0 :=
begin
have : ∀ x : K, 0 ≤ a*x*x + b*x + c := assume x, le_of_lt (h x),
refine lt_of_le_of_ne (discrim_le_zero this) _,
assume h',
have := h (-b / (2 * a)),
have : a * (-b / (2 * a)) * (-b / (2 * a)) + b * (-b / (2 * a)) + c = 0,
{ rw [quadratic_eq_zero_iff_of_discrim_eq_zero ha h' (-b / (2 * a))] },
linarith
end
end linear_ordered_field
|
1a1384efb1743e4b120bd3da268d635d60dcf5a2 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Data/RBTree.lean | 3bcd15f477d868b3ebe2e26d7f779408c951890f | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 3,768 | 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 Lean.Data.RBMap
namespace Lean
universe u v w
def RBTree (α : Type u) (cmp : α → α → Ordering) : Type u :=
RBMap α Unit cmp
instance : Inhabited (RBTree α p) where
default := RBMap.empty
@[inline] def mkRBTree (α : Type u) (cmp : α → α → Ordering) : RBTree α cmp :=
mkRBMap α Unit cmp
instance (α : Type u) (cmp : α → α → Ordering) : EmptyCollection (RBTree α cmp) :=
⟨mkRBTree α cmp⟩
namespace RBTree
variable {α : Type u} {β : Type v} {cmp : α → α → Ordering}
@[inline] def empty : RBTree α cmp :=
RBMap.empty
@[inline] def depth (f : Nat → Nat → Nat) (t : RBTree α cmp) : Nat :=
RBMap.depth f t
@[inline] def fold (f : β → α → β) (init : β) (t : RBTree α cmp) : β :=
RBMap.fold (fun r a _ => f r a) init t
@[inline] def revFold (f : β → α → β) (init : β) (t : RBTree α cmp) : β :=
RBMap.revFold (fun r a _ => f r a) init t
@[inline] def foldM {m : Type v → Type w} [Monad m] (f : β → α → m β) (init : β) (t : RBTree α cmp) : m β :=
RBMap.foldM (fun r a _ => f r a) init t
@[inline] def forM {m : Type v → Type w} [Monad m] (f : α → m PUnit) (t : RBTree α cmp) : m PUnit :=
t.foldM (fun _ a => f a) ⟨⟩
@[inline] protected def forIn [Monad m] (t : RBTree α cmp) (init : σ) (f : α → σ → m (ForInStep σ)) : m σ :=
t.val.forIn init (fun a _ acc => f a acc)
instance : ForIn m (RBTree α cmp) α where
forIn := RBTree.forIn
@[inline] def isEmpty (t : RBTree α cmp) : Bool :=
RBMap.isEmpty t
@[specialize] def toList (t : RBTree α cmp) : List α :=
t.revFold (fun as a => a::as) []
@[specialize] def toArray (t : RBTree α cmp) : Array α :=
t.fold (fun as a => as.push a) #[]
@[inline] protected def min (t : RBTree α cmp) : Option α :=
match RBMap.min t with
| some ⟨a, _⟩ => some a
| none => none
@[inline] protected def max (t : RBTree α cmp) : Option α :=
match RBMap.max t with
| some ⟨a, _⟩ => some a
| none => none
instance [Repr α] : Repr (RBTree α cmp) where
reprPrec t prec := Repr.addAppParen ("Lean.rbtreeOf " ++ repr t.toList) prec
@[inline] def insert (t : RBTree α cmp) (a : α) : RBTree α cmp :=
RBMap.insert t a ()
@[inline] def erase (t : RBTree α cmp) (a : α) : RBTree α cmp :=
RBMap.erase t a
@[specialize] def ofList : List α → RBTree α cmp
| [] => mkRBTree ..
| x::xs => (ofList xs).insert x
@[inline] def find? (t : RBTree α cmp) (a : α) : Option α :=
match RBMap.findCore? t a with
| some ⟨a, _⟩ => some a
| none => none
@[inline] def contains (t : RBTree α cmp) (a : α) : Bool :=
(t.find? a).isSome
def fromList (l : List α) (cmp : α → α → Ordering) : RBTree α cmp :=
l.foldl insert (mkRBTree α cmp)
def fromArray (l : Array α) (cmp : α → α → Ordering) : RBTree α cmp :=
l.foldl insert (mkRBTree α cmp)
@[inline] def all (t : RBTree α cmp) (p : α → Bool) : Bool :=
RBMap.all t (fun a _ => p a)
@[inline] def any (t : RBTree α cmp) (p : α → Bool) : Bool :=
RBMap.any t (fun a _ => p a)
def subset (t₁ t₂ : RBTree α cmp) : Bool :=
t₁.all fun a => (t₂.find? a).toBool
def seteq (t₁ t₂ : RBTree α cmp) : Bool :=
subset t₁ t₂ && subset t₂ t₁
def union (t₁ t₂ : RBTree α cmp) : RBTree α cmp :=
if t₁.isEmpty then
t₂
else
t₂.fold .insert t₁
def diff (t₁ t₂ : RBTree α cmp) : RBTree α cmp :=
t₂.fold .erase t₁
end RBTree
def rbtreeOf {α : Type u} (l : List α) (cmp : α → α → Ordering) : RBTree α cmp :=
RBTree.fromList l cmp
|
fdb16e8fead66b00978475fac8a6806b10c76649 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/data/rat/basic.lean | 4f73818a1d510a4da5fcd3fc28b8698901279c03 | [
"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 | 30,790 | 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, Mario Carneiro
-/
import data.equiv.encodable.basic
import algebra.euclidean_domain
import data.nat.gcd
import data.int.cast
/-!
# Basics for the Rational Numbers
## Summary
We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where
- `num` is the numerator of `q`,
- `denom` is the denominator of `q`,
- `pos` is a proof that `denom > 0`, and
- `cop` is a proof `num` and `denom` are coprime.
We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it.
Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`.
## Main Definitions
- `rat` is the structure encoding `ℚ`.
- `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom
-/
/-- `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 : 0 < denom)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
/-- String representation of a rational numbers, used in `has_repr`, `has_to_string`, and
`has_to_format` instances. -/
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 : ℕ // 0 < d ∧ 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 (d : ℕ) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
localized "infix ` /. `:70 := rat.mk" in rat
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_injective, 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_injective; 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_injective; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib, sub_eq_add_neg], cc }
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 (dv.mul_left _) 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 (dv.mul_left _) 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 mul_right_cancel₀ 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
@[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a
| ⟨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.symm
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom'
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, 0 < d → (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
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `d ≠ 0`. -/
@[elab_as_eliminator] def {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 h.ne'
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
/-- Addition of rational numbers. Use `(+)` instead. -/
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
/-- Negation of rational numbers. Use `-r` instead. -/
protected def neg (r : ℚ) : ℚ :=
⟨-r.num, r.denom, r.pos, by simp [r.cop]⟩
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
/-- Multiplication of rational numbers. Use `(*)` instead. -/
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
/-- Inverse rational number. Use `r⁻¹` instead. -/
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₂]; cc
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, add_assoc]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
@[simp] lemma mk_zero_one : 0 /. 1 = 0 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_one_one : 1 /. 1 = 1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_neg_one_one : (-1) /. 1 = -1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
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:ℚ) :=
suffices (1:ℚ) = 0 → false, by cc,
by { rw [← mk_one_one, mk_eq_zero one_ne_zero], exact 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 simpa [h, n0, mul_comm] using @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 : 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,
exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩,
mul_inv_cancel := rat.mul_inv_cancel,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
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 : nontrivial ℚ := 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, sub_eq_add_neg]
@[simp] lemma denom_neg_eq_denom (q : ℚ) : (-q).denom = q.denom := rfl
@[simp] lemma num_neg_eq_neg_num (q : ℚ) : (-q).num = -(q.num) := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
@[simp] lemma denom_zero : rat.denom 0 = 1 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom.symm,
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 eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom :=
begin
conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] },
apply rat.mk_eq,
{ exact_mod_cast p.denom_ne_zero },
{ exact_mod_cast q.denom_ne_zero }
end
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 simpa using this,
by simp [mul_def hq' hr', -num_denom]
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 r
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp
... = (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 [num_denom],
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 },
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 mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom ∣ d.1 :=
begin
rw mk_pnat_denom,
apply nat.div_dvd_of_dvd,
apply nat.gcd_dvd_right
end
theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
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)
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_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
section casts
protected lemma add_mk (a b c : ℤ) : (a + b) /. c = a /. c + b /. c :=
if h : c = 0 then by simp [h] else
by { rw [add_def h h, mk_eq h (mul_ne_zero h h)], simp [add_mul, mul_assoc] }
theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, rat.add_mk]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, { rw ← of_int_eq_mk, simp, refl },
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH, ← mk_neg_one_one],
simp [-mk_neg_one_one]
end
theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0]
end
@[simp]
theorem num_div_denom (r : ℚ) : (r.num / r.denom : ℚ) = r :=
by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom]
lemma exists_eq_mul_div_num_and_eq_mul_div_denom {n d : ℤ} (n_ne_zero : n ≠ 0)
(d_ne_zero : d ≠ 0) :
∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom :=
begin
have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div],
exact rat.num_denom_mk n_ne_zero d_ne_zero this
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
@[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q :=
by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl }
lemma denom_eq_one_iff (r : ℚ) : r.denom = 1 ↔ ↑r.num = r :=
⟨rat.coe_int_num_of_denom_eq_one, λ h, h ▸ rat.coe_int_denom r.num⟩
instance : can_lift ℚ ℤ :=
⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩
theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 :=
by rw [← int.cast_coe_nat, coe_int_eq_mk]
@[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
-- Will be subsumed by `int.coe_inj` after we have defined
-- `linear_ordered_field ℚ` (which implies characteristic zero).
lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n :=
⟨λ h, by simpa using congr_arg num h, congr_arg _⟩
end casts
lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num :=
by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] }
@[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num :=
begin
suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by
{ conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] },
have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos),
rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)]
end
lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) :
((m : ℚ) / n).denom = 1 ↔ n ∣ m :=
begin
replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj],
split,
{ intro h,
lift ((m : ℚ) / n) to ℤ using h with k hk,
use k,
rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk },
{ rintros ⟨d, rfl⟩,
rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] }
end
lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
(a / b : ℚ).num = a :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one,
int.coe_nat_one, int.div_one]
end
lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
((a / b : ℚ).denom : ℤ) = b :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one,
nat.div_one]
end
lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d)
(h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs)
(h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d :=
begin
apply and.intro,
{ rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] },
{ rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] }
end
@[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n :=
begin
by_cases hn : n = 0,
{ subst hn, simp only [int.cast_zero, euclidean_domain.zero_div] },
{ have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn },
simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] }
end
@[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n :=
coe_int_div_self n
lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc,
coe_int_div_self]
end
lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc,
coe_nat_div_self]
end
lemma inv_coe_int_num {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply num_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_num {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
inv_coe_int_num (by exact_mod_cast ha0 : 0 < (a : ℤ))
lemma inv_coe_int_denom {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.denom : ℤ) = a :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply denom_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_denom {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.denom = a :=
by exact_mod_cast inv_coe_int_denom (by exact_mod_cast ha0 : 0 < (a : ℤ))
protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) :=
⟨λ h _ _, h _,
λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩
protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) :=
⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩
end rat
|
25d721eda929ba97e182053f182bb3f1329a6f23 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/right_assoc_dollar.lean | 8439ba1fb3056a54e0cf1badf7a9117ae0cba6bf | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 69 | lean | constant f : nat → nat → nat
open nat
check f $ succ $ 10 + 20
|
a7fed393d2bbd7adfc64046bfda1b9e7407af696 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/symmetric.lean | 108fb0f1d3e67e91f66cdb97e6750cbf38651cf9 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,263 | lean | /-
Copyright (c) 2021 Lu-Ming Zhang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Lu-Ming Zhang
-/
import data.matrix.block
/-!
# Symmetric matrices
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains the definition and basic results about symmetric matrices.
## Main definition
* `matrix.is_symm `: a matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`.
## Tags
symm, symmetric, matrix
-/
variables {α β n m R : Type*}
namespace matrix
open_locale matrix
/-- A matrix `A : matrix n n α` is "symmetric" if `Aᵀ = A`. -/
def is_symm (A : matrix n n α) : Prop := Aᵀ = A
lemma is_symm.eq {A : matrix n n α} (h : A.is_symm) : Aᵀ = A := h
/-- A version of `matrix.ext_iff` that unfolds the `matrix.transpose`. -/
lemma is_symm.ext_iff {A : matrix n n α} : A.is_symm ↔ ∀ i j, A j i = A i j :=
matrix.ext_iff.symm
/-- A version of `matrix.ext` that unfolds the `matrix.transpose`. -/
@[ext]
lemma is_symm.ext {A : matrix n n α} : (∀ i j, A j i = A i j) → A.is_symm :=
matrix.ext
lemma is_symm.apply {A : matrix n n α} (h : A.is_symm) (i j : n) : A j i = A i j :=
is_symm.ext_iff.1 h i j
lemma is_symm_mul_transpose_self [fintype n] [comm_semiring α] (A : matrix n n α) :
(A ⬝ Aᵀ).is_symm :=
transpose_mul _ _
lemma is_symm_transpose_mul_self [fintype n] [comm_semiring α] (A : matrix n n α) :
(Aᵀ ⬝ A).is_symm :=
transpose_mul _ _
lemma is_symm_add_transpose_self [add_comm_semigroup α] (A : matrix n n α) :
(A + Aᵀ).is_symm :=
add_comm _ _
lemma is_symm_transpose_add_self [add_comm_semigroup α] (A : matrix n n α) :
(Aᵀ + A).is_symm :=
add_comm _ _
@[simp] lemma is_symm_zero [has_zero α] :
(0 : matrix n n α).is_symm :=
transpose_zero
@[simp] lemma is_symm_one [decidable_eq n] [has_zero α] [has_one α] :
(1 : matrix n n α).is_symm :=
transpose_one
@[simp] lemma is_symm.map {A : matrix n n α} (h : A.is_symm) (f : α → β) :
(A.map f).is_symm :=
transpose_map.symm.trans (h.symm ▸ rfl)
@[simp] lemma is_symm.transpose {A : matrix n n α} (h : A.is_symm) :
Aᵀ.is_symm :=
congr_arg _ h
@[simp] lemma is_symm.conj_transpose [has_star α] {A : matrix n n α} (h : A.is_symm) :
Aᴴ.is_symm :=
h.transpose.map _
@[simp] lemma is_symm.neg [has_neg α] {A : matrix n n α} (h : A.is_symm) :
(-A).is_symm :=
(transpose_neg _).trans (congr_arg _ h)
@[simp] lemma is_symm.add {A B : matrix n n α} [has_add α] (hA : A.is_symm) (hB : B.is_symm) :
(A + B).is_symm :=
(transpose_add _ _).trans (hA.symm ▸ hB.symm ▸ rfl)
@[simp] lemma is_symm.sub {A B : matrix n n α} [has_sub α] (hA : A.is_symm) (hB : B.is_symm) :
(A - B).is_symm :=
(transpose_sub _ _).trans (hA.symm ▸ hB.symm ▸ rfl)
@[simp] lemma is_symm.smul [has_smul R α] {A : matrix n n α} (h : A.is_symm) (k : R) :
(k • A).is_symm :=
(transpose_smul _ _).trans (congr_arg _ h)
@[simp] lemma is_symm.submatrix {A : matrix n n α} (h : A.is_symm) (f : m → n) :
(A.submatrix f f).is_symm :=
(transpose_submatrix _ _ _).trans (h.symm ▸ rfl)
/-- The diagonal matrix `diagonal v` is symmetric. -/
@[simp] lemma is_symm_diagonal [decidable_eq n] [has_zero α] (v : n → α) :
(diagonal v).is_symm :=
diagonal_transpose _
/-- A block matrix `A.from_blocks B C D` is symmetric,
if `A` and `D` are symmetric and `Bᵀ = C`. -/
lemma is_symm.from_blocks
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α}
(hA : A.is_symm) (hBC : Bᵀ = C) (hD : D.is_symm) :
(A.from_blocks B C D).is_symm :=
begin
have hCB : Cᵀ = B, {rw ← hBC, simp},
unfold matrix.is_symm,
rw from_blocks_transpose,
congr;
assumption
end
/-- This is the `iff` version of `matrix.is_symm.from_blocks`. -/
lemma is_symm_from_blocks_iff
{A : matrix m m α} {B : matrix m n α} {C : matrix n m α} {D : matrix n n α} :
(A.from_blocks B C D).is_symm ↔ A.is_symm ∧ Bᵀ = C ∧ Cᵀ = B ∧ D.is_symm :=
⟨λ h, ⟨(congr_arg to_blocks₁₁ h : _), (congr_arg to_blocks₂₁ h : _),
(congr_arg to_blocks₁₂ h : _), (congr_arg to_blocks₂₂ h : _)⟩,
λ ⟨hA, hBC, hCB, hD⟩, is_symm.from_blocks hA hBC hD⟩
end matrix
|
d80e9648a43f51c75ac96681c7ef3b4bf666e291 | 761d983a78bc025071bac14a3facced881cf5e53 | /new_affine/affine_coordinate_basis.lean | 6d28b1903360ec9e18663de0cedb7f9d9728d813 | [] | no_license | rohanrajnair/affine_lib | bcf22ff892cf74ccb36a95bc9b7fff8e0adb2d0d | 83076864245ac547b9d615bc6a23804b1b4a8f70 | refs/heads/master | 1,673,320,928,343 | 1,603,036,653,000 | 1,603,036,653,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,082 | lean | import .affine_coordinate_space .list_as_k_tuple
import data.real.basic linear_algebra.affine_space.basic
import linear_algebra.basis
universes u v w x
variables (X : Type u) (K : Type v) (V : Type w) (n : ℕ) (k : K)
[inhabited K] [field K] [add_comm_group V] [vector_space K V] [affine_space V X]
open vecl
abbreviation zero := zero_vector K n
def list.to_basis_vec : fin n → list K := λ x, (zero K n).update_nth (x.1 + 1) 1
lemma len_basis_vec_fixed (x : fin n) : (list.to_basis_vec K n x).length = n + 1 := sorry
lemma head_basis_vec_fixed (x : fin n) : (list.to_basis_vec K n x).head = 0 := sorry
def std_basis : fin n → aff_vec K n :=
λ x, ⟨list.to_basis_vec K n x, len_basis_vec_fixed K n x, head_basis_vec_fixed K n x⟩
lemma std_is_basis : is_basis K (std_basis K n) := sorry
def std_frame : affine_frame (aff_pt K n) K (aff_vec K n) (fin n) := ⟨pt_zero K n, std_basis K n, std_is_basis K n⟩
noncomputable def r3_std_frame := std_frame ℝ 3
def std_origin : pt_with_frame (aff_pt K n) K (aff_vec K n) (fin n) (std_frame K n) := ⟨pt_zero K n⟩ |
646db41a0e65767e452b77911d21d16c8fc65923 | c39706ea6783f804f4403b8f001320a502de6f5a | /folklore/real_axiom.lean | 665a3533b716593074ae9e015fd37838a5eb3d26 | [
"CC-BY-4.0"
] | permissive | semorrison/formalabstracts | bb888dc605e789f4ef1d83635f3b8b9540dd0157 | e547f5939875ac6677b01ec6086d40992fa92629 | refs/heads/master | 1,609,531,064,153 | 1,501,856,066,000 | 1,501,856,066,000 | 98,728,403 | 0 | 0 | null | 1,501,327,991,000 | 1,501,327,991,000 | null | UTF-8 | Lean | false | false | 5,649 | lean | /-
axiomatic development of the complete ordered field
of real numbers in classical logic.
At some point this should be replaced with an actual
construction.
T.Hales, July 15, 2017
-/
import meta_data data.list
noncomputable theory
namespace real_axiom
open classical nat int list vector
local attribute [instance] prop_decidable
universe u
-- TODO: This definition used to be universe-polymorphic, but it looks like unfinished
-- does not support parameters so the universe u is unavailable, fix it.
unfinished ℝ : Type :=
{ description := "the type real numbers" }
unfinished real_of_int : ℤ → ℝ :=
{ description := "the canonical embedding of integers into reals" }
-- TODO: properly treat unbounded and empty sets
unfinished sup : (set ℝ) → ℝ :=
{ description := "the supremum of a subset of real numbers" }
instance real_of_nat_coe : has_coe ℤ ℝ :=
⟨ real_of_int ⟩
@[instance] constant real_ordered_field : linear_ordered_field ℝ
-- It is not clear why this line is required; but it is.
attribute [instance] real_ordered_field
def is_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) (r : α) : Prop :=
(∀ (s : α), s ∈ S → s ≤ r)
def has_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) : Prop :=
(∃ r : α, is_upper_bound S r)
def is_least_upper_bound {α : Type u} [R : linear_ordered_ring α] (S : set α) (s : α) :=
(is_upper_bound S s ∧
(∀ r, is_upper_bound S r → r ≤ s))
class complete_ordered_field (α : Type u) extends discrete_linear_ordered_field α :=
(sup : (set α) → α)
(dedekind_completeness : (∀ (S : set α), (S ≠ ∅) → has_upper_bound S →
is_least_upper_bound S (sup S)))
unfinished real_dedekind_completeness :
(∀ (S : set ℝ), (S ≠ ∅) → has_upper_bound S →
is_least_upper_bound S (sup S)) :=
{ description := "the real numbers are Dedekind complete" }
unfinished real_zero_inv : linear_ordered_field.inv (0 : ℝ) = 0 :=
{ description := "since all functions are total, we define 1/0=0"}
instance real_complete_ordered_field : complete_ordered_field ℝ :=
{
real_axiom.real_ordered_field with
sup := sup,
dedekind_completeness := real_dedekind_completeness,
inv_zero := real_zero_inv,
decidable_lt := by apply_instance,
decidable_le := by apply_instance,
decidable_eq := by apply_instance
}
unfinished real_archimedean :
(∀ x y, x > 0 → y > 0 → ∃ (n : ℕ), y < n*x) :=
{ description := "the real numbers are an archimedean field" }
-- why does -x ∈ S fail?
-- why does {x | ... } fail?
def real_inf (S : set ℝ) : ℝ :=
- (sup (λ x, S( -x )))
-- extension by zero when x < 0.
def real_sqrt (x : ℝ) : ℝ :=
sup (λ (t : ℝ), (t = 0) ∨ t*t = x)
def real_abs (x : ℝ) : ℝ :=
sup (λ (t : ℝ), t = x ∨ t = -x)
def real_max (x : ℝ) y : ℝ :=
sup (λ (t : ℝ), t = x ∨ t = y)
def real_min (x : ℝ) y : ℝ :=
real_inf (λ (t : ℝ), t = x ∨ t = y)
def real_pow : ℝ → ℕ → ℝ
| x 0 := (1 : ℝ)
| x (succ n) := x * (real_pow x n)
local infix `^` := real_pow
unfinished pi : ℝ :=
{ description := "the ratio of the circumference and the diameter of a circle" }
-- one possible specification of pi
unfinished pi_def :
(∀ (n : nat),
let iota := list.iota n,
terms := list.map (λ k, (-1)^(k+1) / (2*k-1)) iota in
(real_abs (pi/ 4 - list.sum terms) < 1 / (2*n + 3))) :=
{ description := "alternating series for pi/4 = 1 - 1/3 + 1/5 -..." }
inductive extended_real
| of_real : ℝ → extended_real
| inf : extended_real
| neg_inf : extended_real
notation `ℝ∞` := extended_real
unfinished ext_reals_has_add : has_add ℝ∞ :=
{ description := "extended reals have a + operator" }
unfinished ext_reals_has_sub : has_sub ℝ∞ :=
{ description := "extended reals have a - operator" }
unfinished ext_reals_has_mul : has_mul ℝ∞ :=
{ description := "extended reals have a * operator" }
unfinished ext_reals_has_div : has_div ℝ∞ :=
{ description := "extended reals have a / operator" }
unfinished ext_reals_order : linear_order ℝ∞ :=
{ description := "extended reals are ordered" }
instance : has_zero ℝ∞ := ⟨extended_real.of_real 0⟩
instance : has_one ℝ∞ := ⟨extended_real.of_real 1⟩
attribute [instance] ext_reals_has_add ext_reals_has_sub ext_reals_has_mul ext_reals_has_div ext_reals_order
unfinished ext_reals_mul_spec : extended_real.inf * 0 = 0 :=
{ description := "we specify that ∞ * 0 = 0" }
def extended_real.sup (s : set extended_real) : extended_real :=
if extended_real.inf ∈ s then extended_real.inf
else let non_neg_inf := {r | ∃ r' ∈ s, r' = extended_real.of_real r} in
extended_real.of_real (complete_ordered_field.sup non_neg_inf)
def extended_real.partial_sum (f : ℕ → ℝ∞) (n : ℕ) : ℝ∞ :=
((list.iota n).map f).foldr (+) 0
open extended_real
def extended_real.countable_sum (f : ℕ → ℝ∞) :=
if h : (∃ r : ℝ, ∀ ε : ℝ, ε > 0 → ∃ n, of_real (-ε) < extended_real.partial_sum f n - of_real r ∧ extended_real.partial_sum f n - of_real r < of_real ε)
then of_real (some h)
else inf
unfinished countable_sum_spec : ∀ f : ℕ → ℝ∞, ∀ h : (∀ n, f n ≥ 0),
(∀ ε : ℝ, ε > 0 → ∃ n, of_real (-ε) < extended_real.partial_sum f n - (extended_real.countable_sum f) ∧
extended_real.partial_sum f n - (extended_real.countable_sum f) < of_real ε)
∨ (∀ r : ℝ, ∃ n, extended_real.partial_sum f n > of_real r) :=
{ description := "If f : ℕ → ℝ∞ is nonnegative, then it has a countable sum in ℝ∞, either a real or ∞" }
end real_axiom
|
fb33fa4ce17f974681d62e5d957c3972f6b2b9e3 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/holor.lean | 8d1be3c4daa773256d9262695da7364e564f91a0 | [
"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 | 14,189 | lean | /-
Copyright (c) 2018 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp
-/
import algebra.module.pi
import algebra.big_operators.basic
/-!
# Basic properties of holors
Holors are indexed collections of tensor coefficients. Confusingly,
they are often called tensors in physics and in the neural network
community.
A holor is simply a multidimensional array of values. The size of a
holor is specified by a `list ℕ`, whose length is called the dimension
of the holor.
The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the
holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of
rank at most 1" if it is a tensor product of one-dimensional holors.
The CP rank of a holor `x` is the smallest N such that `x` is the sum
of N holors of rank at most 1.
Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html>
## References
* <https://en.wikipedia.org/wiki/Tensor_rank_decomposition>
-/
universes u
open list
open_locale big_operators
/-- `holor_index ds` is the type of valid index tuples used to identify an entry of a holor
of dimensions `ds`. -/
def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds}
namespace holor_index
variables {ds₁ ds₂ ds₃ : list ℕ}
def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁
| ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩
def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂
| ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩
lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) :
(cast (congr_arg holor_index eq) ⟨is, h⟩).val = is :=
by subst eq; refl
def assoc_right :
holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm)
lemma take_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.take = t.take.take
| ⟨ is , h ⟩ := subtype.eq $ by simp [assoc_right,take, cast_type, list.take_take,
nat.le_add_right, min_eq_left]
lemma drop_take :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.take = t.take.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take])
lemma drop_drop :
∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃),
t.assoc_right.drop.drop = t.drop
| ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop])
end holor_index
/-- Holor (indexed collections of tensor coefficients) -/
def holor (α : Type u) (ds:list ℕ) := holor_index ds → α
namespace holor
variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ}
instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩
instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩
instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩
instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩
instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance
instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance
instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance
instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance
instance [add_group α] : add_group (holor α ds) := by pi_instance
instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance
/- scalar product -/
instance [has_mul α] : has_scalar α (holor α ds) :=
⟨λ a x, λ t, a * x t⟩
instance [semiring α] : semimodule α (holor α ds) := pi.semimodule _ _ _
/-- The tensor product of two holors. -/
def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) :=
λ t, x (t.take) * y (t.drop)
local infix ` ⊗ ` : 70 := mul
lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) :
cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) :=
by subst eq; refl
def assoc_right :
holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃))
def assoc_left :
holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) :=
cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm)
lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left :=
funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃),
begin
rw assoc_left,
unfold mul,
rw mul_assoc,
rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop],
rw cast_type,
refl,
rw append_assoc
end)
lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) :
mul (mul x y) z == (mul x (mul y z)) :=
by simp [cast_heq, mul_assoc0, assoc_left].
lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) :
x ⊗ (y + z) = x ⊗ y + x ⊗ z :=
funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t)))
lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) :
(x + y) ⊗ z = x ⊗ z + y ⊗ z :=
funext $ λt, add_mul (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))
@[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) :
(0 : holor α ds₁) ⊗ x = 0 :=
funext (λ t, zero_mul (x (holor_index.drop t)))
@[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) :
x ⊗ (0 :holor α ds₂) = 0 :=
funext (λ t, mul_zero (x (holor_index.take t)))
lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) :
x ⊗ y = x ⟨[], forall₂.nil⟩ • y :=
by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop]
/- holor slices -/
/-- A slice is a subholor consisting of all entries with initial index i. -/
def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds :=
(λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩)
/-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/
def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] :=
λ ti, if ti.1 = [j] then 1 else 0
lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) :
Π (t : holor_index (d :: ds)),
(∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t
| ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds)
| ⟨(i :: is), hforall₂⟩ hp := hp i is rfl
/-- Two holors are equal if all their slices are equal. -/
lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds))
(h : slice x = slice y) : x = y :=
funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis,
have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end,
have hid: i<d, from (forall₂_cons.1 hiisdds).1,
have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2,
calc
x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl)
... = slice y i hid ⟨is, hisds⟩ : by rw h
... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl)
lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ}
(hid : i < d) (x : holor α ds) :
slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 :=
funext $ λ t : holor_index ds, if h : i = j
then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]
else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl
lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) :
slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)])
lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) :
slice (0 : holor α (d :: ds)) i hid = 0 := rfl
lemma slice_sum [add_comm_monoid α] {β : Type}
(i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) :
∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid :=
begin
letI := classical.dec_eq β,
refine finset.induction_on s _ _,
{ simp [slice_zero] },
{ intros _ _ h_not_in ih,
rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] }
end
/-- The original holor can be recovered from its slices by multiplying with unit vectors and
summing up. -/
@[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) :
∑ i in (finset.range d).attach,
unit_vec d i ⊗ slice x i (nat.succ_le_of_lt (finset.mem_range.1 i.prop)) = x :=
begin
apply slice_eq _ _ _,
ext i hid,
rw [←slice_sum],
simp only [slice_unit_vec_mul hid],
rw finset.sum_eq_single (subtype.mk i $ finset.mem_range.2 hid),
{ simp },
{ assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩),
have hbi' : i ≠ b,
{ simpa only [ne.def, subtype.ext_iff, subtype.coe_mk] using hbi.symm },
simp [hbi'] },
{ assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d),
exfalso,
exact absurd (finset.mem_attach _ _) hid'
}
end
/- CP rank -/
/-- `cprank_max1 x` means `x` has CP rank at most 1, that is,
it is the tensor product of 1-dimensional holors. -/
inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop
| nil (x : holor α []) :
cprank_max1 x
| cons {d} {ds} (x : holor α [d]) (y : holor α ds) :
cprank_max1 y → cprank_max1 (x ⊗ y)
/-- `cprank_max N x` means `x` has CP rank at most `N`, that is,
it can be written as the sum of N holors of rank at most 1. -/
inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop
| zero {ds} :
cprank_max 0 (0 : holor α ds)
| succ n {ds} (x : holor α ds) (y : holor α ds) :
cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y)
lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x :=
have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero),
by rwa [add_zero x, zero_add] at h
lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds}
(h : cprank_max1 x) : cprank_max 1 x :=
have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero,
by rwa [zero_add, add_zero] at h'
lemma cprank_max_add [monoid α] [add_monoid α]:
∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds},
cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y)
| 0 n x y (cprank_max.zero) hy := by simp [hy]
| (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy :=
begin
simp only [add_comm, add_assoc],
apply cprank_max.succ,
{ assumption },
{ exact cprank_max_add hx₂ hy }
end
lemma cprank_max_mul [ring α] :
∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y)
| 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero]
| (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) :=
begin
rw mul_left_distrib,
rw nat.add_comm,
apply cprank_max_add,
{ exact cprank_max_1 (cprank_max1.cons _ _ hy₁) },
{ exact cprank_max_mul k x y₂ hy₂ }
end
lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) :
(∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) :=
by letI := classical.dec_eq β;
exact finset.induction_on s
(by simp [cprank_max.zero])
(begin
assume x s (h_x_notin_s : x ∉ s) ih h_cprank,
simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s],
rw nat.right_distrib,
simp only [nat.one_mul, nat.add_comm],
have ih' : cprank_max (finset.card s * n) (∑ x in s, f x),
{
apply ih,
assume (x : β) (h_x_in_s: x ∈ s),
simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s]
},
exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih')
end)
lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x
| [] x := cprank_max_nil x
| (d :: ds) x :=
have h_summands : Π (i : {x // x ∈ finset.range d}),
cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)),
from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))),
have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds,
by simp [finset.card_range],
have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i),
have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds)
(∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)),
by rwa [finset.card_attach] at this,
begin
rw [←sum_unit_vec_mul_slice x],
rw [h_dds_prod],
exact h_cprank_max_sum,
end
/-- The CP rank of a holor `x`: the smallest N such that
`x` can be written as the sum of N holors of rank at most 1. -/
noncomputable def cprank [ring α] (x : holor α ds) : nat :=
@nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩
lemma cprank_upper_bound [ring α] :
Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod :=
λ ds (x : holor α ds),
by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x);
exact nat.find_min'
⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩
(cprank_max_upper_bound x)
end holor
|
48d17f674d7cfe18241d3a553197119239953f53 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/test/clone/test/lakefile.lean | 74934abef2567f805b94b17db194bbf6a27ba72a | [
"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 | 265 | lean | import Lake
import Lean.Meta
open System Lake DSL
package test
def url : String :=
match get_config? url with
| some url => url
| none => (FilePath.mk ".." / "hello").toString
require hello from git url
@[default_target]
lean_exe test {
root := `Main
}
|
ba1a6b12efc281e429b688d51830006f310cfdeb | 05f637fa14ac28031cb1ea92086a0f4eb23ff2b1 | /tests/lean/simp29.lean | d8951d69650d5a7986d0b05ef83c3e9d741c957e | [
"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 | 364 | lean | rewrite_set simple
add_rewrite eq_id imp_truel imp_truer Nat::add_zeror : simple
variables a b : Nat
variable f {A : Type} : A → Bool
axiom fNat (a : Nat) : f a = (a > 0)
add_rewrite fNat : simple
(*
local t = parse_lean('(∀ x : Nat, f x) ∧ (∀ x : Bool, f x)')
local t2, pr = simplify(t, "simple")
print(t2)
print(pr)
get_environment():type_check(pr)
*)
|
6d2b68713389b1d77ba471d23b7437c48b25709f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/dedekind_domain.lean | cb0ac9405e13ed99954b418e05a180e3b72a0026 | [
"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 | 44,415 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.discrete_valuation_ring
import ring_theory.fractional_ideal
import ring_theory.ideal.over
import ring_theory.integrally_closed
import ring_theory.polynomial.rational_root
import ring_theory.trace
import algebra.associated
import algebraic_geometry.prime_spectrum.noetherian
/-!
# Dedekind domains
This file defines the notion of a Dedekind domain (or Dedekind ring),
giving three equivalent definitions (TODO: and shows that they are equivalent).
## Main definitions
- `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is
Noetherian, integrally closed in its field of fractions and has Krull dimension at most one.
`is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions.
- `is_dedekind_domain_dvr` alternatively defines a Dedekind domain as an integral domain that
is Noetherian, and the localization at every nonzero prime ideal is a DVR.
- `is_dedekind_domain_inv` alternatively defines a Dedekind domain as an integral domain where
every nonzero fractional ideal is invertible.
- `is_dedekind_domain_inv_iff` shows that this does note depend on the choice of field of
fractions.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
Often, definitions assume that Dedekind domains are not fields. We found it more practical
to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K]
open_locale non_zero_divisors
/-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/
def ring.dimension_le_one : Prop :=
∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal
open ideal ring
namespace ring
lemma dimension_le_one.principal_ideal_ring
[is_domain A] [is_principal_ideal_ring A] : dimension_le_one A :=
λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero }
lemma dimension_le_one.is_integral_closure (B : Type*) [comm_ring B] [is_domain B]
[nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A]
[is_integral_closure B R A] (h : dimension_le_one R) :
dimension_le_one B :=
λ p ne_bot prime, by exactI
is_integral_closure.is_maximal_of_is_maximal_comap A p
(h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance)
lemma dimension_le_one.integral_closure [nontrivial R] [is_domain A] [algebra R A]
(h : dimension_le_one R) : dimension_le_one (integral_closure R A) :=
h.is_integral_closure R A (integral_closure R A)
end ring
variables [is_domain A]
/--
A Dedekind domain is an integral domain that is Noetherian, integrally closed, and
has Krull dimension at most one.
This is definition 3.2 of [Neukirch1992].
The integral closure condition is independent of the choice of field of fractions:
use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`.
This is the default implementation, but there are equivalent definitions,
`is_dedekind_domain_dvr` and `is_dedekind_domain_inv`.
TODO: Prove that these are actually equivalent definitions.
-/
class is_dedekind_domain : Prop :=
(is_noetherian_ring : is_noetherian_ring A)
(dimension_le_one : dimension_le_one A)
(is_integrally_closed : is_integrally_closed A)
-- See library note [lower instance priority]
attribute [instance, priority 100]
is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed
/-- An integral domain is a Dedekind domain iff and only if it is
Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field.
In particular, this definition does not depend on the choice of this fraction field. -/
lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] :
is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧
(∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) :=
⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩,
λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩
@[priority 100] -- See library note [lower instance priority]
instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] :
is_dedekind_domain A :=
⟨principal_ideal_ring.is_noetherian_ring,
ring.dimension_le_one.principal_ideal_ring A,
unique_factorization_monoid.is_integrally_closed⟩
/--
A Dedekind domain is an integral domain that is Noetherian, and the
localization at every nonzero prime is a discrete valuation ring.
This is equivalent to `is_dedekind_domain`.
TODO: prove the equivalence.
-/
structure is_dedekind_domain_dvr : Prop :=
(is_noetherian_ring : is_noetherian_ring A)
(is_dvr_at_nonzero_prime : ∀ P ≠ (⊥ : ideal A), P.is_prime →
discrete_valuation_ring (localization.at_prime P))
section inverse
namespace fractional_ideal
variables {R₁ : Type*} [comm_ring R₁] [is_domain R₁] [algebra R₁ K] [is_fraction_ring R₁ K]
variables {I J : fractional_ideal R₁⁰ K}
noncomputable instance : has_inv (fractional_ideal R₁⁰ K) := ⟨λ I, 1 / I⟩
lemma inv_eq : I⁻¹ = 1 / I := rfl
lemma inv_zero' : (0 : fractional_ideal R₁⁰ K)⁻¹ = 0 := fractional_ideal.div_zero
lemma inv_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
J⁻¹ = ⟨(1 : fractional_ideal R₁⁰ K) / J, fractional_ideal.fractional_div_of_nonzero h⟩ :=
fractional_ideal.div_nonzero _
lemma coe_inv_of_nonzero {J : fractional_ideal R₁⁰ K} (h : J ≠ 0) :
(↑J⁻¹ : submodule R₁ K) = is_localization.coe_submodule K ⊤ / J :=
by { rwa inv_nonzero _, refl, assumption }
variables {K}
lemma mem_inv_iff (hI : I ≠ 0) {x : K} :
x ∈ I⁻¹ ↔ ∀ y ∈ I, x * y ∈ (1 : fractional_ideal R₁⁰ K) :=
fractional_ideal.mem_div_iff_of_nonzero hI
lemma inv_anti_mono (hI : I ≠ 0) (hJ : J ≠ 0) (hIJ : I ≤ J) :
J⁻¹ ≤ I⁻¹ :=
λ x, by { simp only [mem_inv_iff hI, mem_inv_iff hJ], exact λ h y hy, h y (hIJ hy) }
lemma le_self_mul_inv {I : fractional_ideal R₁⁰ K} (hI : I ≤ (1 : fractional_ideal R₁⁰ K)) :
I ≤ I * I⁻¹ :=
fractional_ideal.le_self_mul_one_div hI
variables (K)
lemma coe_ideal_le_self_mul_inv (I : ideal R₁) :
(I : fractional_ideal R₁⁰ K) ≤ I * I⁻¹ :=
le_self_mul_inv fractional_ideal.coe_ideal_le_one
/-- `I⁻¹` is the inverse of `I` if `I` has an inverse. -/
theorem right_inverse_eq (I J : fractional_ideal R₁⁰ K) (h : I * J = 1) :
J = I⁻¹ :=
begin
have hI : I ≠ 0 := fractional_ideal.ne_zero_of_mul_eq_one I J h,
suffices h' : I * (1 / I) = 1,
{ exact (congr_arg units.inv $
@units.ext _ _ (units.mk_of_mul_eq_one _ _ h) (units.mk_of_mul_eq_one _ _ h') rfl) },
apply le_antisymm,
{ apply fractional_ideal.mul_le.mpr _,
intros x hx y hy,
rw mul_comm,
exact (fractional_ideal.mem_div_iff_of_nonzero hI).mp hy x hx },
rw ← h,
apply fractional_ideal.mul_left_mono I,
apply (fractional_ideal.le_div_iff_of_nonzero hI).mpr _,
intros y hy x hx,
rw mul_comm,
exact fractional_ideal.mul_mem_mul hx hy
end
theorem mul_inv_cancel_iff {I : fractional_ideal R₁⁰ K} :
I * I⁻¹ = 1 ↔ ∃ J, I * J = 1 :=
⟨λ h, ⟨I⁻¹, h⟩, λ ⟨J, hJ⟩, by rwa ← right_inverse_eq K I J hJ⟩
lemma mul_inv_cancel_iff_is_unit {I : fractional_ideal R₁⁰ K} :
I * I⁻¹ = 1 ↔ is_unit I :=
(mul_inv_cancel_iff K).trans is_unit_iff_exists_inv.symm
variables {K' : Type*} [field K'] [algebra R₁ K'] [is_fraction_ring R₁ K']
@[simp] lemma map_inv (I : fractional_ideal R₁⁰ K) (h : K ≃ₐ[R₁] K') :
(I⁻¹).map (h : K →ₐ[R₁] K') = (I.map h)⁻¹ :=
by rw [inv_eq, fractional_ideal.map_div, fractional_ideal.map_one, inv_eq]
open submodule submodule.is_principal
@[simp] lemma span_singleton_inv (x : K) :
(fractional_ideal.span_singleton R₁⁰ x)⁻¹ = fractional_ideal.span_singleton _ (x⁻¹) :=
fractional_ideal.one_div_span_singleton x
lemma mul_generator_self_inv {R₁ : Type*} [comm_ring R₁] [algebra R₁ K] [is_localization R₁⁰ K]
(I : fractional_ideal R₁⁰ K) [submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
I * fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹ = 1 :=
begin
-- Rewrite only the `I` that appears alone.
conv_lhs { congr, rw fractional_ideal.eq_span_singleton_of_principal I },
rw [fractional_ideal.span_singleton_mul_span_singleton, mul_inv_cancel,
fractional_ideal.span_singleton_one],
intro generator_I_eq_zero,
apply h,
rw [fractional_ideal.eq_span_singleton_of_principal I, generator_I_eq_zero,
fractional_ideal.span_singleton_zero]
end
lemma invertible_of_principal (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
I * I⁻¹ = 1 :=
(fractional_ideal.mul_div_self_cancel_iff).mpr
⟨fractional_ideal.span_singleton _ (generator (I : submodule R₁ K))⁻¹,
mul_generator_self_inv _ I h⟩
lemma invertible_iff_generator_nonzero (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] :
I * I⁻¹ = 1 ↔ generator (I : submodule R₁ K) ≠ 0 :=
begin
split,
{ intros hI hg,
apply fractional_ideal.ne_zero_of_mul_eq_one _ _ hI,
rw [fractional_ideal.eq_span_singleton_of_principal I, hg,
fractional_ideal.span_singleton_zero] },
{ intro hg,
apply invertible_of_principal,
rw [fractional_ideal.eq_span_singleton_of_principal I],
intro hI,
have := fractional_ideal.mem_span_singleton_self _ (generator (I : submodule R₁ K)),
rw [hI, fractional_ideal.mem_zero_iff] at this,
contradiction }
end
lemma is_principal_inv (I : fractional_ideal R₁⁰ K)
[submodule.is_principal (I : submodule R₁ K)] (h : I ≠ 0) :
submodule.is_principal (I⁻¹).1 :=
begin
rw [fractional_ideal.val_eq_coe, fractional_ideal.is_principal_iff],
use (generator (I : submodule R₁ K))⁻¹,
have hI : I * fractional_ideal.span_singleton _ ((generator (I : submodule R₁ K))⁻¹) = 1,
apply mul_generator_self_inv _ I h,
exact (right_inverse_eq _ I (fractional_ideal.span_singleton _
((generator (I : submodule R₁ K))⁻¹)) hI).symm
end
@[simp] lemma one_inv : (1⁻¹ : fractional_ideal R₁⁰ K) = 1 :=
fractional_ideal.div_one
end fractional_ideal
/--
A Dedekind domain is an integral domain such that every fractional ideal has an inverse.
This is equivalent to `is_dedekind_domain`.
In particular we provide a `fractional_ideal.comm_group_with_zero` instance,
assuming `is_dedekind_domain A`, which implies `is_dedekind_domain_inv`. For **integral** ideals,
`is_dedekind_domain`(`_inv`) implies only `ideal.cancel_comm_monoid_with_zero`.
-/
def is_dedekind_domain_inv : Prop :=
∀ I ≠ (⊥ : fractional_ideal A⁰ (fraction_ring A)), I * I⁻¹ = 1
open fractional_ideal
variables {R A K}
lemma is_dedekind_domain_inv_iff [algebra A K] [is_fraction_ring A K] :
is_dedekind_domain_inv A ↔
(∀ I ≠ (⊥ : fractional_ideal A⁰ K), I * I⁻¹ = 1) :=
begin
set h := fraction_ring.alg_equiv A K,
split; rintros hi I hI,
{ refine fractional_ideal.map_injective h.symm.to_alg_hom h.symm.injective _,
rw [alg_equiv.to_alg_hom_eq_coe, inv_eq, fractional_ideal.map_mul,
fractional_ideal.map_one_div, fractional_ideal.map_one, ← inv_eq, hi],
exact fractional_ideal.map_ne_zero _ hI },
{ refine fractional_ideal.map_injective h.to_alg_hom h.injective _,
rw [alg_equiv.to_alg_hom_eq_coe, inv_eq, fractional_ideal.map_mul,
fractional_ideal.map_one_div, fractional_ideal.map_one, ← inv_eq, hi],
exact fractional_ideal.map_ne_zero _ hI },
end
lemma fractional_ideal.adjoin_integral_eq_one_of_is_unit [algebra A K] [is_fraction_ring A K]
(x : K) (hx : is_integral A x) (hI : is_unit (adjoin_integral A⁰ x hx)) :
adjoin_integral A⁰ x hx = 1 :=
begin
set I := adjoin_integral A⁰ x hx,
have mul_self : I * I = I,
{ apply fractional_ideal.coe_to_submodule_injective, simp },
convert congr_arg (* I⁻¹) mul_self;
simp only [(mul_inv_cancel_iff_is_unit K).mpr hI, mul_assoc, mul_one],
end
namespace is_dedekind_domain_inv
variables [algebra A K] [is_fraction_ring A K] (h : is_dedekind_domain_inv A)
include h
lemma mul_inv_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I * I⁻¹ = 1 :=
is_dedekind_domain_inv_iff.mp h I hI
lemma inv_mul_eq_one {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : I⁻¹ * I = 1 :=
(mul_comm _ _).trans (h.mul_inv_eq_one hI)
protected lemma is_unit {I : fractional_ideal A⁰ K} (hI : I ≠ 0) : is_unit I :=
is_unit_of_mul_eq_one _ _ (h.mul_inv_eq_one hI)
lemma is_noetherian_ring : is_noetherian_ring A :=
begin
refine is_noetherian_ring_iff.mpr ⟨λ (I : ideal A), _⟩,
by_cases hI : I = ⊥,
{ rw hI, apply submodule.fg_bot },
have hI : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 :=
(coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI,
exact I.fg_of_is_unit (is_fraction_ring.injective A (fraction_ring A)) (h.is_unit hI)
end
lemma integrally_closed : is_integrally_closed A :=
begin
-- It suffices to show that for integral `x`,
-- `A[x]` (which is a fractional ideal) is in fact equal to `A`.
refine ⟨λ x hx, _⟩,
rw [← set.mem_range, ← algebra.mem_bot, ← subalgebra.mem_to_submodule, algebra.to_submodule_bot,
← coe_span_singleton A⁰ (1 : fraction_ring A), fractional_ideal.span_singleton_one,
← fractional_ideal.adjoin_integral_eq_one_of_is_unit x hx (h.is_unit _)],
{ exact mem_adjoin_integral_self A⁰ x hx },
{ exact λ h, one_ne_zero (eq_zero_iff.mp h 1 (subalgebra.one_mem _)) },
end
lemma dimension_le_one : dimension_le_one A :=
begin
-- We're going to show that `P` is maximal because any (maximal) ideal `M`
-- that is strictly larger would be `⊤`.
rintros P P_ne hP,
refine ideal.is_maximal_def.mpr ⟨hP.ne_top, λ M hM, _⟩,
-- We may assume `P` and `M` (as fractional ideals) are nonzero.
have P'_ne : (P : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 :=
(coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr P_ne,
have M'_ne : (M : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 :=
(coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr
(lt_of_le_of_lt bot_le hM).ne',
-- In particular, we'll show `M⁻¹ * P ≤ P`
suffices : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ P,
{ rw [eq_top_iff, ← coe_ideal_le_coe_ideal (fraction_ring A), fractional_ideal.coe_ideal_top],
calc (1 : fractional_ideal A⁰ (fraction_ring A)) = _ * _ * _ : _
... ≤ _ * _ : mul_right_mono (P⁻¹ * M : fractional_ideal A⁰ (fraction_ring A)) this
... = M : _,
{ rw [mul_assoc, ← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul, h.inv_mul_eq_one M'_ne] },
{ rw [← mul_assoc ↑P, h.mul_inv_eq_one P'_ne, one_mul] },
{ apply_instance } },
-- Suppose we have `x ∈ M⁻¹ * P`, then in fact `x = algebra_map _ _ y` for some `y`.
intros x hx,
have le_one : (M⁻¹ * P : fractional_ideal A⁰ (fraction_ring A)) ≤ 1,
{ rw [← h.inv_mul_eq_one M'_ne],
exact fractional_ideal.mul_left_mono _ ((coe_ideal_le_coe_ideal (fraction_ring A)).mpr hM.le) },
obtain ⟨y, hy, rfl⟩ := (mem_coe_ideal _).mp (le_one hx),
-- Since `M` is strictly greater than `P`, let `z ∈ M \ P`.
obtain ⟨z, hzM, hzp⟩ := set_like.exists_of_lt hM,
-- We have `z * y ∈ M * (M⁻¹ * P) = P`.
have zy_mem := fractional_ideal.mul_mem_mul (mem_coe_ideal_of_mem A⁰ hzM) hx,
rw [← ring_hom.map_mul, ← mul_assoc, h.mul_inv_eq_one M'_ne, one_mul] at zy_mem,
obtain ⟨zy, hzy, zy_eq⟩ := (mem_coe_ideal A⁰).mp zy_mem,
rw is_fraction_ring.injective A (fraction_ring A) zy_eq at hzy,
-- But `P` is a prime ideal, so `z ∉ P` implies `y ∈ P`, as desired.
exact mem_coe_ideal_of_mem A⁰ (or.resolve_left (hP.mem_or_mem hzy) hzp)
end
/-- Showing one side of the equivalence between the definitions
`is_dedekind_domain_inv` and `is_dedekind_domain` of Dedekind domains. -/
theorem is_dedekind_domain : is_dedekind_domain A :=
⟨h.is_noetherian_ring, h.dimension_le_one, h.integrally_closed⟩
end is_dedekind_domain_inv
variables [algebra A K] [is_fraction_ring A K]
/-- Specialization of `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` to Dedekind domains:
Let `I : ideal A` be a nonzero ideal, where `A` is a Dedekind domain that is not a field.
Then `exists_prime_spectrum_prod_le_and_ne_bot_of_domain` states we can find a product of prime
ideals that is contained within `I`. This lemma extends that result by making the product minimal:
let `M` be a maximal ideal that contains `I`, then the product including `M` is contained within `I`
and the product excluding `M` is not contained within `I`. -/
lemma exists_multiset_prod_cons_le_and_prod_not_le [is_dedekind_domain A]
(hNF : ¬ is_field A) {I M : ideal A} (hI0 : I ≠ ⊥) (hIM : I ≤ M) [hM : M.is_maximal] :
∃ (Z : multiset (prime_spectrum A)),
(M ::ₘ (Z.map prime_spectrum.as_ideal)).prod ≤ I ∧
¬ (multiset.prod (Z.map prime_spectrum.as_ideal) ≤ I) :=
begin
-- Let `Z` be a minimal set of prime ideals such that their product is contained in `J`.
obtain ⟨Z₀, hZ₀⟩ := prime_spectrum.exists_prime_spectrum_prod_le_and_ne_bot_of_domain hNF hI0,
obtain ⟨Z, ⟨hZI, hprodZ⟩, h_eraseZ⟩ := multiset.well_founded_lt.has_min
(λ Z, (Z.map prime_spectrum.as_ideal).prod ≤ I ∧ (Z.map prime_spectrum.as_ideal).prod ≠ ⊥)
⟨Z₀, hZ₀⟩,
have hZM : multiset.prod (Z.map prime_spectrum.as_ideal) ≤ M := le_trans hZI hIM,
have hZ0 : Z ≠ 0, { rintro rfl, simpa [hM.ne_top] using hZM },
obtain ⟨_, hPZ', hPM⟩ := (hM.is_prime.multiset_prod_le (mt multiset.map_eq_zero.mp hZ0)).mp hZM,
-- Then in fact there is a `P ∈ Z` with `P ≤ M`.
obtain ⟨P, hPZ, rfl⟩ := multiset.mem_map.mp hPZ',
letI := classical.dec_eq (ideal A),
have := multiset.map_erase prime_spectrum.as_ideal subtype.coe_injective P Z,
obtain ⟨hP0, hZP0⟩ : P.as_ideal ≠ ⊥ ∧ ((Z.erase P).map prime_spectrum.as_ideal).prod ≠ ⊥,
{ rwa [ne.def, ← multiset.cons_erase hPZ', multiset.prod_cons, ideal.mul_eq_bot,
not_or_distrib, ← this] at hprodZ },
-- By maximality of `P` and `M`, we have that `P ≤ M` implies `P = M`.
have hPM' := (is_dedekind_domain.dimension_le_one _ hP0 P.is_prime).eq_of_le hM.ne_top hPM,
substI hPM',
-- By minimality of `Z`, erasing `P` from `Z` is exactly what we need.
refine ⟨Z.erase P, _, _⟩,
{ convert hZI,
rw [this, multiset.cons_erase hPZ'] },
{ refine λ h, h_eraseZ (Z.erase P) ⟨h, _⟩ (multiset.erase_lt.mpr hPZ),
exact hZP0 }
end
namespace fractional_ideal
lemma exists_not_mem_one_of_ne_bot [is_dedekind_domain A]
(hNF : ¬ is_field A) {I : ideal A} (hI0 : I ≠ ⊥) (hI1 : I ≠ ⊤) :
∃ x : K, x ∈ (I⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K) :=
begin
-- WLOG, let `I` be maximal.
suffices : ∀ {M : ideal A} (hM : M.is_maximal),
∃ x : K, x ∈ (M⁻¹ : fractional_ideal A⁰ K) ∧ x ∉ (1 : fractional_ideal A⁰ K),
{ obtain ⟨M, hM, hIM⟩ : ∃ (M : ideal A), is_maximal M ∧ I ≤ M := ideal.exists_le_maximal I hI1,
resetI,
have hM0 := (M.bot_lt_of_maximal hNF).ne',
obtain ⟨x, hxM, hx1⟩ := this hM,
refine ⟨x, inv_anti_mono _ _ ((coe_ideal_le_coe_ideal _).mpr hIM) hxM, hx1⟩;
apply fractional_ideal.coe_ideal_ne_zero; assumption },
-- Let `a` be a nonzero element of `M` and `J` the ideal generated by `a`.
intros M hM,
resetI,
obtain ⟨⟨a, haM⟩, ha0⟩ := submodule.nonzero_mem_of_bot_lt (M.bot_lt_of_maximal hNF),
replace ha0 : a ≠ 0 := subtype.coe_injective.ne ha0,
let J : ideal A := ideal.span {a},
have hJ0 : J ≠ ⊥ := mt ideal.span_singleton_eq_bot.mp ha0,
have hJM : J ≤ M := ideal.span_le.mpr (set.singleton_subset_iff.mpr haM),
have hM0 : ⊥ < M := M.bot_lt_of_maximal hNF,
-- Then we can find a product of prime (hence maximal) ideals contained in `J`,
-- such that removing element `M` from the product is not contained in `J`.
obtain ⟨Z, hle, hnle⟩ := exists_multiset_prod_cons_le_and_prod_not_le hNF hJ0 hJM,
-- Choose an element `b` of the product that is not in `J`.
obtain ⟨b, hbZ, hbJ⟩ := set_like.not_le_iff_exists.mp hnle,
have hnz_fa : algebra_map A K a ≠ 0 :=
mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) a) ha0,
have hb0 : algebra_map A K b ≠ 0 :=
mt ((ring_hom.injective_iff _).mp (is_fraction_ring.injective A K) b)
(λ h, hbJ $ h.symm ▸ J.zero_mem),
-- Then `b a⁻¹ : K` is in `M⁻¹` but not in `1`.
refine ⟨algebra_map A K b * (algebra_map A K a)⁻¹, (mem_inv_iff _).mpr _, _⟩,
{ exact (fractional_ideal.coe_to_fractional_ideal_ne_zero le_rfl).mpr hM0.ne' },
{ rintro y₀ hy₀,
obtain ⟨y, h_Iy, rfl⟩ := (fractional_ideal.mem_coe_ideal _).mp hy₀,
rw [mul_comm, ← mul_assoc, ← ring_hom.map_mul],
have h_yb : y * b ∈ J,
{ apply hle,
rw multiset.prod_cons,
exact submodule.smul_mem_smul h_Iy hbZ },
rw ideal.mem_span_singleton' at h_yb,
rcases h_yb with ⟨c, hc⟩,
rw [← hc, ring_hom.map_mul, mul_assoc, mul_inv_cancel hnz_fa, mul_one],
apply fractional_ideal.coe_mem_one },
{ refine mt (fractional_ideal.mem_one_iff _).mp _,
rintros ⟨x', h₂_abs⟩,
rw [← div_eq_mul_inv, eq_div_iff_mul_eq hnz_fa, ← ring_hom.map_mul] at h₂_abs,
have := ideal.mem_span_singleton'.mpr ⟨x', is_fraction_ring.injective A K h₂_abs⟩,
contradiction },
end
lemma one_mem_inv_coe_ideal {I : ideal A} (hI : I ≠ ⊥) :
(1 : K) ∈ (I : fractional_ideal A⁰ K)⁻¹ :=
begin
rw mem_inv_iff (fractional_ideal.coe_ideal_ne_zero hI),
intros y hy,
rw one_mul,
exact coe_ideal_le_one hy,
assumption
end
lemma mul_inv_cancel_of_le_one [h : is_dedekind_domain A]
{I : ideal A} (hI0 : I ≠ ⊥) (hI : ((I * I⁻¹)⁻¹ : fractional_ideal A⁰ K) ≤ 1) :
(I * I⁻¹ : fractional_ideal A⁰ K) = 1 :=
begin
-- Handle a few trivial cases.
by_cases hI1 : I = ⊤,
{ rw [hI1, coe_ideal_top, one_mul, fractional_ideal.one_inv] },
by_cases hNF : is_field A,
{ letI := hNF.to_field A, rcases hI1 (I.eq_bot_or_top.resolve_left hI0) },
-- We'll show a contradiction with `exists_not_mem_one_of_ne_bot`:
-- `J⁻¹ = (I * I⁻¹)⁻¹` cannot have an element `x ∉ 1`, so it must equal `1`.
obtain ⟨J, hJ⟩ : ∃ (J : ideal A), (J : fractional_ideal A⁰ K) = I * I⁻¹ :=
le_one_iff_exists_coe_ideal.mp mul_one_div_le_one,
by_cases hJ0 : J = ⊥,
{ subst hJ0,
refine absurd _ hI0,
rw [eq_bot_iff, ← coe_ideal_le_coe_ideal K, hJ],
exact coe_ideal_le_self_mul_inv K I,
apply_instance },
by_cases hJ1 : J = ⊤,
{ rw [← hJ, hJ1, coe_ideal_top] },
obtain ⟨x, hx, hx1⟩ : ∃ (x : K),
x ∈ (J : fractional_ideal A⁰ K)⁻¹ ∧ x ∉ (1 : fractional_ideal A⁰ K) :=
exists_not_mem_one_of_ne_bot hNF hJ0 hJ1,
contrapose! hx1 with h_abs,
rw hJ at hx,
exact hI hx,
end
/-- Nonzero integral ideals in a Dedekind domain are invertible.
We will use this to show that nonzero fractional ideals are invertible,
and finally conclude that fractional ideals in a Dedekind domain form a group with zero.
-/
lemma coe_ideal_mul_inv [h : is_dedekind_domain A] (I : ideal A) (hI0 : I ≠ ⊥) :
(I * I⁻¹ : fractional_ideal A⁰ K) = 1 :=
begin
-- We'll show `1 ≤ J⁻¹ = (I * I⁻¹)⁻¹ ≤ 1`.
apply mul_inv_cancel_of_le_one hI0,
by_cases hJ0 : (I * I⁻¹ : fractional_ideal A⁰ K) = 0,
{ rw [hJ0, inv_zero'], exact fractional_ideal.zero_le _ },
intros x hx,
-- In particular, we'll show all `x ∈ J⁻¹` are integral.
suffices : x ∈ integral_closure A K,
{ rwa [is_integrally_closed.integral_closure_eq_bot, algebra.mem_bot, set.mem_range,
← fractional_ideal.mem_one_iff] at this;
assumption },
-- For that, we'll find a subalgebra that is f.g. as a module and contains `x`.
-- `A` is a noetherian ring, so we just need to find a subalgebra between `{x}` and `I⁻¹`.
rw mem_integral_closure_iff_mem_fg,
have x_mul_mem : ∀ b ∈ (I⁻¹ : fractional_ideal A⁰ K), x * b ∈ (I⁻¹ : fractional_ideal A⁰ K),
{ intros b hb,
rw mem_inv_iff at ⊢ hx,
swap, { exact fractional_ideal.coe_ideal_ne_zero hI0 },
swap, { exact hJ0 },
simp only [mul_assoc, mul_comm b] at ⊢ hx,
intros y hy,
exact hx _ (fractional_ideal.mul_mem_mul hy hb) },
-- It turns out the subalgebra consisting of all `p(x)` for `p : polynomial A` works.
refine ⟨alg_hom.range (polynomial.aeval x : polynomial A →ₐ[A] K),
is_noetherian_submodule.mp (fractional_ideal.is_noetherian I⁻¹) _ (λ y hy, _),
⟨polynomial.X, polynomial.aeval_X x⟩⟩,
obtain ⟨p, rfl⟩ := (alg_hom.mem_range _).mp hy,
rw polynomial.aeval_eq_sum_range,
refine submodule.sum_mem _ (λ i hi, submodule.smul_mem _ _ _),
clear hi,
induction i with i ih,
{ rw pow_zero, exact one_mem_inv_coe_ideal hI0 },
{ show x ^ i.succ ∈ (I⁻¹ : fractional_ideal A⁰ K),
rw pow_succ, exact x_mul_mem _ ih },
end
/-- Nonzero fractional ideals in a Dedekind domain are units.
This is also available as `_root_.mul_inv_cancel`, using the
`comm_group_with_zero` instance defined below.
-/
protected theorem mul_inv_cancel [is_dedekind_domain A]
{I : fractional_ideal A⁰ K} (hne : I ≠ 0) : I * I⁻¹ = 1 :=
begin
obtain ⟨a, J, ha, hJ⟩ :
∃ (a : A) (aI : ideal A), a ≠ 0 ∧ I = span_singleton A⁰ (algebra_map _ _ a)⁻¹ * aI :=
exists_eq_span_singleton_mul I,
suffices h₂ : I * (span_singleton A⁰ (algebra_map _ _ a) * J⁻¹) = 1,
{ rw mul_inv_cancel_iff,
exact ⟨span_singleton A⁰ (algebra_map _ _ a) * J⁻¹, h₂⟩ },
subst hJ,
rw [mul_assoc, mul_left_comm (J : fractional_ideal A⁰ K), coe_ideal_mul_inv, mul_one,
fractional_ideal.span_singleton_mul_span_singleton, inv_mul_cancel,
fractional_ideal.span_singleton_one],
{ exact mt ((algebra_map A K).injective_iff.mp (is_fraction_ring.injective A K) _) ha },
{ exact fractional_ideal.coe_ideal_ne_zero_iff.mp (right_ne_zero_of_mul hne) }
end
lemma mul_right_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K}
(hJ : J ≠ 0) : ∀ {I I'}, I * J ≤ I' * J ↔ I ≤ I' :=
begin
intros I I',
split,
{ intros h, convert mul_right_mono J⁻¹ h;
rw [mul_assoc, fractional_ideal.mul_inv_cancel hJ, mul_one] },
{ exact λ h, mul_right_mono J h }
end
lemma mul_left_le_iff [is_dedekind_domain A] {J : fractional_ideal A⁰ K}
(hJ : J ≠ 0) {I I'} : J * I ≤ J * I' ↔ I ≤ I' :=
by convert fractional_ideal.mul_right_le_iff hJ using 1; simp only [mul_comm]
lemma mul_right_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K}
(hI : I ≠ 0) : strict_mono (* I) :=
strict_mono_of_le_iff_le (λ _ _, (mul_right_le_iff hI).symm)
lemma mul_left_strict_mono [is_dedekind_domain A] {I : fractional_ideal A⁰ K}
(hI : I ≠ 0) : strict_mono ((*) I) :=
strict_mono_of_le_iff_le (λ _ _, (mul_left_le_iff hI).symm)
/--
This is also available as `_root_.div_eq_mul_inv`, using the
`comm_group_with_zero` instance defined below.
-/
protected lemma div_eq_mul_inv [is_dedekind_domain A] (I J : fractional_ideal A⁰ K) :
I / J = I * J⁻¹ :=
begin
by_cases hJ : J = 0,
{ rw [hJ, div_zero, inv_zero', mul_zero] },
refine le_antisymm ((mul_right_le_iff hJ).mp _) ((le_div_iff_mul_le hJ).mpr _),
{ rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one, mul_le],
intros x hx y hy,
rw [mem_div_iff_of_nonzero hJ] at hx,
exact hx y hy },
rw [mul_assoc, mul_comm J⁻¹, fractional_ideal.mul_inv_cancel hJ, mul_one],
exact le_refl I
end
end fractional_ideal
/-- `is_dedekind_domain` and `is_dedekind_domain_inv` are equivalent ways
to express that an integral domain is a Dedekind domain. -/
theorem is_dedekind_domain_iff_is_dedekind_domain_inv :
is_dedekind_domain A ↔ is_dedekind_domain_inv A :=
⟨λ h I hI, by exactI fractional_ideal.mul_inv_cancel hI, λ h, h.is_dedekind_domain⟩
end inverse
section is_dedekind_domain
variables {R A} [is_dedekind_domain A] [algebra A K] [is_fraction_ring A K]
open fractional_ideal
noncomputable instance fractional_ideal.comm_group_with_zero :
comm_group_with_zero (fractional_ideal A⁰ K) :=
{ inv := λ I, I⁻¹,
inv_zero := inv_zero' _,
div := (/),
div_eq_mul_inv := fractional_ideal.div_eq_mul_inv,
exists_pair_ne := ⟨0, 1, (coe_to_fractional_ideal_injective le_rfl).ne
(by simpa using @zero_ne_one (ideal A) _ _)⟩,
mul_inv_cancel := λ I, fractional_ideal.mul_inv_cancel,
.. fractional_ideal.comm_semiring }
noncomputable instance ideal.cancel_comm_monoid_with_zero :
cancel_comm_monoid_with_zero (ideal A) :=
function.injective.cancel_comm_monoid_with_zero (coe_ideal_hom A⁰ (fraction_ring A))
coe_ideal_injective (ring_hom.map_zero _) (ring_hom.map_one _) (ring_hom.map_mul _)
/-- For ideals in a Dedekind domain, to divide is to contain. -/
lemma ideal.dvd_iff_le {I J : ideal A} : (I ∣ J) ↔ J ≤ I :=
⟨ideal.le_of_dvd,
λ h, begin
by_cases hI : I = ⊥,
{ have hJ : J = ⊥, { rwa [hI, ← eq_bot_iff] at h },
rw [hI, hJ] },
have hI' : (I : fractional_ideal A⁰ (fraction_ring A)) ≠ 0 :=
(fractional_ideal.coe_to_fractional_ideal_ne_zero (le_refl (non_zero_divisors A))).mpr hI,
have : (I : fractional_ideal A⁰ (fraction_ring A))⁻¹ * J ≤ 1 := le_trans
(fractional_ideal.mul_left_mono (↑I)⁻¹ ((coe_ideal_le_coe_ideal _).mpr h))
(le_of_eq (inv_mul_cancel hI')),
obtain ⟨H, hH⟩ := fractional_ideal.le_one_iff_exists_coe_ideal.mp this,
use H,
refine coe_to_fractional_ideal_injective (le_refl (non_zero_divisors A))
(show (J : fractional_ideal A⁰ (fraction_ring A)) = _, from _),
rw [fractional_ideal.coe_ideal_mul, hH, ← mul_assoc, mul_inv_cancel hI', one_mul]
end⟩
lemma ideal.dvd_not_unit_iff_lt {I J : ideal A} :
dvd_not_unit I J ↔ J < I :=
⟨λ ⟨hI, H, hunit, hmul⟩, lt_of_le_of_ne (ideal.dvd_iff_le.mp ⟨H, hmul⟩)
(mt (λ h, have H = 1, from mul_left_cancel₀ hI (by rw [← hmul, h, mul_one]),
show is_unit H, from this.symm ▸ is_unit_one) hunit),
λ h, dvd_not_unit_of_dvd_of_not_dvd (ideal.dvd_iff_le.mpr (le_of_lt h))
(mt ideal.dvd_iff_le.mp (not_le_of_lt h))⟩
instance : wf_dvd_monoid (ideal A) :=
{ well_founded_dvd_not_unit :=
have well_founded ((>) : ideal A → ideal A → Prop) :=
is_noetherian_iff_well_founded.mp
(is_noetherian_ring_iff.mp is_dedekind_domain.is_noetherian_ring),
by { convert this, ext, rw ideal.dvd_not_unit_iff_lt } }
instance ideal.unique_factorization_monoid :
unique_factorization_monoid (ideal A) :=
{ irreducible_iff_prime := λ P,
⟨λ hirr, ⟨hirr.ne_zero, hirr.not_unit, λ I J, begin
have : P.is_maximal,
{ refine ⟨⟨mt ideal.is_unit_iff.mpr hirr.not_unit, _⟩⟩,
intros J hJ,
obtain ⟨J_ne, H, hunit, P_eq⟩ := ideal.dvd_not_unit_iff_lt.mpr hJ,
exact ideal.is_unit_iff.mp ((hirr.is_unit_or_is_unit P_eq).resolve_right hunit) },
rw [ideal.dvd_iff_le, ideal.dvd_iff_le, ideal.dvd_iff_le,
set_like.le_def, set_like.le_def, set_like.le_def],
contrapose!,
rintros ⟨⟨x, x_mem, x_not_mem⟩, ⟨y, y_mem, y_not_mem⟩⟩,
exact ⟨x * y, ideal.mul_mem_mul x_mem y_mem,
mt this.is_prime.mem_or_mem (not_or x_not_mem y_not_mem)⟩,
end⟩,
prime.irreducible⟩,
.. ideal.wf_dvd_monoid }
noncomputable instance ideal.normalization_monoid : normalization_monoid (ideal A) :=
normalization_monoid_of_unique_units
@[simp] lemma ideal.dvd_span_singleton {I : ideal A} {x : A} :
I ∣ ideal.span {x} ↔ x ∈ I :=
ideal.dvd_iff_le.trans (ideal.span_le.trans set.singleton_subset_iff)
lemma ideal.is_prime_of_prime {P : ideal A} (h : prime P) : is_prime P :=
begin
refine ⟨_, λ x y hxy, _⟩,
{ unfreezingI { rintro rfl },
rw ← ideal.one_eq_top at h,
exact h.not_unit is_unit_one },
{ simp only [← ideal.dvd_span_singleton, ← ideal.span_singleton_mul_span_singleton] at ⊢ hxy,
exact h.dvd_or_dvd hxy }
end
theorem ideal.prime_of_is_prime {P : ideal A} (hP : P ≠ ⊥) (h : is_prime P) : prime P :=
begin
refine ⟨hP, mt ideal.is_unit_iff.mp h.ne_top, λ I J hIJ, _⟩,
simpa only [ideal.dvd_iff_le] using (h.mul_le.mp (ideal.le_of_dvd hIJ)),
end
/-- In a Dedekind domain, the (nonzero) prime elements of the monoid with zero `ideal A`
are exactly the prime ideals. -/
theorem ideal.prime_iff_is_prime {P : ideal A} (hP : P ≠ ⊥) :
prime P ↔ is_prime P :=
⟨ideal.is_prime_of_prime, ideal.prime_of_is_prime hP⟩
end is_dedekind_domain
section is_integral_closure
/-! ### `is_integral_closure` section
We show that an integral closure of a Dedekind domain in a finite separable
field extension is again a Dedekind domain. This implies the ring of integers
of a number field is a Dedekind domain. -/
open algebra
open_locale big_operators
variables {A K} [algebra A K] [is_fraction_ring A K]
variables {L : Type*} [field L] (C : Type*) [comm_ring C]
variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L]
variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L]
lemma is_integral_closure.range_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
((algebra.linear_map C L).restrict_scalars A).range ≤
submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
rintros _ ⟨x, rfl⟩,
simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply],
have hx : is_integral A (algebra_map C L x) :=
(is_integral_closure.is_integral A L x).algebra_map,
suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i,
{ obtain ⟨c, x_eq⟩ := this,
rw x_eq,
refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)),
rw set.mem_range,
exact ⟨i, rfl⟩ },
suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i),
{ obtain ⟨c, hc, hx⟩ := this,
have hc' : ∀ i, is_localization.is_integer A (c i) :=
λ i, is_integrally_closed.is_integral_iff.mp (hc i),
use λ i, classical.some (hc' i),
refine hx.trans (finset.sum_congr rfl (λ i _, _)),
conv_lhs { rw [← classical.some_spec (hc' i)] },
rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] },
refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩,
rw bilin_form.dual_basis_repr_apply,
exact is_integral_trace (is_integral_mul hx (hb_int i))
end
lemma integral_closure_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
(integral_closure A L).to_submodule ≤ submodule.span A (set.range $
(trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int),
intros x hx,
exact ⟨⟨x, hx⟩, rfl⟩
end
variables (A) (K)
include K
/-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R`
to `(y : R) • x ∈ integral_closure R L`. -/
lemma exists_integral_multiples (s : finset L) :
∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) :=
begin
haveI := classical.dec_eq L,
refine s.induction _ _,
{ use [1, one_ne_zero],
rintros x ⟨⟩ },
{ rintros x s hx ⟨y, hy, hs⟩,
obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple
((is_fraction_ring.is_algebraic_iff A K L).mpr (is_algebraic_of_finite _ _ x))
((algebra_map A L).injective_iff.mp _),
refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩,
rcases finset.mem_insert.mp hx'' with (rfl | hx''),
{ rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'],
exact is_integral_mul is_integral_algebra_map x'.2 },
{ rw [mul_comm, mul_smul, algebra.smul_def],
exact is_integral_mul is_integral_algebra_map (hs _ hx'') },
{ rw is_scalar_tower.algebra_map_eq A K L,
apply (algebra_map K L).injective.comp,
exact is_fraction_ring.injective _ _ } }
end
variables (L)
/-- If `L` is a finite extension of `K = Frac(A)`,
then `L` has a basis over `A` consisting of integral elements. -/
lemma finite_dimensional.exists_is_basis_integral :
∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) :=
begin
letI := classical.dec_eq L,
letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance,
let s' := is_noetherian.finset_basis_index K L,
let bs' := is_noetherian.finset_basis K L,
obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'),
have hy' : algebra_map A L y ≠ 0,
{ refine mt ((algebra_map A L).injective_iff.mp _ _) hy,
rw is_scalar_tower.algebra_map_eq A K L,
exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) },
refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x,
inv_fun := λ x, (algebra_map A L y)⁻¹ * x,
left_inv := _,
right_inv := _,
.. algebra.lmul _ _ (algebra_map A L y) },
_⟩,
{ intros x, simp only [inv_mul_cancel_left₀ hy'] },
{ intros x, simp only [mul_inv_cancel_left₀ hy'] },
{ rintros ⟨x', hx'⟩,
simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his',
simp only [basis.map_apply, linear_equiv.coe_mk],
exact his' _ ⟨_, rfl⟩ }
end
variables (A K L) [is_separable K L]
include L
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure `C` of `A` in `L` is
Noetherian. -/
lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring C :=
begin
haveI := classical.dec_eq L,
obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L,
rw is_noetherian_ring_iff,
let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
letI := is_noetherian_span_of_finite A (set.finite_range b'),
let f : C →ₗ[A] submodule.span A (set.range b') :=
(submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp
((algebra.linear_map C L).restrict_scalars A).range_restrict,
refine is_noetherian_of_tower A (is_noetherian_of_ker_bot f _),
rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict],
exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L)
end
variables {A K}
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure of `A` in `L` is
Noetherian. -/
lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring (integral_closure A L) :=
is_integral_closure.is_noetherian_ring A K L (integral_closure A L)
variables (A K) [is_domain C]
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure `C` of `A` in `L` is a Dedekind domain.
Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`
and `C := integral_closure A L`.
-/
lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain C :=
begin
haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C,
exact
⟨is_integral_closure.is_noetherian_ring A K L C,
h.dimension_le_one.is_integral_closure _ L _,
(is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x
(is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx),
is_integral_closure.algebra_map_mk' _ _ _⟩)⟩
end
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
Can't be an instance since `K` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`.
-/
lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain (integral_closure A L) :=
is_integral_closure.is_dedekind_domain A K L (integral_closure A L)
omit K
variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L]
variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L]
/- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
See also the lemma `integral_closure.is_dedekind_domain` where you can choose
the field of fractions yourself.
-/
instance integral_closure.is_dedekind_domain_fraction_ring
[is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) :=
integral_closure.is_dedekind_domain A (fraction_ring A) L
end is_integral_closure
section is_dedekind_domain
variables {T : Type*} [comm_ring T] [is_domain T] [is_dedekind_domain T] (I J : ideal T)
open_locale classical
open multiset unique_factorization_monoid ideal
lemma prod_normalized_factors_eq_self {I : ideal T} (hI : I ≠ ⊥) :
(normalized_factors I).prod = I :=
associated_iff_eq.1 (normalized_factors_prod hI)
lemma normalized_factors_prod {α : multiset (ideal T)}
(h : ∀ p ∈ α, prime p) : normalized_factors α.prod = α :=
by { simp_rw [← multiset.rel_eq, ← associated_eq_eq],
exact prime_factors_unique (prime_of_normalized_factor) h
(normalized_factors_prod (α.prod_ne_zero_of_prime h)) }
lemma count_le_of_ideal_ge {I J : ideal T} (h : I ≤ J) (hI : I ≠ ⊥) (K : ideal T) :
count K (normalized_factors J) ≤ count K (normalized_factors I) :=
le_iff_count.1 ((dvd_iff_normalized_factors_le_normalized_factors (ne_bot_of_le_ne_bot hI h) hI).1
(dvd_iff_le.2 h)) _
lemma sup_eq_prod_inf_factors (hI : I ≠ ⊥) (hJ : J ≠ ⊥) :
I ⊔ J = (normalized_factors I ∩ normalized_factors J).prod :=
begin
have H : normalized_factors (normalized_factors I ∩ normalized_factors J).prod =
normalized_factors I ∩ normalized_factors J,
{ apply _root_.normalized_factors_prod,
intros p hp,
rw mem_inter at hp,
exact prime_of_normalized_factor p hp.left },
have := (multiset.prod_ne_zero_of_prime (normalized_factors I ∩ normalized_factors J)
(λ _ h, prime_of_normalized_factor _ (multiset.mem_inter.1 h).1)),
apply le_antisymm,
{ rw [sup_le_iff, ← dvd_iff_le, ← dvd_iff_le],
split,
{ rw [dvd_iff_normalized_factors_le_normalized_factors this hI, H],
exact inf_le_left },
{ rw [dvd_iff_normalized_factors_le_normalized_factors this hJ, H],
exact inf_le_right } },
{ rw [← dvd_iff_le, dvd_iff_normalized_factors_le_normalized_factors,
_root_.normalized_factors_prod, le_iff_count],
{ intro a,
rw multiset.count_inter,
exact le_min (count_le_of_ideal_ge le_sup_left hI a)
(count_le_of_ideal_ge le_sup_right hJ a) },
{ intros p hp,
rw mem_inter at hp,
exact prime_of_normalized_factor p hp.left },
{ exact ne_bot_of_le_ne_bot hI le_sup_left },
{ exact this } },
end
end is_dedekind_domain
|
0aad0b72f9ec9f4b91604fd013d3854beb9f74d7 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/group_theory/abelianization.lean | df7dc9e81030bacb77279dbe42a6c68e1103faf0 | [
"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,526 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Michael Howes
The functor Grp → Ab which is the left adjoint
of the forgetful functor Ab → Grp.
-/
import group_theory.quotient_group
import tactic.group
universes u v
-- let G be a group
variables (G : Type u) [group G]
/-- The commutator subgroup of a group G is the normal subgroup
generated by the commutators [p,q]=`p*q*p⁻¹*q⁻¹` -/
@[derive subgroup.normal]
def commutator : subgroup G :=
subgroup.normal_closure {x | ∃ p q, p * q * p⁻¹ * q⁻¹ = x}
/-- The abelianization of G is the quotient of G by its commutator subgroup -/
def abelianization : Type u :=
quotient_group.quotient (commutator G)
namespace abelianization
local attribute [instance] quotient_group.left_rel
instance : comm_group (abelianization G) :=
{ mul_comm := λ x y, quotient.induction_on₂' x y $ λ a b,
begin
apply quotient.sound,
apply subgroup.subset_normal_closure,
use b⁻¹, use a⁻¹,
group,
end,
.. quotient_group.group _ }
instance : inhabited (abelianization G) := ⟨1⟩
variable {G}
/-- `of` is the canonical projection from G to its abelianization. -/
def of : G →* abelianization G :=
{ to_fun := quotient_group.mk,
map_one' := rfl,
map_mul' := λ x y, rfl }
section lift
-- so far -- built Gᵃᵇ and proved it's an abelian group.
-- defined `of : G → Gᵃᵇ`
-- let A be an abelian group and let f be a group hom from G to A
variables {A : Type v} [comm_group A] (f : G →* A)
lemma commutator_subset_ker : commutator G ≤ f.ker :=
begin
apply subgroup.normal_closure_le_normal,
-- FIXME why is the apply_instance needed?
{ apply_instance },
{ rintros x ⟨p, q, rfl⟩,
simp [monoid_hom.mem_ker, mul_right_comm (f p) (f q)] }
end
def lift : abelianization G →* A :=
quotient_group.lift _ f (λ x h, f.mem_ker.2 $ commutator_subset_ker _ h)
@[simp] lemma lift.of (x : G) : lift f (of x) = f x :=
rfl
theorem lift.unique
(φ : abelianization G →* A)
-- hφ : φ agrees with f on the image of G in Gᵃᵇ
(hφ : ∀ (x : G), φ (of x) = f x)
{x : abelianization G} :
φ x = lift f x :=
quotient_group.induction_on x hφ
end lift
variables {A : Type v} [monoid A]
theorem hom_ext (φ ψ : abelianization G →* A)
(h : φ.comp of = ψ.comp of) : φ = ψ :=
begin
ext x,
apply quotient_group.induction_on x,
intro z,
show φ.comp of z = _,
rw h,
refl,
end
end abelianization
|
b42929b89bcb9f5247d92b60f1b94651e42d9882 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/topology/bases.lean | d9d268c7e06c743a652ba1a5ce1e9e8cb40c41ca | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 12,431 | 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
Bases of topologies. Countability axioms.
-/
import topology.constructions
open set filter classical
open_locale topological_space filter
namespace topological_space
/- countability axioms
For our applications we are interested that there exists a countable basis, but we do not need the
concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins.
-/
universe u
variables {α : Type u} [t : topological_space α]
include t
/-- A topological basis is one that satisfies the necessary conditions so that
it suffices to take unions of the basis sets to get a topology (without taking
finite intersections as well). -/
def is_topological_basis (s : set (set α)) : Prop :=
(∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧
(⋃₀ s) = univ ∧
t = generate_from s
lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) :
is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) :=
let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty} in
⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩,
have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union,
eq₁ ▸ eq₂ ▸ assume x h,
⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b,
ie.symm ▸ ⟨_, h⟩⟩, ie⟩, h, subset.refl _⟩,
eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _,
by rw sInter_empty; exact ⟨a, mem_univ a⟩⟩, sInter_empty⟩, mem_univ _⟩,
have generate_from s = generate_from b',
from le_antisymm
(le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩,
eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs))
(le_generate_from $ assume s hs,
s.eq_empty_or_nonempty.elim
(assume : s = ∅, by rw [this]; apply @is_open_empty _ _)
(assume : s.nonempty, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs,
by rwa sInter_singleton⟩, sInter_singleton s⟩)),
this ▸ hs⟩
lemma is_topological_basis_of_open_of_nhds {s : set (set α)}
(h_open : ∀ u ∈ s, is_open u)
(h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) :
is_topological_basis s :=
⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩,
h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩
(is_open_inter (h_open _ ht₁) (h_open _ ht₂)),
eq_univ_iff_forall.2 $ assume a,
let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial is_open_univ in
⟨u, h₁, h₂⟩,
le_antisymm
(le_generate_from h_open)
(assume u hu,
(@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau,
let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in
by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩
lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)}
(hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s :=
begin
change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s,
rw [hb.2.2, nhds_generate_from, binfi_sets_eq],
{ simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl },
{ exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩,
have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩,
let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in
⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)),
le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ },
{ rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩,
exact ⟨i, h2, h1⟩ }
end
lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)}
(hb : is_topological_basis b) (hs : s ∈ b) : is_open s :=
is_open_iff_mem_nhds.2 $ λ a as,
(mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩
lemma mem_basis_subset_of_mem_open {b : set (set α)}
(hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u)
(ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u :=
(mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au
lemma sUnion_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : is_open u) :
∃ S ⊆ B, u = ⋃₀ S :=
⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a,
⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in
⟨b, ⟨hb, bu⟩, ab⟩,
λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩
lemma Union_basis_of_is_open {B : set (set α)}
(hB : is_topological_basis B) {u : set α} (ou : is_open u) :
∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B :=
let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in
⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩
variables (α)
/-- A separable space is one with a countable dense subset. -/
class separable_space : Prop :=
(exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ)
/-- A first-countable space is one in which every point has a
countable neighborhood basis. -/
class first_countable_topology : Prop :=
(nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated)
namespace first_countable_topology
variable {α}
lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) :
∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) :=
(nhds_generated_countable x).subseq_tendsto hx
end first_countable_topology
/-- A second-countable space is one with a countable basis. -/
class second_countable_topology : Prop :=
(is_open_generated_countable [] : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b)
@[priority 100] -- see Note [lower instance priority]
instance second_countable_topology.to_first_countable_topology
[second_countable_topology α] : first_countable_topology α :=
let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in
⟨begin
intros,
rw [eq, nhds_generate_from],
exact is_countably_generated_binfi_principal (hb.mono (assume x, and.right)),
end⟩
lemma second_countable_topology_induced (β)
[t : topological_space β] [second_countable_topology β] (f : α → β) :
@second_countable_topology α (t.induced f) :=
begin
rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩,
refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ },
rw [eq, induced_generate_from_eq]
end
instance subtype.second_countable_topology
(s : set α) [second_countable_topology α] : second_countable_topology s :=
second_countable_topology_induced s α coe
lemma is_open_generated_countable_inter [second_countable_topology α] :
∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b :=
let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in
let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in
⟨b',
((countable_set_of_finite_subset hb₁).mono
(by { simp only [← and_assoc], apply inter_subset_left })).image _,
assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp),
is_topological_basis_of_subbasis hb₂⟩
/- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/
instance {β : Type*} [topological_space β]
[second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) :=
⟨let ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩ := is_open_generated_countable_inter α in
let ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩ := is_open_generated_countable_inter β in
⟨{g | ∃u∈a, ∃v∈b, g = set.prod u v},
have {g | ∃u∈a, ∃v∈b, g = set.prod u v} = (⋃u∈a, ⋃v∈b, {set.prod u v}),
by apply set.ext; simp,
by rw [this]; exact (ha₁.bUnion $ assume u hu, hb₁.bUnion $ by simp),
by rw [ha₅, hb₅, prod_generate_from_generate_from_eq ha₄ hb₄]⟩⟩
instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*}
[fintype ι] [t : ∀a, topological_space (π a)] [sc : ∀a, second_countable_topology (π a)] :
second_countable_topology (∀a, π a) :=
have ∀i, ∃b : set (set (π i)), countable b ∧ ∅ ∉ b ∧ is_topological_basis b, from
assume a, @is_open_generated_countable_inter (π a) _ (sc a),
let ⟨g, hg⟩ := classical.axiom_of_choice this in
have t = (λa, generate_from (g a)), from funext $ assume a, (hg a).2.2.2.2,
begin
constructor,
refine ⟨pi univ '' pi univ g, countable.image _ _, _⟩,
{ suffices : countable {f : Πa, set (π a) | ∀a, f a ∈ g a}, { simpa [pi] },
exact countable_pi (assume i, (hg i).1), },
rw [this, pi_generate_from_eq_fintype],
{ congr' 1, ext f, simp [pi, eq_comm] },
exact assume a, (hg a).2.2.2.1
end
@[priority 100] -- see Note [lower instance priority]
instance second_countable_topology.to_separable_space
[second_countable_topology α] : separable_space α :=
let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in
have nhds_eq : ∀a, 𝓝 a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, 𝓟 s.val),
by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl,
have ∀s∈b, set.nonempty s,
from assume s hs, ne_empty_iff_nonempty.1 $ λ eq, absurd hs (eq.symm ▸ hb₂),
have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simpa only [skolem, set.nonempty] using this,
let ⟨f, hf⟩ := this in
⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}),
hb₁.bUnion (λ _ _, countable_Union_Prop $ λ _, countable_singleton _),
set.ext $ assume a,
have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial,
let ⟨t, ht₁, ht₂⟩ := this in
have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩,
suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), 𝓟 (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥,
by simpa only [closure_eq_cluster_pts, cluster_pt, nhds_eq, infi_inf w, inf_principal,
mem_set_of_eq, mem_univ, iff_true],
infi_ne_bot_of_directed ⟨a⟩
(assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩,
have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩,
let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in
⟨⟨s₃, has₃, hs₃⟩, begin
simp only [le_principal_iff, mem_principal_sets, (≥)],
simp only [subset_inter_iff] at hs, split;
apply inter_subset_inter_left; simp only [hs]
end⟩)
(assume ⟨s, has, hs⟩,
have (s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h})).nonempty,
from ⟨_, hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩,
principal_ne_bot_iff.2 this) ⟩⟩
variables {α}
lemma is_open_Union_countable [second_countable_topology α]
{ι} (s : ι → set α) (H : ∀ i, is_open (s i)) :
∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i :=
let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in
begin
let B' := {b ∈ B | ∃ i, b ⊆ s i},
choose f hf using λ b:B', b.2.2,
haveI : encodable B' := (cB.mono (sep_subset _ _)).to_encodable,
refine ⟨_, countable_range f,
subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩,
rintro _ ⟨i, rfl⟩ x xs,
rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩,
exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩
end
lemma is_open_sUnion_countable [second_countable_topology α]
(S : set (set α)) (H : ∀ s ∈ S, is_open s) :
∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S :=
let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in
⟨subtype.val '' T, cT.image _,
image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs,
by rwa [sUnion_image, sUnion_eq_Union]⟩
end topological_space
|
ce70843bce1f550aea0ef28eca6db6dacec9d039 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/meta/expr.lean | bf556b9393c31e020f0635ee46d8344df86a97a9 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 48,475 | 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 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
-/
open tactic
attribute [derive has_reflect, derive decidable_eq] binder_info congr_arg_kind
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
/-- Like `++`, except that if the right argument starts with `_root_` the namespace will be
ignored.
```
append_namespace `a.b `c.d = `a.b.c.d
append_namespace `a.b `_root_.c.d = `c.d
```
-/
meta def append_namespace (ns : name) : name → name
| (mk_string s anonymous) := if s = "_root_" then anonymous else mk_string s ns
| (mk_string s p) := mk_string s (append_namespace p)
| (mk_numeral n p) := mk_numeral n (append_namespace p)
| anonymous := ns
/--
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
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)))
/--
`int.to_pexpr n` creates a `pexpr` that will evaluate to `n`.
The `pexpr` does not hold any typing information:
`to_expr ``((%%(int.to_pexpr (-5)) : ℚ))` will create a native `ℚ` numeral `(-5 : ℚ)`.
-/
meta def int.to_pexpr : ℤ → pexpr
| (int.of_nat k) := k.to_pexpr
| (int.neg_succ_of_nat k) := ``(-%%((k+1).to_pexpr))
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 `pexpr` -/
namespace pexpr
/--
If `e` is an annotation of `frozen_name` to `expr.const n`,
`e.get_frozen_name` returns `n`.
Otherwise, returns `name.anonymous`.
-/
meta def get_frozen_name (e : pexpr) : name :=
match e.is_annotation with
| some (`frozen_name, expr.const n _) := n
| _ := name.anonymous
end
/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_fn_args` returns `(f, [e₁, ... eₙ])`.
See also `expr.get_app_fn_args`.
-/
meta def get_app_fn_args : pexpr → opt_param (list pexpr) [] → pexpr × list pexpr
| (expr.app e1 e2) r := get_app_fn_args e1 (e2::r)
| e1 r := (e1, r)
/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_fn` returns `f`.
See also `expr.get_app_fn`.
-/
meta def get_app_fn : pexpr → list pexpr :=
prod.snd ∘ get_app_fn_args
/--
If `e : pexpr` is a sequence of applications `f e₁ e₂ ... eₙ`,
`e.get_app_args` returns `[e₁, ... eₙ]`.
See also `expr.get_app_args`.
-/
meta def get_app_args : pexpr → list pexpr :=
prod.snd ∘ get_app_fn_args
end pexpr
/-! ### Declarations about `expr` -/
namespace expr
/-- 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 name` containing the constant names of an `expr` in the same order
that `expr.fold` traverses it. -/
meta def list_constant' (e : expr) : list name :=
(e.fold [] (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)).reverse
/-- 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`.
See also `name.contains_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
/-- 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
/-- `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
/--
`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
|
df116e7db67225aa06f6bb5977b3735e2ec4677f | 4a092885406df4e441e9bb9065d9405dacb94cd8 | /src/for_mathlib/data/set/finite.lean | 9b0d6178c497ef6583df67623c30cb0d897cdb4f | [
"Apache-2.0"
] | permissive | semorrison/lean-perfectoid-spaces | 78c1572cedbfae9c3e460d8aaf91de38616904d8 | bb4311dff45791170bcb1b6a983e2591bee88a19 | refs/heads/master | 1,588,841,765,494 | 1,554,805,620,000 | 1,554,805,620,000 | 180,353,546 | 0 | 1 | null | 1,554,809,880,000 | 1,554,809,880,000 | null | UTF-8 | Lean | false | false | 88 | lean |
import data.set.finite
attribute [instance] set.fintype_seq -- should move to mathlib
|
d082c90f6c6a4c54f91d450e12c31aede67034c3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /archive/oxford_invariants/2021summer/week3_p1.lean | cf1d4fe0e3ed0cd3a06806499446a2f83c3f53ff | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,906 | 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 algebra.big_operators.order
import algebra.big_operators.ring
import algebra.char_zero.lemmas
import data.rat.cast
/-!
# The Oxford Invariants Puzzle Challenges - Summer 2021, Week 3, Problem 1
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
## Original statement
Let `n ≥ 3`, `a₁, ..., aₙ` be strictly positive integers such that `aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` for
`i = 2, ..., n - 1`. Show that $\sum_{i=1}^{n-1}\dfrac{a_0a_n}{a_ia_{i+1}} ∈ \mathbb N$.
## Comments
Mathlib is based on type theory, so saying that a rational is a natural doesn't make sense. Instead,
we ask that there exists `b : ℕ` whose cast to `α` is the sum we want.
In mathlib, `ℕ` starts at `0`. To make the indexing cleaner, we use `a₀, ..., aₙ₋₁` instead of
`a₁, ..., aₙ`. Similarly, it's nicer to not use subtraction of naturals, so we replace
`aᵢ ∣ aᵢ₋₁ + aᵢ₊₁` by `aᵢ₊₁ ∣ aᵢ + aᵢ₊₂`.
We don't actually have to work in `ℚ` or `ℝ`. We can be even more general by stating the result for
any linearly ordered field.
Instead of having `n` naturals, we use a function `a : ℕ → ℕ`.
In the proof itself, we replace `n : ℕ, 1 ≤ n` by `n + 1`.
The statement is actually true for `n = 0, 1` (`n = 1, 2` before the reindexing) as the sum is
simply `0` and `1` respectively. So the version we prove is slightly more general.
Overall, the indexing is a bit of a mess to understand. But, trust Lean, it works.
## Formalised statement
Let `n : ℕ`, `a : ℕ → ℕ`, `∀ i ≤ n, 0 < a i`, `∀ i, i + 2 ≤ n → aᵢ₊₁ ∣ aᵢ + aᵢ₊₂` (read `→` as
"implies"). Then there exists `b : ℕ` such that `b` as an element of any linearly ordered field
equals $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$.
## Proof outline
The case `n = 0` is trivial.
For `n + 1`, we prove the result by induction but by adding `aₙ₊₁ ∣ aₙ * b - a₀` to the induction
hypothesis, where `b` is the previous sum, $\sum_{i=0}^{n-1} (a_0 a_n) / (a_i a_{i+1})$, as a
natural.
* Base case:
* $\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1})$ is a natural:
$\sum_{i=0}^0 (a_0 a_{0+1}) / (a_0 a_{0+1}) = (a_0 a_1) / (a_0 a_1) = 1$.
* Divisibility condition:
`a₀ * 1 - a₀ = 0` is clearly divisible by `a₁`.
* Induction step:
* $\sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1})$ is a natural:
$$\sum_{i=0}^{n+1} (a_0 a_{n+2}) / (a_i a_{i+1})
= \sum_{i=0}^n\ (a_0 a_{n+2}) / (a_i a_{i+1}) + (a_0 a_{n+2}) / (a_{n+1} a_{n+2})
= a_{n+2} / a_{n+1} × \sum_{i=0}^n (a_0 a_{n+1}) / (a_i a_{i+1}) + a_0 / a_{n+1}
= a_{n+2} / a_{n+1} × b + a_0 / a_{n+1}
= (a_n + a_{n+2}) / a_{n+1} × b - (a_n b - a_0)(a_{n+1})$$
which is a natural because `(aₙ + aₙ₊₂)/aₙ₊₁`, `b` and `(aₙ * b - a₀)/aₙ₊₁` are (plus an
annoying inequality, or the fact that the original sum is positive because its terms are).
* Divisibility condition:
`aₙ₊₁ * ((aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁) - a₀ = aₙ₊₁aₙ₊₂b` is divisible by `aₙ₊₂`.
-/
open_locale big_operators
variables {α : Type*} [linear_ordered_field α]
theorem oxford_invariants.week3_p1 (n : ℕ) (a : ℕ → ℕ) (a_pos : ∀ i ≤ n, 0 < a i)
(ha : ∀ i, i + 2 ≤ n → a (i + 1) ∣ a i + a (i + 2)) :
∃ b : ℕ, (b : α) = ∑ i in finset.range n, (a 0 * a n)/(a i * a (i + 1)) :=
begin
-- Treat separately `n = 0` and `n ≥ 1`
cases n,
/- Case `n = 0`
The sum is trivially equal to `0` -/
{ exact ⟨0, by rw [nat.cast_zero, finset.sum_range_zero]⟩ }, -- `⟨Claim it, Prove it⟩`
/- Case `n ≥ 1`. We replace `n` by `n + 1` everywhere to make this inequality explicit
Set up the stronger induction hypothesis -/
rsuffices ⟨b, hb, -⟩ :
∃ b : ℕ, (b : α) = ∑ i in finset.range (n + 1), (a 0 * a (n + 1)) / (a i * a (i + 1))
∧ a (n + 1) ∣ a n * b - a 0,
{ exact ⟨b, hb⟩ },
simp_rw ←@nat.cast_pos α at a_pos,
/- Declare the induction
`ih` will be the induction hypothesis -/
induction n with n ih,
/- Base case
Claim that the sum equals `1`-/
{ refine ⟨1, _, _⟩,
-- Check that this indeed equals the sum
{ rw [nat.cast_one, finset.sum_range_one, div_self],
exact (mul_pos (a_pos 0 (nat.zero_le _)) (a_pos 1 (nat.zero_lt_succ _))).ne' },
-- Check the divisibility condition
{ rw [mul_one, tsub_self],
exact dvd_zero _ } },
/- Induction step
`b` is the value of the previous sum as a natural, `hb` is the proof that it is indeed the value,
and `han` is the divisibility condition -/
obtain ⟨b, hb, han⟩ := ih (λ i hi, ha i $ nat.le_succ_of_le hi)
(λ i hi, a_pos i $ nat.le_succ_of_le hi),
specialize ha n le_rfl,
have ha₀ : a 0 ≤ a n * b, -- Needing this is an artifact of `ℕ`-subtraction.
{ rw [←@nat.cast_le α, nat.cast_mul, hb, ←div_le_iff' (a_pos _ $ n.le_succ.trans $ nat.le_succ _),
←mul_div_mul_right _ _ (a_pos _ $ nat.le_succ _).ne'],
suffices h : ∀ i, i ∈ finset.range (n + 1) → 0 ≤ (a 0 : α) * a (n + 1) / (a i * a (i + 1)),
{ exact finset.single_le_sum h (finset.self_mem_range_succ n) },
refine (λ i _, div_nonneg _ _); refine mul_nonneg _ _; exact nat.cast_nonneg _ },
-- Claim that the sum equals `(aₙ + aₙ₊₂)/aₙ₊₁ * b - (aₙ * b - a₀)/aₙ₊₁`
refine ⟨(a n + a (n + 2))/ a (n + 1) * b - (a n * b - a 0) / a (n + 1), _, _⟩,
-- Check that this indeed equals the sum
{ calc
(((a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : ℕ) : α)
= (a n + a (n + 2)) / a (n + 1) * b - (a n * b - a 0) / a (n + 1) : begin
norm_cast,
rw nat.cast_sub (nat.div_le_of_le_mul _),
rw [←mul_assoc, nat.mul_div_cancel' ha, add_mul],
exact tsub_le_self.trans (nat.le_add_right _ _),
end
... = a (n + 2) / a (n + 1) * b + (a 0 * a (n + 2)) / (a (n + 1) * a (n + 2))
: by rw [add_div, add_mul, sub_div, mul_div_right_comm, add_sub_sub_cancel,
mul_div_mul_right _ _ (a_pos _ le_rfl).ne']
... = ∑ (i : ℕ) in finset.range (n + 2), a 0 * a (n + 2) / (a i * a (i + 1))
: begin
rw [finset.sum_range_succ, hb, finset.mul_sum],
congr, ext i,
rw [←mul_div_assoc, ←mul_div_right_comm, mul_div_assoc, mul_div_cancel _
(a_pos _ $ nat.le_succ _).ne', mul_comm],
end },
-- Check the divisibility condition
{ rw [mul_tsub, ← mul_assoc, nat.mul_div_cancel' ha, add_mul,
nat.mul_div_cancel' han, add_tsub_tsub_cancel ha₀, add_tsub_cancel_right],
exact dvd_mul_right _ _ }
end
|
a5407af7424e237eede0df6e697bb62d09152a3a | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/linear_algebra/finite_dimensional.lean | 7e7bea062fa8ef2b06013afb2f199065c24c25db | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 16,954 | 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
/-!
# 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_finite_basis` states that the existence of a finite basis 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_finite_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.val_range],
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 function `subtype.val`).
-/
variables (K V)
lemma exists_is_basis_finite [finite_dimensional K V] :
∃ s : set V, (is_basis K (subtype.val : s → V)) ∧ s.finite :=
begin
cases exists_is_basis K V with s hs,
exact ⟨s, hs, finite_of_linear_independent hs.1⟩
end
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_finite_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} ⟩
/-- 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] : ℕ :=
if h : dim K V < omega.{v} then classical.some (lt_omega.1 h) else 0
/-- 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 :=
begin
have : findim K V = classical.some (lt_omega.1 (dim_lt_omega K V)) :=
dif_pos (dim_lt_omega K V),
rw this,
exact (classical.some_spec (lt_omega.1 (dim_lt_omega K V))).symm
end
/-- 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 zero_ne_one)]
/-- 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_finite_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 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.val_range, ← this, set.set_of_mem_eq, ← subtype_eq_val, span_image],
have := hbS.2,
erw [subtype.val_range, set.set_of_mem_eq] 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
/-- The vector space of functions on a fintype has finite dimension. -/
instance finite_dimensional_fintype_fun {ι : Type*} [fintype ι] :
finite_dimensional K (ι → K) :=
by { rw [finite_dimensional_iff_dim_lt_omega, dim_fun'], exact nat_lt_omega _ }
/-- 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
end finite_dimensional
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) }⟩
/-- 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 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 _ _ }
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,
rcases exists_is_basis_finite K V with ⟨s, s_basis, s_finite⟩,
letI : fintype s := s_finite.fintype,
have A : findim K V = fintype.card s := findim_eq_card_basis s_basis,
have : is_basis K (λx:s, f (subtype.val x)) := f.is_basis s_basis,
have B : findim K V₂ = fintype.card s := findim_eq_card_basis this,
rw [A, B]
end
end linear_equiv
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_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,
injective_of_has_left_inverse ⟨g, left_inverse_of_surjective_of_right_inverse
(surjective_of_injective (injective_of_left_inverse this)) this⟩⟩
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 injective_of_has_left_inverse
⟨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
|
1be6afb999f282d8f5095b8054c2493eae19dc5e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/playground/cmdparsertest1.lean | 44a7e0f1a328cd743e766d199554607976108794 | [
"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,195 | lean | import Lean.Parser.Command
open Lean
open Lean.Parser
def testParser (input : String) : IO Unit :=
do
env ← mkEmptyEnvironment;
cmdPTables ← builtinCommandParsingTable.get;
stx ← IO.ofExcept $ runParser env cmdPTables input "<input>" "command";
IO.println stx
def test (is : List String) : IO Unit :=
is.mfor $ fun input => do
IO.println input;
testParser input
def main (xs : List String) : IO Unit :=
do
IO.println Command.declaration.info.firstTokens;
test [
"@[inline] def x := 2",
"protected def length.{u} {α : Type u} : List α → Nat
| [] := 0
| (a::as) := 1 + length as",
"/-- doc string test -/ private theorem bla (x : Nat) : x = x := Eq.refl x",
"class Alternative (f : Type u → Type v) extends Applicative f : Type (max (u+1) v) :=
(failure : ∀ {α : Type u}, f α)
(orelse : ∀ {α : Type u}, f α → f α → f α)
",
"local attribute [instance] foo bla",
"attribute [inline] test",
"open Lean (hiding Name)",
"reserve infixr ` ∨ `:30",
"reserve prefix `¬`:40",
"infixr ` ^ ` := Pow.pow",
"notation f ` $ `:1 a:0 := f a",
"notation `Prop` := Sort 0",
"notation `∅` := EmptyCollection.emptyc _",
"notation `⟦`:max a `⟧`:0 := Quotient.mk a"
]
|
b0a3341aa4047bb08e96ca6ec8daeb678715aa9b | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/ring_theory/local_properties.lean | cb3e04017c5dbb47042e22aba51c8ab865f1d201 | [
"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 | 28,809 | lean | /-
Copyright (c) 2021 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import group_theory.submonoid.pointwise
import logic.equiv.transfer_instance
import ring_theory.finiteness
import ring_theory.localization.at_prime
import ring_theory.localization.away
import ring_theory.localization.integer
import ring_theory.localization.submodule
import ring_theory.nilpotent
import ring_theory.ring_hom_properties
/-!
# Local properties of commutative rings
In this file, we provide the proofs of various local properties.
## Naming Conventions
* `localization_P` : `P` holds for `S⁻¹R` if `P` holds for `R`.
* `P_of_localization_maximal` : `P` holds for `R` if `P` holds for `Rₘ` for all maximal `m`.
* `P_of_localization_prime` : `P` holds for `R` if `P` holds for `Rₘ` for all prime `m`.
* `P_of_localization_span` : `P` holds for `R` if given a spanning set `{fᵢ}`, `P` holds for all
`R_{fᵢ}`.
## Main results
The following properties are covered:
* The triviality of an ideal or an element:
`ideal_eq_zero_of_localization`, `eq_zero_of_localization`
* `is_reduced` : `localization_is_reduced`, `is_reduced_of_localization_maximal`.
* `finite`: `localization_finite`, `finite_of_localization_span`
* `finite_type`: `localization_finite_type`, `finite_type_of_localization_span`
-/
open_locale pointwise classical big_operators
universe u
variables {R S : Type u} [comm_ring R] [comm_ring S] (M : submonoid R)
variables (N : submonoid S) (R' S' : Type u) [comm_ring R'] [comm_ring S'] (f : R →+* S)
variables [algebra R R'] [algebra S S']
section properties
section comm_ring
variable (P : ∀ (R : Type u) [comm_ring R], Prop)
include P
/-- A property `P` of comm rings is said to be preserved by localization
if `P` holds for `M⁻¹R` whenever `P` holds for `R`. -/
def localization_preserves : Prop :=
∀ {R : Type u} [hR : comm_ring R] (M : by exactI submonoid R) (S : Type u) [hS : comm_ring S]
[by exactI algebra R S] [by exactI is_localization M S], @P R hR → @P S hS
/-- A property `P` of comm rings satisfies `of_localization_maximal` if
if `P` holds for `R` whenever `P` holds for `Rₘ` for all maximal ideal `m`. -/
def of_localization_maximal : Prop :=
∀ (R : Type u) [comm_ring R],
by exactI (∀ (J : ideal R) (hJ : J.is_maximal), by exactI P (localization.at_prime J)) → P R
end comm_ring
section ring_hom
variable (P : ∀ {R S : Type u} [comm_ring R] [comm_ring S] (f : by exactI R →+* S), Prop)
include P
/-- A property `P` of ring homs is said to be preserved by localization
if `P` holds for `M⁻¹R →+* M⁻¹S` whenever `P` holds for `R →+* S`. -/
def ring_hom.localization_preserves :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S) (M : by exactI submonoid R)
(R' S' : Type u) [comm_ring R'] [comm_ring S'] [by exactI algebra R R']
[by exactI algebra S S'] [by exactI is_localization M R']
[by exactI is_localization (M.map f) S'],
by exactI (P f → P (is_localization.map S' f (submonoid.le_comap_map M) : R' →+* S'))
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span`
if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `R` such that
`P` holds for `Rᵣ →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_span` via
`ring_hom.of_localization_span_iff_finite`, but this is easier to prove. -/
def ring_hom.of_localization_finite_span :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : finset R) (hs : by exactI ideal.span (s : set R) = ⊤)
(H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span`
if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `R` such that
`P` holds for `Rᵣ →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_finite_span` via
`ring_hom.of_localization_span_iff_finite`, but this has less restrictions when applying. -/
def ring_hom.of_localization_span :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : set R) (hs : by exactI ideal.span s = ⊤)
(H : by exactI (∀ (r : s), P (localization.away_map f r))), by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.holds_for_localization_away`
if `P` holds for each localization map `R →+* Rᵣ`. -/
def ring_hom.holds_for_localization_away : Prop :=
∀ ⦃R : Type u⦄ (S : Type u) [comm_ring R] [comm_ring S] [by exactI algebra R S] (r : R)
[by exactI is_localization.away r S], by exactI P (algebra_map R S)
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_finite_span_target`
if `P` holds for `R →+* S` whenever there exists a finite set `{ r }` that spans `S` such that
`P` holds for `R →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_span_target` via
`ring_hom.of_localization_span_target_iff_finite`, but this is easier to prove. -/
def ring_hom.of_localization_finite_span_target : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : finset S) (hs : by exactI ideal.span (s : set S) = ⊤)
(H : by exactI (∀ (r : s), P ((algebra_map S (localization.away (r : S))).comp f))),
by exactI P f
/-- A property `P` of ring homs satisfies `ring_hom.of_localization_span_target`
if `P` holds for `R →+* S` whenever there exists a set `{ r }` that spans `S` such that
`P` holds for `R →+* Sᵣ`.
Note that this is equivalent to `ring_hom.of_localization_finite_span_target` via
`ring_hom.of_localization_span_target_iff_finite`, but this has less restrictions when applying. -/
def ring_hom.of_localization_span_target : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S)
(s : set S) (hs : by exactI ideal.span s = ⊤)
(H : by exactI (∀ (r : s), P ((algebra_map S (localization.away (r : S))).comp f))),
by exactI P f
/-- A property `P` of ring homs satisfies `of_localization_prime` if
if `P` holds for `R` whenever `P` holds for `Rₘ` for all prime ideals `p`. -/
def ring_hom.of_localization_prime : Prop :=
∀ ⦃R S : Type u⦄ [comm_ring R] [comm_ring S] (f : by exactI R →+* S),
by exactI (∀ (J : ideal S) (hJ : J.is_prime),
by exactI P (localization.local_ring_hom _ J f rfl)) → P f
/-- A property of ring homs is local if it is preserved by localizations and compositions, and for
each `{ r }` that spans `S`, we have `P (R →+* S) ↔ ∀ r, P (R →+* Sᵣ)`. -/
structure ring_hom.property_is_local : Prop :=
(localization_preserves : ring_hom.localization_preserves @P)
(of_localization_span_target : ring_hom.of_localization_span_target @P)
(stable_under_composition : ring_hom.stable_under_composition @P)
(holds_for_localization_away : ring_hom.holds_for_localization_away @P)
lemma ring_hom.of_localization_span_iff_finite :
ring_hom.of_localization_span @P ↔ ring_hom.of_localization_finite_span @P :=
begin
delta ring_hom.of_localization_span ring_hom.of_localization_finite_span,
apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`.
introsI,
split,
{ intros h s, exact h s },
{ intros h s hs hs',
obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs,
exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) }
end
lemma ring_hom.of_localization_span_target_iff_finite :
ring_hom.of_localization_span_target @P ↔ ring_hom.of_localization_finite_span_target @P :=
begin
delta ring_hom.of_localization_span_target ring_hom.of_localization_finite_span_target,
apply forall₅_congr, -- TODO: Using `refine` here breaks `resetI`.
introsI,
split,
{ intros h s, exact h s },
{ intros h s hs hs',
obtain ⟨s', h₁, h₂⟩ := (ideal.span_eq_top_iff_finite s).mp hs,
exact h s' h₂ (λ x, hs' ⟨_, h₁ x.prop⟩) }
end
variables {P f R' S'}
lemma _root_.ring_hom.property_is_local.respects_iso (hP : ring_hom.property_is_local @P) :
ring_hom.respects_iso @P :=
begin
apply hP.stable_under_composition.respects_iso,
introv,
resetI,
letI := e.to_ring_hom.to_algebra,
apply_with hP.holds_for_localization_away { instances := ff },
apply is_localization.away_of_is_unit_of_bijective _ is_unit_one,
exact e.bijective
end
-- Almost all arguments are implicit since this is not intended to use mid-proof.
lemma ring_hom.localization_preserves.away
(H : ring_hom.localization_preserves @P) (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : P f) :
P (by exactI is_localization.away.map R' S' f r) :=
begin
resetI,
haveI : is_localization ((submonoid.powers r).map f) S',
{ rw submonoid.map_powers, assumption },
exact H f (submonoid.powers r) R' S' hf,
end
lemma ring_hom.property_is_local.of_localization_span (hP : ring_hom.property_is_local @P) :
ring_hom.of_localization_span @P :=
begin
introv R hs hs',
resetI,
apply_fun (ideal.map f) at hs,
rw [ideal.map_span, ideal.map_top] at hs,
apply hP.of_localization_span_target _ _ hs,
rintro ⟨_, r, hr, rfl⟩,
have := hs' ⟨r, hr⟩,
convert hP.stable_under_composition _ _ (hP.holds_for_localization_away (localization.away r) r)
(hs' ⟨r, hr⟩) using 1,
exact (is_localization.map_comp _).symm
end
end ring_hom
end properties
section ideal
-- This proof should work for all modules, but we do not know how to localize a module yet.
/-- An ideal is trivial if its localization at every maximal ideal is trivial. -/
lemma ideal_eq_zero_of_localization (I : ideal R)
(h : ∀ (J : ideal R) (hJ : J.is_maximal),
by exactI is_localization.coe_submodule (localization.at_prime J) I = 0) : I = 0 :=
begin
by_contradiction hI, change I ≠ ⊥ at hI,
obtain ⟨x, hx, hx'⟩ := set_like.exists_of_lt hI.bot_lt,
rw [submodule.mem_bot] at hx',
have H : (ideal.span ({x} : set R)).annihilator ≠ ⊤,
{ rw [ne.def, submodule.annihilator_eq_top_iff],
by_contra,
apply hx',
rw [← set.mem_singleton_iff, ← @submodule.bot_coe R, ← h],
exact ideal.subset_span (set.mem_singleton x) },
obtain ⟨p, hp₁, hp₂⟩ := ideal.exists_le_maximal _ H,
resetI,
specialize h p hp₁,
have : algebra_map R (localization.at_prime p) x = 0,
{ rw ← set.mem_singleton_iff,
change algebra_map R (localization.at_prime p) x ∈ (0 : submodule R (localization.at_prime p)),
rw ← h,
exact submodule.mem_map_of_mem hx },
rw is_localization.map_eq_zero_iff p.prime_compl at this,
obtain ⟨m, hm⟩ := this,
apply m.prop,
refine hp₂ _,
erw submodule.mem_annihilator_span_singleton,
rwa mul_comm at hm,
end
lemma eq_zero_of_localization (r : R)
(h : ∀ (J : ideal R) (hJ : J.is_maximal),
by exactI algebra_map R (localization.at_prime J) r = 0) : r = 0 :=
begin
rw ← ideal.span_singleton_eq_bot,
apply ideal_eq_zero_of_localization,
intros J hJ,
delta is_localization.coe_submodule,
erw [submodule.map_span, submodule.span_eq_bot],
rintro _ ⟨_, h', rfl⟩,
cases set.mem_singleton_iff.mpr h',
exact h J hJ,
end
end ideal
section reduced
lemma localization_is_reduced : localization_preserves (λ R hR, by exactI is_reduced R) :=
begin
introv R _ _,
resetI,
constructor,
rintro x ⟨(_|n), e⟩,
{ simpa using congr_arg (*x) e },
obtain ⟨⟨y, m⟩, hx⟩ := is_localization.surj M x,
dsimp only at hx,
let hx' := congr_arg (^ n.succ) hx,
simp only [mul_pow, e, zero_mul, ← ring_hom.map_pow] at hx',
rw [← (algebra_map R S).map_zero] at hx',
obtain ⟨m', hm'⟩ := (is_localization.eq_iff_exists M S).mp hx',
apply_fun (*m'^n) at hm',
simp only [mul_assoc, zero_mul] at hm',
rw [mul_comm, ← pow_succ, ← mul_pow] at hm',
replace hm' := is_nilpotent.eq_zero ⟨_, hm'.symm⟩,
rw [← (is_localization.map_units S m).mul_left_inj, hx, zero_mul,
is_localization.map_eq_zero_iff M],
exact ⟨m', by rw [← hm', mul_comm]⟩
end
instance [is_reduced R] : is_reduced (localization M) := localization_is_reduced M _ infer_instance
lemma is_reduced_of_localization_maximal :
of_localization_maximal (λ R hR, by exactI is_reduced R) :=
begin
introv R h,
constructor,
intros x hx,
apply eq_zero_of_localization,
intros J hJ,
specialize h J hJ,
resetI,
exact (hx.map $ algebra_map R $ localization.at_prime J).eq_zero,
end
end reduced
section surjective
lemma localization_preserves_surjective :
ring_hom.localization_preserves (λ R S _ _ f, function.surjective f) :=
begin
introv R H x,
resetI,
obtain ⟨x, ⟨_, s, hs, rfl⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
obtain ⟨y, rfl⟩ := H x,
use is_localization.mk' R' y ⟨s, hs⟩,
rw is_localization.map_mk',
refl,
end
lemma surjective_of_localization_span :
ring_hom.of_localization_span (λ R S _ _ f, function.surjective f) :=
begin
introv R e H,
rw [← set.range_iff_surjective, set.eq_univ_iff_forall],
resetI,
letI := f.to_algebra,
intro x,
apply submodule.mem_of_span_eq_top_of_smul_pow_mem (algebra.of_id R S).to_linear_map.range s e,
intro r,
obtain ⟨a, e'⟩ := H r (algebra_map _ _ x),
obtain ⟨b, ⟨_, n, rfl⟩, rfl⟩ := is_localization.mk'_surjective (submonoid.powers (r : R)) a,
erw is_localization.map_mk' at e',
rw [eq_comm, is_localization.eq_mk'_iff_mul_eq, subtype.coe_mk, subtype.coe_mk, ← map_mul] at e',
obtain ⟨⟨_, n', rfl⟩, e''⟩ := (is_localization.eq_iff_exists (submonoid.powers (f r)) _).mp e',
rw [subtype.coe_mk, mul_assoc, ← map_pow, ← map_mul, ← map_mul, ← pow_add, mul_comm] at e'',
exact ⟨n + n', _, e''.symm⟩
end
end surjective
section finite
/-- If `S` is a finite `R`-algebra, then `S' = M⁻¹S` is a finite `R' = M⁻¹R`-algebra. -/
lemma localization_finite : ring_hom.localization_preserves @ring_hom.finite :=
begin
introv R hf,
-- Setting up the `algebra` and `is_scalar_tower` instances needed
resetI,
letI := f.to_algebra,
letI := ((algebra_map S S').comp f).to_algebra,
let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M),
letI := f'.to_algebra,
haveI : is_scalar_tower R R' S' :=
is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _),
-- We claim that if `S` is generated by `T` as an `R`-module,
-- then `S'` is generated by `T` as an `R'`-module.
unfreezingI { obtain ⟨T, hT⟩ := hf },
use T.image (algebra_map S S'),
rw eq_top_iff,
rintro x -,
-- By the hypotheses, for each `x : S'`, we have `x = y / (f r)` for some `y : S` and `r : M`.
-- Since `S` is generated by `T`, the image of `y` should fall in the span of the image of `T`.
obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image],
have hy : y ∈ submodule.span R ↑T, by { rw hT, trivial },
replace hy : algebra_map S S' y ∈ submodule.map fₐ.to_linear_map (submodule.span R T) :=
submodule.mem_map_of_mem hy,
rw submodule.map_span fₐ.to_linear_map T at hy,
have H : submodule.span R ((algebra_map S S') '' T) ≤
(submodule.span R' ((algebra_map S S') '' T)).restrict_scalars R,
{ rw submodule.span_le, exact submodule.subset_span },
-- Now, since `y ∈ span T`, and `(f r)⁻¹ ∈ R'`, `x / (f r)` is in `span T` as well.
convert (submodule.span R' ((algebra_map S S') '' T)).smul_mem
(is_localization.mk' R' (1 : R) ⟨r, hr⟩) (H hy) using 1,
rw algebra.smul_def,
erw is_localization.map_mk',
rw map_one,
refl,
end
lemma localization_away_map_finite (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : f.finite) :
(is_localization.away.map R' S' f r).finite :=
localization_finite.away r hf
/--
Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`.
If the image of some `x : S` falls in the span of some finite `s ⊆ S'` over `R`,
then there exists some `m : M` such that `m • x` falls in the
span of `finset_integer_multiple _ s` over `R`.
-/
lemma is_localization.smul_mem_finset_integer_multiple_span [algebra R S]
[algebra R S'] [is_scalar_tower R S S']
[is_localization (M.map (algebra_map R S)) S'] (x : S)
(s : finset S') (hx : algebra_map S S' x ∈ submodule.span R (s : set S')) :
∃ m : M, m • x ∈ submodule.span R
(is_localization.finset_integer_multiple (M.map (algebra_map R S)) s : set S) :=
begin
let g : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S')
(λ c x, by simp [algebra.algebra_map_eq_smul_one]),
-- We first obtain the `y' ∈ M` such that `s' = y' • s` is falls in the image of `S` in `S'`.
let y := is_localization.common_denom_of_finset (M.map (algebra_map R S)) s,
have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm,
obtain ⟨y', hy', e : algebra_map R S y' = y⟩ := y.prop,
have : algebra_map R S y' • (s : set S') = y' • s :=
by simp_rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul],
rw [← e, this] at hx₁,
replace hx₁ := congr_arg (submodule.span R) hx₁,
rw submodule.span_smul_eq at hx₁,
replace hx : _ ∈ y' • submodule.span R (s : set S') := set.smul_mem_smul_set hx,
rw hx₁ at hx,
erw [← g.map_smul, ← submodule.map_span (g : S →ₗ[R] S')] at hx,
-- Since `x` falls in the span of `s` in `S'`, `y' • x : S` falls in the span of `s'` in `S'`.
-- That is, there exists some `x' : S` in the span of `s'` in `S` and `x' = y' • x` in `S'`.
-- Thus `a • (y' • x) = a • x' ∈ span s'` in `S` for some `a ∈ M`.
obtain ⟨x', hx', hx'' : algebra_map _ _ _ = _⟩ := hx,
obtain ⟨⟨_, a, ha₁, rfl⟩, ha₂⟩ := (is_localization.eq_iff_exists
(M.map (algebra_map R S)) S').mp hx'',
use (⟨a, ha₁⟩ : M) * (⟨y', hy'⟩ : M),
convert (submodule.span R (is_localization.finset_integer_multiple
(submonoid.map (algebra_map R S) M) s : set S)).smul_mem a hx' using 1,
convert ha₂.symm,
{ rw [mul_comm (y' • x), subtype.coe_mk, submonoid.smul_def, submonoid.coe_mul, ← smul_smul],
exact algebra.smul_def _ _ },
{ rw mul_comm, exact algebra.smul_def _ _ }
end
/-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ span R' s`,
then `t • x ∈ span R s` for some `t : M`.-/
lemma multiple_mem_span_of_mem_localization_span [algebra R' S] [algebra R S]
[is_scalar_tower R R' S] [is_localization M R']
(s : set S) (x : S) (hx : x ∈ submodule.span R' s) :
∃ t : M, t • x ∈ submodule.span R s :=
begin
classical,
obtain ⟨s', hss', hs'⟩ := submodule.mem_span_finite_of_mem_span hx,
rsuffices ⟨t, ht⟩ : ∃ t : M, t • x ∈ submodule.span R (s' : set S),
{ exact ⟨t, submodule.span_mono hss' ht⟩ },
clear hx hss' s,
revert x,
apply s'.induction_on,
{ intros x hx, use 1, simpa using hx },
rintros a s ha hs x hx,
simp only [finset.coe_insert, finset.image_insert, finset.coe_image, subtype.coe_mk,
submodule.mem_span_insert] at hx ⊢,
rcases hx with ⟨y, z, hz, rfl⟩,
rcases is_localization.surj M y with ⟨⟨y', s'⟩, e⟩,
replace e : _ * a = _ * a := (congr_arg (λ x, algebra_map R' S x * a) e : _),
simp_rw [ring_hom.map_mul, ← is_scalar_tower.algebra_map_apply, mul_comm (algebra_map R' S y),
mul_assoc, ← algebra.smul_def] at e,
rcases hs _ hz with ⟨t, ht⟩,
refine ⟨t*s', t*y', _, (submodule.span R (s : set S)).smul_mem s' ht, _⟩,
rw [smul_add, ← smul_smul, mul_comm, ← smul_smul, ← smul_smul, ← e],
refl,
end
/-- If `S` is an `R' = M⁻¹R` algebra, and `x ∈ adjoin R' s`,
then `t • x ∈ adjoin R s` for some `t : M`.-/
lemma multiple_mem_adjoin_of_mem_localization_adjoin [algebra R' S] [algebra R S]
[is_scalar_tower R R' S] [is_localization M R']
(s : set S) (x : S) (hx : x ∈ algebra.adjoin R' s) :
∃ t : M, t • x ∈ algebra.adjoin R s :=
begin
change ∃ (t : M), t • x ∈ (algebra.adjoin R s).to_submodule,
change x ∈ (algebra.adjoin R' s).to_submodule at hx,
simp_rw [algebra.adjoin_eq_span] at hx ⊢,
exact multiple_mem_span_of_mem_localization_span M R' _ _ hx
end
lemma finite_of_localization_span : ring_hom.of_localization_span @ring_hom.finite :=
begin
rw ring_hom.of_localization_span_iff_finite,
introv R hs H,
-- We first setup the instances
resetI,
letI := f.to_algebra,
letI := λ (r : s), (localization.away_map f r).to_algebra,
haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S))
(localization.away (f r)),
{ intro r, rw submonoid.map_powers, exact localization.is_localization },
haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) :=
λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
-- By the hypothesis, we may find a finite generating set for each `Sᵣ`. This set can then be
-- lifted into `R` by multiplying a sufficiently large power of `r`. I claim that the union of
-- these generates `S`.
constructor,
replace H := λ r, (H r).1,
choose s₁ s₂ using H,
let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x),
use s.attach.bUnion sf,
rw [submodule.span_attach_bUnion, eq_top_iff],
-- It suffices to show that `r ^ n • x ∈ span T` for each `r : s`, since `{ r ^ n }` spans `R`.
-- This then follows from the fact that each `x : R` is a linear combination of the generating set
-- of `Sᵣ`. By multiplying a sufficiently large power of `r`, we can cancel out the `r`s in the
-- denominators of both the generating set and the coefficients.
rintro x -,
apply submodule.mem_of_span_eq_top_of_smul_pow_mem _ (s : set R) hs _ _,
intro r,
obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_span_of_mem_localization_span
(submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r)))
(algebra_map S _ x) (by { rw s₂ r, trivial }),
rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S,
subtype.coe_mk, ← map_mul] at hn₁,
obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.smul_mem_finset_integer_multiple_span
(submonoid.powers (r : R)) (localization.away (f r)) _ (s₁ r) hn₁,
rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂,
simp_rw submonoid.map_powers at hn₂,
use n₂ + n₁,
exact le_supr (λ (x : s), submodule.span R (sf x : set S)) r hn₂,
end
end finite
section finite_type
lemma localization_finite_type : ring_hom.localization_preserves @ring_hom.finite_type :=
begin
introv R hf,
-- mirrors the proof of `localization_map_finite`
resetI,
letI := f.to_algebra,
letI := ((algebra_map S S').comp f).to_algebra,
let f' : R' →+* S' := is_localization.map S' f (submonoid.le_comap_map M),
letI := f'.to_algebra,
haveI : is_scalar_tower R R' S' :=
is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
let fₐ : S →ₐ[R] S' := alg_hom.mk' (algebra_map S S') (λ c x, ring_hom.map_mul _ _ _),
obtain ⟨T, hT⟩ := id hf,
use T.image (algebra_map S S'),
rw eq_top_iff,
rintro x -,
obtain ⟨y, ⟨_, ⟨r, hr, rfl⟩⟩, rfl⟩ := is_localization.mk'_surjective (M.map f) x,
rw [is_localization.mk'_eq_mul_mk'_one, mul_comm, finset.coe_image],
have hy : y ∈ algebra.adjoin R (T : set S), by { rw hT, trivial },
replace hy : algebra_map S S' y ∈ (algebra.adjoin R (T : set S)).map fₐ :=
subalgebra.mem_map.mpr ⟨_, hy, rfl⟩,
rw fₐ.map_adjoin T at hy,
have H : algebra.adjoin R ((algebra_map S S') '' T) ≤
(algebra.adjoin R' ((algebra_map S S') '' T)).restrict_scalars R,
{ rw algebra.adjoin_le_iff, exact algebra.subset_adjoin },
convert (algebra.adjoin R' ((algebra_map S S') '' T)).smul_mem (H hy)
(is_localization.mk' R' (1 : R) ⟨r, hr⟩) using 1,
rw algebra.smul_def,
erw is_localization.map_mk',
rw map_one,
refl,
end
lemma localization_away_map_finite_type (r : R) [is_localization.away r R']
[is_localization.away (f r) S'] (hf : f.finite_type) :
(is_localization.away.map R' S' f r).finite_type :=
localization_finite_type.away r hf
variable {S'}
/--
Let `S` be an `R`-algebra, `M` a submonoid of `S`, `S' = M⁻¹S`.
Suppose the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`,
and `A` is an `R`-subalgebra of `S` containing both `M` and the numerators of `s`.
Then, there exists some `m : M` such that `m • x` falls in `A`.
-/
lemma is_localization.exists_smul_mem_of_mem_adjoin [algebra R S]
[algebra R S'] [is_scalar_tower R S S'] (M : submonoid S)
[is_localization M S'] (x : S) (s : finset S') (A : subalgebra R S)
(hA₁ : (is_localization.finset_integer_multiple M s : set S) ⊆ A)
(hA₂ : M ≤ A.to_submonoid)
(hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) :
∃ m : M, m • x ∈ A :=
begin
let g : S →ₐ[R] S' := is_scalar_tower.to_alg_hom R S S',
let y := is_localization.common_denom_of_finset M s,
have hx₁ : (y : S) • ↑s = g '' _ := (is_localization.finset_integer_multiple_image _ s).symm,
obtain ⟨n, hn⟩ := algebra.pow_smul_mem_of_smul_subset_of_mem_adjoin (y : S) (s : set S')
(A.map g) (by { rw hx₁, exact set.image_subset _ hA₁ }) hx (set.mem_image_of_mem _ (hA₂ y.2)),
obtain ⟨x', hx', hx''⟩ := hn n (le_of_eq rfl),
rw [algebra.smul_def, ← _root_.map_mul] at hx'',
obtain ⟨a, ha₂⟩ := (is_localization.eq_iff_exists M S').mp hx'',
use a * y ^ n,
convert A.mul_mem hx' (hA₂ a.2),
convert ha₂.symm,
simp only [submonoid.smul_def, submonoid.coe_pow, smul_eq_mul, submonoid.coe_mul],
ring,
end
/--
Let `S` be an `R`-algebra, `M` an submonoid of `R`, and `S' = M⁻¹S`.
If the image of some `x : S` falls in the adjoin of some finite `s ⊆ S'` over `R`,
then there exists some `m : M` such that `m • x` falls in the
adjoin of `finset_integer_multiple _ s` over `R`.
-/
lemma is_localization.lift_mem_adjoin_finset_integer_multiple [algebra R S]
[algebra R S'] [is_scalar_tower R S S']
[is_localization (M.map (algebra_map R S)) S'] (x : S)
(s : finset S') (hx : algebra_map S S' x ∈ algebra.adjoin R (s : set S')) :
∃ m : M, m • x ∈ algebra.adjoin R
(is_localization.finset_integer_multiple (M.map (algebra_map R S)) s : set S) :=
begin
obtain ⟨⟨_, a, ha, rfl⟩, e⟩ := is_localization.exists_smul_mem_of_mem_adjoin
(M.map (algebra_map R S)) x s (algebra.adjoin R _) algebra.subset_adjoin _ hx,
{ exact ⟨⟨a, ha⟩, by simpa [submonoid.smul_def] using e⟩ },
{ rintros _ ⟨a, ha, rfl⟩, exact subalgebra.algebra_map_mem _ a }
end
lemma finite_type_of_localization_span : ring_hom.of_localization_span @ring_hom.finite_type :=
begin
rw ring_hom.of_localization_span_iff_finite,
introv R hs H,
-- mirrors the proof of `finite_of_localization_span`
resetI,
letI := f.to_algebra,
letI := λ (r : s), (localization.away_map f r).to_algebra,
haveI : ∀ r : s, is_localization ((submonoid.powers (r : R)).map (algebra_map R S))
(localization.away (f r)),
{ intro r, rw submonoid.map_powers, exact localization.is_localization },
haveI : ∀ r : s, is_scalar_tower R (localization.away (r : R)) (localization.away (f r)) :=
λ r, is_scalar_tower.of_algebra_map_eq' (is_localization.map_comp _).symm,
constructor,
replace H := λ r, (H r).1,
choose s₁ s₂ using H,
let sf := λ (x : s), is_localization.finset_integer_multiple (submonoid.powers (f x)) (s₁ x),
use s.attach.bUnion sf,
convert (algebra.adjoin_attach_bUnion sf).trans _,
rw eq_top_iff,
rintro x -,
apply (⨆ (x : s), algebra.adjoin R (sf x : set S)).to_submodule
.mem_of_span_eq_top_of_smul_pow_mem _ hs _ _,
intro r,
obtain ⟨⟨_, n₁, rfl⟩, hn₁⟩ := multiple_mem_adjoin_of_mem_localization_adjoin
(submonoid.powers (r : R)) (localization.away (r : R)) (s₁ r : set (localization.away (f r)))
(algebra_map S (localization.away (f r)) x) (by { rw s₂ r, trivial }),
rw [submonoid.smul_def, algebra.smul_def, is_scalar_tower.algebra_map_apply R S,
subtype.coe_mk, ← map_mul] at hn₁,
obtain ⟨⟨_, n₂, rfl⟩, hn₂⟩ := is_localization.lift_mem_adjoin_finset_integer_multiple
(submonoid.powers (r : R)) _ (s₁ r) hn₁,
rw [submonoid.smul_def, ← algebra.smul_def, smul_smul, subtype.coe_mk, ← pow_add] at hn₂,
simp_rw submonoid.map_powers at hn₂,
use n₂ + n₁,
exact le_supr (λ (x : s), algebra.adjoin R (sf x : set S)) r hn₂
end
end finite_type
|
0d074637fe39f12cfc664e56d38498eaaa5f183c | b147e1312077cdcfea8e6756207b3fa538982e12 | /algebra/group_power.lean | fe9a3f14b6317f13adb647779c20b6f49af8cfc5 | [
"Apache-2.0"
] | permissive | SzJS/mathlib | 07836ee708ca27cd18347e1e11ce7dd5afb3e926 | 23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29 | refs/heads/master | 1,584,980,332,064 | 1,532,063,841,000 | 1,532,063,841,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,654 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
The power operation on monoids and groups. We separate this from group, because it depends on
nat, which in turn depends on other parts of algebra.
We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation
a^n is used for the first, but users can locally redefine it to gpow when needed.
Note: power adopts the convention that 0^0=1.
-/
import algebra.char_zero data.int.basic algebra.group algebra.ordered_field data.list.basic
universes u v
variable {α : Type u}
@[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one]
@[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a :=
by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div]; simp [div_one]
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow [monoid α] (a : α) : ℕ → α
| 0 := 1
| (n+1) := a * monoid.pow n
def add_monoid.smul [add_monoid α] (n : ℕ) (a : α) : α :=
@monoid.pow (multiplicative α) _ a n
precedence `•`:70
local infix ` • ` := add_monoid.smul
@[priority 5] instance monoid.has_pow [monoid α] : has_pow α ℕ := ⟨monoid.pow⟩
/- monoid -/
section monoid
variables [monoid α] {β : Type u} [add_monoid β]
@[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl
@[simp] theorem add_monoid.zero_smul (a : β) : 0 • a = 0 := rfl
attribute [to_additive add_monoid.zero_smul] pow_zero
theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl
theorem succ_smul (a : β) (n : ℕ) : (n+1)•a = a + n•a := rfl
attribute [to_additive succ_smul] pow_succ
@[simp] theorem pow_one (a : α) : a^1 = a := mul_one _
@[simp] theorem add_monoid.one_smul (a : β) : 1•a = a := add_zero _
attribute [to_additive add_monoid.one_smul] pow_one
theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n :=
by induction n with n ih; simp [*, pow_succ, mul_assoc]
theorem smul_add_comm' : ∀ (a : β) (n : ℕ), n•a + a = a + n•a :=
@pow_mul_comm' (multiplicative β) _
theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a :=
by simp [pow_succ, pow_mul_comm']
theorem succ_smul' (a : β) (n : ℕ) : (n+1)•a = n•a + a :=
by simp [succ_smul, smul_add_comm']
attribute [to_additive succ_smul'] pow_succ'
theorem pow_two (a : α) : a^2 = a * a :=
by simp [pow_succ]
theorem two_smul (a : β) : 2•a = a + a :=
by simp [succ_smul]
attribute [to_additive two_smul] pow_two
theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n :=
by induction n; simp [*, pow_succ', nat.add_succ, mul_assoc]
theorem add_monoid.add_smul : ∀ (a : β) (m n : ℕ), (m + n)•a = m•a + n•a :=
@pow_add (multiplicative β) _
attribute [to_additive add_monoid.add_smul] pow_add
@[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) :=
by induction n; simp [*, pow_succ]
@[simp] theorem add_monoid.smul_zero (n : ℕ) : n•(0 : β) = (0:β) :=
by induction n; simp [*, succ_smul]
attribute [to_additive add_monoid.smul_zero] one_pow
theorem pow_mul (a : α) (m : ℕ) : ∀ n, a^(m * n) = (a^m)^n
| 0 := by simp
| (n+1) := by rw [nat.mul_succ, pow_add, pow_succ', pow_mul]
theorem add_monoid.mul_smul' : ∀ (a : β) (m n : ℕ), m * n • a = n•(m•a) :=
@pow_mul (multiplicative β) _
attribute [to_additive add_monoid.mul_smul'] pow_mul
theorem pow_mul' (a : α) (m n : ℕ) : a^(m * n) = (a^n)^m :=
by rw [mul_comm, pow_mul]
theorem add_monoid.mul_smul (a : β) (m n : ℕ) : m * n • a = m•(n•a) :=
by rw [mul_comm, add_monoid.mul_smul']
attribute [to_additive add_monoid.mul_smul] pow_mul'
@[simp] theorem add_monoid.smul_one [has_one β] : ∀ n : ℕ, n • (1 : β) = n :=
nat.eq_cast _ (add_monoid.zero_smul _) (add_monoid.one_smul _) (add_monoid.add_smul _)
theorem pow_bit0 (a : α) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _
theorem bit0_smul (a : β) (n : ℕ) : bit0 n • a = n•a + n•a := add_monoid.add_smul _ _ _
attribute [to_additive bit0_smul] pow_bit0
theorem pow_bit1 (a : α) (n : ℕ) : a ^ bit1 n = a^n * a^n * a :=
by rw [bit1, pow_succ', pow_bit0]
theorem bit1_smul : ∀ (a : β) (n : ℕ), bit1 n • a = n•a + n•a + a :=
@pow_bit1 (multiplicative β) _
attribute [to_additive bit1_smul] pow_bit1
theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m :=
by rw [←pow_add, ←pow_add, add_comm]
theorem smul_add_comm : ∀ (a : β) (m n : ℕ), m•a + n•a = n•a + m•a :=
@pow_mul_comm (multiplicative β) _
attribute [to_additive smul_add_comm] pow_mul_comm
@[simp] theorem list.prod_repeat (a : α) : ∀ (n : ℕ), (list.repeat a n).prod = a ^ n
| 0 := rfl
| (n+1) := by simp [pow_succ, list.prod_repeat n]
@[simp] theorem list.sum_repeat : ∀ (a : β) (n : ℕ), (list.repeat a n).sum = n • a :=
@list.prod_repeat (multiplicative β) _
attribute [to_additive list.sum_repeat] list.prod_repeat
end monoid
@[simp] theorem nat.pow_eq_pow (p q : ℕ) :
@has_pow.pow _ _ monoid.has_pow p q = p ^ q :=
by induction q; [refl, simp [nat.pow_succ, pow_succ, mul_comm, *]]
@[simp] theorem nat.smul_eq_mul (m n : ℕ) : m • n = m * n :=
by rw mul_comm; induction m; simp [succ_smul', nat.mul_succ, *]
/- commutative monoid -/
section comm_monoid
variables [comm_monoid α] {β : Type*} [add_comm_monoid β]
theorem mul_pow (a b : α) : ∀ n:ℕ, (a * b)^n = a^n * b^n
| 0 := by simp
| (n+1) := by simp [pow_succ, mul_assoc, mul_left_comm]; rw mul_pow
theorem add_monoid.smul_add : ∀ (a b : β) (n : ℕ), n•(a + b) = n•a + n•b :=
@mul_pow (multiplicative β) _
attribute [to_additive add_monoid.add_smul] mul_pow
end comm_monoid
section group
variables [group α] {β : Type*} [add_group β]
section nat
@[simp] theorem inv_pow (a : α) : ∀n:ℕ, (a⁻¹)^n = (a^n)⁻¹
| 0 := by simp
| (n+1) := by rw [pow_succ', pow_succ, mul_inv_rev, inv_pow]
@[simp] theorem add_monoid.neg_smul : ∀ (a : β) (n : ℕ), n•(-a) = -(n•a) :=
@inv_pow (multiplicative β) _
attribute [to_additive add_monoid.neg_smul] inv_pow
theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ :=
have h1 : m - n + n = m, from nat.sub_add_cancel h,
have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1],
eq_mul_inv_of_mul_eq h2
theorem add_monoid.smul_sub : ∀ (a : β) {m n : ℕ}, m ≥ n → (m - n)•a = m•a - n•a :=
@pow_sub (multiplicative β) _
attribute [to_additive add_monoid.smul_sub] inv_pow
theorem pow_inv_comm (a : α) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m :=
by rw inv_pow; exact inv_comm_of_comm (pow_mul_comm _ _ _)
theorem add_monoid.smul_neg_comm : ∀ (a : β) (m n : ℕ), m•(-a) + n•a = n•a + m•(-a) :=
@pow_inv_comm (multiplicative β) _
attribute [to_additive add_monoid.smul_neg_comm] pow_inv_comm
end nat
open int
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow (a : α) : ℤ → α
| (of_nat n) := a^n
| -[1+n] := (a^(nat.succ n))⁻¹
def gsmul (n : ℤ) (a : β) : β :=
@gpow (multiplicative β) _ a n
@[priority 10] instance group.has_pow : has_pow α ℤ := ⟨gpow⟩
local infix ` • `:70 := gsmul
local infix ` •ℕ `:70 := add_monoid.smul
@[simp] theorem gpow_coe_nat (a : α) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl
@[simp] theorem gsmul_coe_nat (a : β) (n : ℕ) : (n:ℤ) • a = n •ℕ a := rfl
attribute [to_additive gsmul_coe_nat] gpow_coe_nat
@[simp] theorem gpow_of_nat (a : α) (n : ℕ) : a ^ of_nat n = a ^ n := rfl
@[simp] theorem gsmul_of_nat (a : β) (n : ℕ) : of_nat n • a = n •ℕ a := rfl
attribute [to_additive gsmul_of_nat] gpow_of_nat
@[simp] theorem gpow_neg_succ (a : α) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl
@[simp] theorem gsmul_neg_succ (a : β) (n : ℕ) : -[1+n] • a = - (n.succ •ℕ a) := rfl
attribute [to_additive gsmul_neg_succ] gpow_neg_succ
local attribute [ematch] le_of_lt
open nat
@[simp] theorem gpow_zero (a : α) : a ^ (0:ℤ) = 1 := rfl
@[simp] theorem zero_gsmul (a : β) : (0:ℤ) • a = 0 := rfl
attribute [to_additive zero_gsmul] gpow_zero
@[simp] theorem gpow_one (a : α) : a ^ (1:ℤ) = a := mul_one _
@[simp] theorem one_gsmul (a : β) : (1:ℤ) • a = a := add_zero _
attribute [to_additive one_gsmul] gpow_one
@[simp, to_additive zero_gsmul]
theorem one_gpow : ∀ (n : ℤ), (1 : α) ^ n = 1
| (n : ℕ) := one_pow _
| -[1+ n] := by simp
@[simp] theorem gpow_neg (a : α) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := rfl
| 0 := one_inv.symm
| -[1+ n] := (inv_inv _).symm
@[simp] theorem neg_gsmul : ∀ (a : β) (n : ℤ), -n • a = -(n • a) :=
@gpow_neg (multiplicative β) _
attribute [to_additive neg_gsmul] gpow_neg
theorem gpow_neg_one (x : α) : x ^ (-1:ℤ) = x⁻¹ := by simp
theorem neg_one_gsmul (x : β) : (-1:ℤ) • x = -x := by simp
attribute [to_additive neg_one_gsmul] gpow_neg_one
@[to_additive neg_gsmul]
theorem inv_gpow (a : α) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := inv_pow a n
| -[1+ n] := by simp [inv_pow]
private lemma gpow_add_aux (a : α) (m n : nat) :
a ^ ((of_nat m) + -[1+n]) = a ^ of_nat m * a ^ -[1+n] :=
or.elim (nat.lt_or_ge m (nat.succ n))
(assume : m < succ n,
have m ≤ n, from le_of_lt_succ this,
suffices a ^ -[1+ n-m] = a ^ of_nat m * a ^ -[1+n], by simp [*, of_nat_add_neg_succ_of_nat_of_lt],
suffices (a ^ nat.succ (n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], from this,
suffices (a ^ (nat.succ n - m))⁻¹ = a ^ of_nat m * a ^ -[1+n], by rw ←succ_sub; assumption,
by rw pow_sub; finish [gpow])
(assume : m ≥ succ n,
suffices a ^ (of_nat (m - succ n)) = (a ^ (of_nat m)) * (a ^ -[1+ n]),
by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption,
suffices a ^ (m - succ n) = a ^ m * (a ^ n.succ)⁻¹, from this,
by rw pow_sub; assumption)
theorem gpow_add (a : α) : ∀ (i j : ℤ), a ^ (i + j) = a ^ i * a ^ j
| (of_nat m) (of_nat n) := pow_add _ _ _
| (of_nat m) -[1+n] := gpow_add_aux _ _ _
| -[1+m] (of_nat n) := by rw [add_comm, gpow_add_aux,
gpow_neg_succ, gpow_of_nat, ← inv_pow, ← pow_inv_comm]
| -[1+m] -[1+n] :=
suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ m.succ)⁻¹ * (a ^ n.succ)⁻¹, from this,
by rw [← succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev]
theorem add_gsmul : ∀ (a : β) (i j : ℤ), (i + j) • a = i • a + j • a :=
@gpow_add (multiplicative β) _
theorem gpow_mul_comm (a : α) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i :=
by rw [← gpow_add, ← gpow_add, add_comm]
theorem gsmul_add_comm : ∀ (a : β) (i j), i • a + j • a = j • a + i • a :=
@gpow_mul_comm (multiplicative β) _
attribute [to_additive gsmul_add_comm] gpow_mul_comm
theorem gpow_mul (a : α) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := pow_mul _ _ _
| (m : ℕ) -[1+ n] := (gpow_neg _ (m * succ n)).trans $
show (a ^ (m * succ n))⁻¹ = _, by rw pow_mul; refl
| -[1+ m] (n : ℕ) := (gpow_neg _ (succ m * n)).trans $
show (a ^ (m.succ * n))⁻¹ = _, by simp [pow_mul]
| -[1+ m] -[1+ n] := (pow_mul a (succ m) (succ n)).trans $ by simp
theorem gsmul_mul' : ∀ (a : β) (m n : ℤ), m * n • a = n • (m • a) :=
@gpow_mul (multiplicative β) _
attribute [to_additive gsmul_mul'] gpow_mul
theorem gpow_mul' (a : α) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, gpow_mul]
theorem gsmul_mul (a : β) (m n : ℤ) : m * n • a = m • (n • a) :=
by rw [mul_comm, gsmul_mul']
attribute [to_additive gsmul_mul] gpow_mul'
theorem gpow_bit0 (a : α) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _
theorem bit0_gsmul (a : β) (n : ℤ) : bit0 n • a = n • a + n • a := gpow_add _ _ _
attribute [to_additive bit0_gsmul] gpow_bit0
theorem gpow_bit1 (a : α) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
by rw [bit1, gpow_add]; simp [gpow_bit0]
theorem bit1_gsmul : ∀ (a : β) (n : ℤ), bit1 n • a = n • a + n • a + a :=
@gpow_bit1 (multiplicative β) _
attribute [to_additive bit1_gsmul] gpow_bit1
end group
local infix ` •ℤ `:70 := gsmul
theorem add_monoid.smul_eq_mul' [semiring α] (a : α) : ∀ n : ℕ, n • a = a * n
| 0 := by simp
| (n+1) := by simp [add_monoid.smul_eq_mul' n, mul_add, succ_smul']
theorem add_monoid.smul_eq_mul [semiring α] (n : ℕ) (a : α) : n • a = n * a :=
by rw [add_monoid.smul_eq_mul', nat.mul_cast_comm]
theorem add_monoid.mul_smul_left [semiring α] (a b : α) (n : ℕ) : n • (a * b) = a * (n • b) :=
by rw [add_monoid.smul_eq_mul', add_monoid.smul_eq_mul', mul_assoc]
theorem add_monoid.mul_smul_assoc [semiring α] (a b : α) (n : ℕ) : n • (a * b) = n • a * b :=
by rw [add_monoid.smul_eq_mul, add_monoid.smul_eq_mul, mul_assoc]
theorem neg_one_pow_eq_or {R} [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1
| 0 := by simp
| (n+1) := by cases neg_one_pow_eq_or n; simp [pow_succ, h]
theorem gsmul_eq_mul [ring α] (a : α) : ∀ n, n •ℤ a = n * a
| (n : ℕ) := by simp [add_monoid.smul_eq_mul]
| -[1+ n] := by simp [add_monoid.smul_eq_mul, -add_comm, add_mul]
theorem gsmul_eq_mul' [ring α] (a : α) (n : ℤ) : n •ℤ a = a * n :=
by rw [gsmul_eq_mul, int.mul_cast_comm]
theorem mul_gsmul_left [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) :=
by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc]
theorem mul_gsmul_assoc [ring α] (a b : α) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b :=
by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc]
theorem pow_ne_zero [domain α] {a : α} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
by induction n with n ih; simp [pow_succ, mul_eq_zero, *]
@[simp] theorem one_div_pow [division_ring α] {a : α} (ha : a ≠ 0) : ∀ n : ℕ, (1 / a) ^ n = 1 / a ^ n
| 0 := by simp
| (n+1) := by rw [pow_succ', pow_succ,
← division_ring.one_div_mul_one_div (pow_ne_zero n ha) ha, one_div_pow]
@[simp] theorem division_ring.inv_pow [division_ring α] {a : α} (ha : a ≠ 0) (n : ℕ) : a⁻¹ ^ n = (a ^ n)⁻¹ :=
by simp [inv_eq_one_div, -one_div_eq_inv, ha]
@[simp] theorem div_pow [field α] (a : α) {b : α} (hb : b ≠ 0) (n : ℕ) : (a / b) ^ n = a ^ n / b ^ n :=
by rw [div_eq_mul_one_div, mul_pow, one_div_pow hb, ← div_eq_mul_one_div]
theorem add_monoid.smul_nonneg [ordered_comm_monoid α] {a : α} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n • a
| 0 := le_refl _
| (n+1) := add_nonneg' H (add_monoid.smul_nonneg n)
lemma pow_abs [decidable_linear_ordered_comm_ring α] (a : α) (n : ℕ) : (abs a)^n = abs (a^n) :=
by induction n; simp [*, pow_succ, abs_mul]
lemma pow_inv [division_ring α] (a : α) : ∀ n : ℕ, a ≠ 0 → (a^n)⁻¹ = (a⁻¹)^n
| 0 ha := by simp [pow_zero]
| (n+1) ha := by rw [pow_succ, pow_succ', mul_inv_eq (pow_ne_zero _ ha) ha, pow_inv _ ha]
section linear_ordered_semiring
variable [linear_ordered_semiring α]
theorem pow_pos {a : α} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n
| 0 := by simp [zero_lt_one]
| (n+1) := by simpa [pow_succ] using mul_pos H (pow_pos _)
theorem pow_nonneg {a : α} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n
| 0 := by simp [zero_le_one]
| (n+1) := by simpa [pow_succ] using mul_nonneg H (pow_nonneg _)
theorem one_le_pow_of_one_le {a : α} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n
| 0 := by simp; apply le_refl
| (n+1) :=
begin
simp [pow_succ], rw ← one_mul (1 : α),
apply mul_le_mul,
assumption,
apply one_le_pow_of_one_le,
apply zero_le_one,
transitivity, apply zero_le_one, assumption
end
theorem pow_ge_one_add_mul {a : α} (H : a ≥ 0) :
∀ (n : ℕ), 1 + n • a ≤ (1 + a) ^ n
| 0 := by simp
| (n+1) := begin
rw [pow_succ', succ_smul'],
refine le_trans _ (mul_le_mul_of_nonneg_right
(pow_ge_one_add_mul n) (add_nonneg zero_le_one H)),
rw [mul_add, mul_one, ← add_assoc, add_le_add_iff_left],
simpa using mul_le_mul_of_nonneg_right
((le_add_iff_nonneg_right 1).2 (add_monoid.smul_nonneg H n)) H
end
theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
let ⟨k, hk⟩ := nat.le.dest h in
calc a ^ n = a ^ n * 1 : by simp
... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left
(one_le_pow_of_one_le ha _)
(pow_nonneg (le_trans zero_le_one ha) _)
... = a ^ m : by rw [←hk, pow_add]
end linear_ordered_semiring
theorem pow_two_nonneg [linear_ordered_ring α] (a : α) : 0 ≤ a ^ 2 :=
by rw pow_two; exact mul_self_nonneg _
theorem pow_ge_one_add_sub_mul [linear_ordered_ring α]
{a : α} (H : a ≥ 1) (n : ℕ) : 1 + n • (a - 1) ≤ a ^ n :=
by simpa using pow_ge_one_add_mul (sub_nonneg.2 H) n
|
5427fc01b7605436370a6771d3fd88dd30286149 | 36938939954e91f23dec66a02728db08a7acfcf9 | /old-lean4/json.lean | ed99ff0ba71e9c67d28b87bd367ecd9f9f81c4c6 | [] | no_license | pnwamk/reopt-vcg | f8b56dd0279392a5e1c6aee721be8138e6b558d3 | c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d | refs/heads/master | 1,631,145,017,772 | 1,593,549,019,000 | 1,593,549,143,000 | 254,191,418 | 0 | 0 | null | 1,586,377,077,000 | 1,586,377,077,000 | null | UTF-8 | Lean | false | false | 8,978 | lean | import hex
import rbnode
import reader
namespace json
-- Scientific notation (note this does not maintain a normal form for now)
structure Scientific :=
(numerator : Int)
(exponent : Int)
namespace Scientific
def toString (s:Scientific) : String :=
let e := s.exponent
in toString (s.numerator) ++ (if e == 0 then "" else "E" ++ toString e)
end Scientific
def stringLt (x y : String) : Bool := Decidable.toBool (x < y)
--- A JSON value
inductive Value
| object : RBNode String (λ_, Value) → Value
| array : Array Value → Value
| string : String → Value
| number : Scientific → Value
| bool : Bool → Value
| null : Value
namespace Value
def true : Value := Value.bool True
def false : Value := Value.bool False
def ofNat (n:ℕ) : Value := Value.number ⟨Int.ofNat n, 0⟩
def ofList (l:List Value) := Value.array (List.toArray l)
def listObj (l:List (String × Value)) : Value := object (RBNode.ofList stringLt l)
def isControl (c:Char) : Bool := c.val ≤ 0x1f ∨ c.val = 0x7f
def utf8Escape' : String → List Char → String
| p [] := p
| p (c::l) :=
if c.val = 0x22 then
utf8Escape' (p ++ "\\\"") l
else if c.val = 0x8 then
utf8Escape' (p ++ "\\b") l
else if c.val = 0xc then
utf8Escape' (p ++ "\\f") l
else if c = '\n' then
utf8Escape' (p ++ "\\n") l
else if c.val = 0xd then
utf8Escape' (p ++ "\\r") l
else if c = '\t' then
utf8Escape' (p ++ "\\t") l
else if isControl c then
let v := c.val in
let s := if v < 0x10 then "000" ++ toString v else "00" ++ toString v in
utf8Escape' (p ++ "\\u" ++ s) l
else
utf8Escape' (p.push c) l
def utf8Escape (l:String) (s:String) : String := (utf8Escape' (l.push '\"') s.data).push '\"'
/-
partial
def toString : Value → String
| (object m) :=
let f (s:String) (k:String) (v:Value) : String
:= (if s.isEmpty then "" else s ++ ", ")
++ k ++ ": " ++ toString v in
"{" ++ m.fold f "" ++ "}"
| (array a) := a.iterate "[" (λi v s, s ++ (if i.val = 0 then "" else ", ") ++ toString v) ++ "]"
| (string s) := "\"" ++ utf8Escape s ++ "\""
| (number s) := s.toString
| (bool b) := if b then "true" else "false"
| null := "null"
-/
partial
def toStringPre : String → Value → String
| l (object m) :=
let f (s:Bool × String) (k:String) (v:Value) : Bool × String
:= (False, toStringPre (utf8Escape (if s.fst then s.snd else s.snd ++ ", ") k ++ ": ") v) in
(m.fold f (True, l ++ "{")).snd ++ "}"
| l (array a) := a.iterate (l ++ "[") (λi v s, toStringPre (s ++ (if i.val = 0 then "" else ", ")) v) ++ "]"
| l (string s) := utf8Escape (l.push '\"') s ++ "\""
| l (number s) := l ++ s.toString
| l (bool b) := l ++ (if b then "true" else "false")
| l null := l ++ "null"
instance : HasToString Value := ⟨toStringPre ""⟩
section read
variable {m: Type → Type}
variable [h:ReadMonad m]
include h
attribute [instance] monadInhabited
open MonadFail
open ReadMonad
-- This reads a string lit until reaching the trailing quote.
-- The argument is the string so far.
partial
def readStringLit' : String → m String | l := do
c ← read,
if c = '\"' then -- Quote
pure l
else if c = '\\' then do -- Reverse solidus
d ← read,
match d with
| '\"' := readStringLit' (l.push c)
| '\\' := readStringLit' (l.push c)
| '/' := readStringLit' (l.push c)
| 'b' := readStringLit' (l.push '\x08')
| 'f' := readStringLit' (l.push '\x0c')
| 'n' := readStringLit' (l.push '\n')
| 'r' := readStringLit' (l.push '\x0d')
| 't' := readStringLit' (l.push '\t')
| 'u' := do
n ← readN 4,
(when (not (n.all Char.isHexDigit)) $ fail ("Expected hex digits, found " ++ repr n)),
let r := n.hexToNat,
-- TODO: Consider checking this is not a control character and isValidChar
readStringLit' (l.push (Char.ofNat r))
| _ := fail ("Unexpected escape character " ++ repr d)
else
readStringLit' (String.singleton c ++ l)
partial
def readStringLit : Unit → m String | () := do
c ← read,
if c.isWhitespace then
readStringLit ()
else if c = '\"' then
readStringLit' ""
else
fail "Expected start of string literal."
-- This reads a natural number given a nat containing digits read so far.
partial
def readNat' : Nat → m Nat | r := do
b ← atEnd,
if b then
pure r
else do
c ← peek,
if c.isDigit then
readNat' (10 * r + (c.toNat - '0'.toNat))
else
pure r
partial
def readNat : m Nat := do
c ← read,
if c = '0' then
pure 0
else if c.isDigit then
readNat' (c.toNat - '0'.toNat)
else
fail $ "Expected a digit, found " ++ repr c
-- This reads a natural number, and returns it along with the number of digits read.
partial
def readNatWithDigits' : ℕ → ℕ → m (Nat × Nat) | n r := do
b ← atEnd,
if b then
pure (n,r)
else do
c ← peek,
if c.isDigit then do
skip,
readNatWithDigits' (n+1) (10 * r + (c.toNat - '0'.toNat))
else
pure (n,r)
-- Read a digit
def readDigit : m ℕ := do
d ← read,
(when (not d.isDigit) $ fail "Expected a digit"),
pure (d.toNat - '0'.toNat)
-- This reads a decimal number "(.yyy)"
def readDecimal (p:Nat) : m Scientific := do
b ← atEnd,
if b then
pure ⟨p,0⟩
else do
c ← peek,
if c = '.' then do
skip,
d ← readDigit,
(n,r) ← readNatWithDigits' 1 (10 * p + d),
pure ⟨r, - (n:Int)⟩
else
pure ⟨p,0⟩
-- Read an optional exponent string of form ([e,E](+/-)nnnn)
def readExponent (n:Scientific) : m Scientific := do
b ← atEnd,
if b then
pure n
else do
-- Look ahead for exponent
c ← peek,
if c = 'e' ∨ c = 'E' then do
skip,
d ← read,
if d = '+' then do
e ← readNat,
pure { n with exponent := n.exponent + e }
else if d = '-' then do
e ← readNat,
pure { n with exponent := n.exponent - e }
else do
e ← readNat,
pure { n with exponent := n.exponent + e }
else
pure n
def expect (pre:String) (r:String) : m Unit := do
e ← readN r.length,
when (e ≠ r) (fail $ "Expected token " ++ repr (pre ++ r))
partial
def readColon : Unit → m Unit | () := do
c ← read,
if c.isWhitespace then do
readColon ()
else if c = ':' then
pure ()
else
fail ("Unexpected character: " ++ repr c)
section
variable {α : Type _}
variable {β : α → Type _}
instance inhabited : Inhabited (RBNode α β) := ⟨RBNode.leaf⟩
end
partial
def readBindings' {α} (readVal : m α)
: RBNode String (λ_, α) → m (RBNode String (λ_, α))
| bindings := do
c ← read,
if c.isWhitespace then
readBindings' bindings
else if c = '}' then
pure bindings
else if c = ',' then do
nm ← readStringLit (),
readColon (),
v ← readVal,
(match RBNode.find stringLt bindings nm with
| Option.none := pure ()
| (Option.some _) := fail $ "Name " ++ repr nm ++ " already bound."),
readBindings' (bindings.insert stringLt nm v)
else
fail "Expected field name or '}'"
partial
def readBindings {α} (readVal : m α) : Unit → m (RBNode String (λ_, α))
| bindings := do
c ← read,
if c.isWhitespace then
readBindings ()
else if c = '}' then
pure RBNode.leaf
else if c = '\"' then do
nm ← readStringLit' "",
readColon (),
v ← readVal,
readBindings' readVal (RBNode.leaf.insert stringLt nm v)
else
fail "Expected field name or '}'"
partial
def readArray' {α} (readVal : m α)
: Array α → m (Array α)
| prev := do
c ← read,
if c.isWhitespace then
readArray' prev
else if c = ']' then
pure prev
else do
v ← readVal,
readArray' (prev.push v)
instance : Inhabited Value := ⟨Value.null⟩
partial
def readValue' : Unit → m Value | () := do
c ← ReadMonad.read,
if c.isWhitespace then
readValue' ()
else if c = '\"' then do
Value.string <$> readStringLit' ""
else if c = '-' then do -- Negative scientific
n ← (readNat >>= readDecimal) >>= readExponent,
pure (Value.number { n with numerator := - n.numerator })
else if c = '0' then do
n ← readDecimal 0 >>= readExponent,
pure (Value.number n)
else if '1' ≤ c ∧ c ≤ '9' then do
n ← (readNat' (c.toNat - '0'.toNat) >>= readDecimal) >>= readExponent,
pure (Value.number n)
else if c = '{' then do
-- Read object.
Value.object <$> readBindings (readValue' ()) ()
else if c = '[' then -- Start of array
-- Read array
Value.array <$> readArray' (readValue' ()) Array.empty
else if c = 't' then
expect "t" "rue" *> pure Value.true
else if c = 'f' then
expect "f" "alse" *> pure Value.false
else if c = 'n' then
expect "n" "ull" *> pure Value.null
else
fail ("Unexpected character " ++ repr c)
def readValue : m Value := readValue' ()
end read
end Value
end json
|
7c91e4d247029ee04e1e0fe5b1c4b1afa9c342bd | cc62cd292c1acc80a10b1c645915b70d2cdee661 | /src/category_theory/universal/monic.lean | 99f3b0896e8a1861caad554029d8693fd84a3db5 | [] | no_license | RitaAhmadi/lean-category-theory | 4afb881c4b387ee2c8ce706c454fbf9db8897a29 | a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e | refs/heads/master | 1,651,786,183,402 | 1,565,604,314,000 | 1,565,604,314,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,020 | 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.limits.equalizers
-- import category_theory.abelian.monic
-- open category_theory
-- open category_theory.limits
-- namespace category_theory.universal.monic
-- universes u v
-- variables {C : Type u} [category.{u v} C] {X Y Z : C}
-- structure regular_mono (f : X ⟶ Y) :=
-- (Z : C)
-- (a b : Y ⟶ Z)
-- (w : f ≫ a = f ≫ b)
-- (e : is_equalizer ⟨ ⟨ X ⟩, f, w ⟩)
-- -- EXERCISE
-- -- def SplitMonic_implies_RegularMonic
-- -- {f : Hom X Y}
-- -- (s : SplitMonic f) : RegularMonic f := sorry
-- -- EXERCISE
-- -- def RegularMonic_implies_Monic
-- -- {f : Hom X Y}
-- -- (s : RegularMonic f) : Monic f := sorry
-- structure regular_epi (f : Y ⟶ Z) :=
-- (X : C)
-- (a b : X ⟶ Y)
-- (w : a ≫ f = b ≫ f)
-- (c : is_coequalizer ⟨ ⟨ Z ⟩, f, w ⟩)
-- end category_theory.universal.monic |
2a9bcb9492efb2da5aacc12de9ab012088cdab68 | 1b8f093752ba748c5ca0083afef2959aaa7dace5 | /src/category_theory/examples/groups/forgetful.lean | e0bd60a1bb1f9722896b2d7900e0bb8e0d4eb408 | [] | no_license | khoek/lean-category-theory | 7ec4cda9cc64a5a4ffeb84712ac7d020dbbba386 | 63dcb598e9270a3e8b56d1769eb4f825a177cd95 | refs/heads/master | 1,585,251,725,759 | 1,539,344,445,000 | 1,539,344,445,000 | 145,281,070 | 0 | 0 | null | 1,534,662,376,000 | 1,534,662,376,000 | null | UTF-8 | Lean | false | false | 2,040 | lean | -- Copyright (c) 2018 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import category_theory.examples.groups
import category_theory.types
import category_theory.representable
import algebra.group_power
namespace category_theory.examples.groups
open category_theory
open category_theory.yoneda
universes u₁ u₂
def ForgetfulFunctor_Groups_to_Types : Group ⥤ (Type u₁) :=
{ obj := λ s, s.1,
map' := λ s t f x, f.map x }
local attribute [search] semigroup.mul_assoc
instance ulift_group {α : Type u₁} [group α] : group (ulift.{u₂} α) :=
begin
refine { one := ulift.up 1,
mul := λ x y, ulift.up (x.down * y.down),
inv := λ x, ulift.up ((x.down)⁻¹),
.. } ; obviously
end
instance integers_as_group : group ℤ :=
begin
refine {
one := 0,
mul := λ x y, x + y,
inv := λ x, -x,
..
} ; obviously
end
-- TODO fix inconsistent naming of monoid.pow and gpow in mathlib
local attribute [class] is_group_hom
instance exponentiation_is_hom (G : Group) (g : G.1) : is_group_hom (λ (n : ℤ), gpow g n) := begin tidy, sorry end
instance exponentiation_is_hom' (G : Group) (g : G.1) : is_group_hom (λ (n : _root_.ulift ℤ), gpow g (n.down)) := begin tidy, sorry end
@[simp] lemma hom_exponentiation (G : Group) (f : _root_.ulift ℤ → G.1) [is_group_hom f] (n : ℤ) : gpow (f (ulift.up int.one)) n = f (ulift.up n) := sorry
@[simp] lemma monoid_pow_one {G} [group G] (x : G) : monoid.pow x 1 = x := begin sorry, end
instance Groups_ForgetfulFunctor_Representable : representable (ForgetfulFunctor_Groups_to_Types.{u₁}) :=
{ c := ⟨ _root_.ulift ℤ, by apply_instance ⟩,
Φ := { hom := { app := λ G g, ⟨λ n, gpow g n.down, begin tidy, sorry end⟩,
naturality' := sorry },
inv := { app := λ G f, f.map (ulift.up (1 : ℤ)), },
hom_inv_id' := sorry,
inv_hom_id' := sorry, } }
end category_theory.examples.groups |
bde636fb1ba808142c1b982205c8f0742684e097 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Elab/PreDefinition/Main.lean | 1440adee0bf683ef4713bf1353d088a0158f7a64 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 3,550 | 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.Elab.PreDefinition.Basic
import Lean.Elab.PreDefinition.Structural
import Lean.Elab.PreDefinition.WF
namespace Lean.Elab
open Meta
open Term
private def addAndCompilePartial (preDefs : Array PreDefinition) : TermElabM Unit := do
for preDef in preDefs do
trace[Elab.definition] "processing {preDef.declName}"
forallTelescope preDef.type fun xs type => do
let inh ← liftM $ mkInhabitantFor preDef.declName xs type
trace[Elab.definition] "inhabitant for {preDef.declName}"
addNonRec { preDef with
kind := DefKind.«opaque»,
value := inh
}
addAndCompilePartialRec preDefs
private def isNonRecursive (preDef : PreDefinition) : Bool :=
Option.isNone $ preDef.value.find? fun
| Expr.const declName _ _ => preDef.declName == declName
| _ => false
private def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) :=
let getPreDef := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get!
let vertices := preDefs.toList.map (·.declName)
let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors =>
if preDefs.any fun preDef => preDef.declName == declName then
declName :: successors
else
successors
let sccs := SCC.scc vertices successorsOf
sccs.toArray.map fun scc => scc.toArray.map getPreDef
private def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do
collectMVars preDef.value
collectMVars preDef.type
private def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do
let (_, s) ← (collectMVarsAtPreDef preDef).run {}
pure s.result
private def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM PreDefinition := do
let pendingMVarIds ← getMVarsAtPreDef preDef
if (← logUnassignedUsingErrorInfos pendingMVarIds) then
let preDef := { preDef with value := (← mkSorry preDef.type (synthetic := true)) }
if (← getMVarsAtPreDef preDef).isEmpty then
return preDef
else
throwAbortCommand
else
return preDef
def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := do
for preDef in preDefs do
trace[Elab.definition.body] "{preDef.declName} : {preDef.type} :=\n{preDef.value}"
let preDefs ← preDefs.mapM ensureNoUnassignedMVarsAtPreDef
for preDefs in partitionPreDefs preDefs do
trace[Elab.definition.scc] "{preDefs.map (·.declName)}"
if preDefs.size == 1 && isNonRecursive preDefs[0] then
let preDef := preDefs[0]
if preDef.modifiers.isNoncomputable then
addNonRec preDef
else
addAndCompileNonRec preDef
else if preDefs.any (·.modifiers.isUnsafe) then
addAndCompileUnsafe preDefs
else if preDefs.any (·.modifiers.isPartial) then
addAndCompilePartial preDefs
else withRef (preDefs[0].ref) do
mapError
(orelseMergeErrors
(structuralRecursion preDefs)
(WFRecursion preDefs))
(fun msg =>
let preDefMsgs := preDefs.toList.map (MessageData.ofExpr $ mkConst ·.declName)
m!"fail to show termination for{indentD (MessageData.joinSep preDefMsgs Format.line)}\nwith errors\n{msg}")
builtin_initialize
registerTraceClass `Elab.definition.body
registerTraceClass `Elab.definition.scc
end Lean.Elab
|
b6ae94a1145faa7fe150872eea0768b5dc013b1f | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/equiv/ring.lean | d92caeec931193574552644c795c2ab4b295a436 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 11,036 | 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 data.equiv.mul_add
import algebra.field
import algebra.opposites
/-!
# (Semi)ring equivs
In this file we define extension of `equiv` called `ring_equiv`, which is a datatype representing an
isomorphism of `semiring`s, `ring`s, `division_ring`s, or `field`s. We also introduce the
corresponding group of automorphisms `ring_aut`.
## Notations
The extended equiv have coercions to functions, and the coercion is the canonical notation when
treating the isomorphism as maps.
## Implementation notes
The fields for `ring_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are
deprecated.
Definition of multiplication in the groups of automorphisms agrees with function composition,
multiplication in `equiv.perm`, and multiplication in `category_theory.End`, not with
`category_theory.comp`.
## Tags
equiv, mul_equiv, add_equiv, ring_equiv, mul_aut, add_aut, ring_aut
-/
variables {R : Type*} {S : Type*} {S' : Type*}
set_option old_structure_cmd true
/- (semi)ring equivalence. -/
structure ring_equiv (R S : Type*) [has_mul R] [has_add R] [has_mul S] [has_add S]
extends R ≃ S, R ≃* S, R ≃+ S
infix ` ≃+* `:25 := ring_equiv
namespace ring_equiv
section basic
variables [has_mul R] [has_add R] [has_mul S] [has_add S] [has_mul S'] [has_add S']
instance : has_coe_to_fun (R ≃+* S) := ⟨_, ring_equiv.to_fun⟩
@[simp] lemma to_fun_eq_coe_fun (f : R ≃+* S) : f.to_fun = f := rfl
instance has_coe_to_mul_equiv : has_coe (R ≃+* S) (R ≃* S) := ⟨ring_equiv.to_mul_equiv⟩
instance has_coe_to_add_equiv : has_coe (R ≃+* S) (R ≃+ S) := ⟨ring_equiv.to_add_equiv⟩
@[norm_cast] lemma coe_mul_equiv (f : R ≃+* S) (a : R) :
(f : R ≃* S) a = f a := rfl
@[norm_cast] lemma coe_add_equiv (f : R ≃+* S) (a : R) :
(f : R ≃+ S) a = f a := rfl
variable (R)
/-- The identity map is a ring isomorphism. -/
@[refl] protected def refl : R ≃+* R := { .. mul_equiv.refl R, .. add_equiv.refl R }
@[simp] lemma refl_apply (x : R) : ring_equiv.refl R x = x := rfl
@[simp] lemma coe_add_equiv_refl : (ring_equiv.refl R : R ≃+ R) = add_equiv.refl R := rfl
@[simp] lemma coe_mul_equiv_refl : (ring_equiv.refl R : R ≃* R) = mul_equiv.refl R := rfl
variables {R}
/-- The inverse of a ring isomorphism is a ring isomorphism. -/
@[symm] protected def symm (e : R ≃+* S) : S ≃+* R :=
{ .. e.to_mul_equiv.symm, .. e.to_add_equiv.symm }
/-- Transitivity of `ring_equiv`. -/
@[trans] protected def trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') : R ≃+* S' :=
{ .. (e₁.to_mul_equiv.trans e₂.to_mul_equiv), .. (e₁.to_add_equiv.trans e₂.to_add_equiv) }
protected lemma bijective (e : R ≃+* S) : function.bijective e := e.to_equiv.bijective
protected lemma injective (e : R ≃+* S) : function.injective e := e.to_equiv.injective
protected lemma surjective (e : R ≃+* S) : function.surjective e := e.to_equiv.surjective
@[simp] lemma apply_symm_apply (e : R ≃+* S) : ∀ x, e (e.symm x) = x := e.to_equiv.apply_symm_apply
@[simp] lemma symm_apply_apply (e : R ≃+* S) : ∀ x, e.symm (e x) = x := e.to_equiv.symm_apply_apply
lemma image_eq_preimage (e : R ≃+* S) (s : set R) : e '' s = e.symm ⁻¹' s :=
e.to_equiv.image_eq_preimage s
end basic
section comm_semiring
open opposite
variables (R) [comm_semiring R]
/-- A commutative ring is isomorphic to its opposite. -/
def to_opposite : R ≃+* Rᵒᵖ :=
{ map_add' := λ x y, rfl,
map_mul' := λ x y, mul_comm (op y) (op x),
..equiv_to_opposite }
@[simp]
lemma to_opposite_apply (r : R) : to_opposite R r = op r := rfl
@[simp]
lemma to_opposite_symm_apply (r : Rᵒᵖ) : (to_opposite R).symm r = unop r := rfl
end comm_semiring
section semiring
variables [semiring R] [semiring S] (f : R ≃+* S) (x y : R)
/-- A ring isomorphism preserves multiplication. -/
@[simp] lemma map_mul : f (x * y) = f x * f y := f.map_mul' x y
/-- A ring isomorphism sends one to one. -/
@[simp] lemma map_one : f 1 = 1 := (f : R ≃* S).map_one
/-- A ring isomorphism preserves addition. -/
@[simp] lemma map_add : f (x + y) = f x + f y := f.map_add' x y
/-- A ring isomorphism sends zero to zero. -/
@[simp] lemma map_zero : f 0 = 0 := (f : R ≃+ S).map_zero
variable {x}
@[simp] lemma map_eq_one_iff : f x = 1 ↔ x = 1 := (f : R ≃* S).map_eq_one_iff
@[simp] lemma map_eq_zero_iff : f x = 0 ↔ x = 0 := (f : R ≃+ S).map_eq_zero_iff
lemma map_ne_one_iff : f x ≠ 1 ↔ x ≠ 1 := (f : R ≃* S).map_ne_one_iff
lemma map_ne_zero_iff : f x ≠ 0 ↔ x ≠ 0 := (f : R ≃+ S).map_ne_zero_iff
/-- Produce a ring isomorphism from a bijective ring homomorphism. -/
noncomputable def of_bijective (f : R →+* S) (hf : function.bijective f) : R ≃+* S :=
{ .. equiv.of_bijective f hf, .. f }
end semiring
section
variables [ring R] [ring S] (f : R ≃+* S) (x y : R)
@[simp] lemma map_neg : f (-x) = -f x := (f : R ≃+ S).map_neg x
@[simp] lemma map_sub : f (x - y) = f x - f y := (f : R ≃+ S).map_sub x y
@[simp] lemma map_neg_one : f (-1) = -1 := f.map_one ▸ f.map_neg 1
end
section semiring_hom
variables [semiring R] [semiring S] [semiring S']
/-- Reinterpret a ring equivalence as a ring homomorphism. -/
def to_ring_hom (e : R ≃+* S) : R →+* S :=
{ .. e.to_mul_equiv.to_monoid_hom, .. e.to_add_equiv.to_add_monoid_hom }
instance has_coe_to_ring_hom : has_coe (R ≃+* S) (R →+* S) := ⟨ring_equiv.to_ring_hom⟩
@[norm_cast] lemma coe_ring_hom (f : R ≃+* S) (a : R) :
(f : R →+* S) a = f a := rfl
/-- Reinterpret a ring equivalence as a monoid homomorphism. -/
abbreviation to_monoid_hom (e : R ≃+* S) : R →* S := e.to_ring_hom.to_monoid_hom
/-- Reinterpret a ring equivalence as an `add_monoid` homomorphism. -/
abbreviation to_add_monoid_hom (e : R ≃+* S) : R →+ S := e.to_ring_hom.to_add_monoid_hom
@[simp]
lemma to_ring_hom_refl : (ring_equiv.refl R).to_ring_hom = ring_hom.id R := rfl
@[simp]
lemma to_monoid_hom_refl : (ring_equiv.refl R).to_monoid_hom = monoid_hom.id R := rfl
@[simp]
lemma to_add_monoid_hom_refl : (ring_equiv.refl R).to_add_monoid_hom = add_monoid_hom.id R := rfl
@[simp]
lemma to_ring_hom_apply_symm_to_ring_hom_apply (e : R ≃+* S) :
∀ (y : S), e.to_ring_hom (e.symm.to_ring_hom y) = y :=
e.to_equiv.apply_symm_apply
@[simp]
lemma symm_to_ring_hom_apply_to_ring_hom_apply (e : R ≃+* S) :
∀ (x : R), e.symm.to_ring_hom (e.to_ring_hom x) = x :=
equiv.symm_apply_apply (e.to_equiv)
@[simp]
lemma to_ring_hom_trans (e₁ : R ≃+* S) (e₂ : S ≃+* S') :
(e₁.trans e₂).to_ring_hom = e₂.to_ring_hom.comp e₁.to_ring_hom := rfl
/--
Construct an equivalence of rings from homomorphisms in both directions, which are inverses.
-/
def of_hom_inv (hom : R →+* S) (inv : S →+* R)
(hom_inv_id : inv.comp hom = ring_hom.id R) (inv_hom_id : hom.comp inv = ring_hom.id S) :
R ≃+* S :=
{ inv_fun := inv,
left_inv := λ x, ring_hom.congr_fun hom_inv_id x,
right_inv := λ x, ring_hom.congr_fun inv_hom_id x,
..hom }
@[simp]
lemma of_hom_inv_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (r : R) :
(of_hom_inv hom inv hom_inv_id inv_hom_id) r = hom r := rfl
@[simp]
lemma of_hom_inv_symm_apply (hom : R →+* S) (inv : S →+* R) (hom_inv_id inv_hom_id) (s : S) :
(of_hom_inv hom inv hom_inv_id inv_hom_id).symm s = inv s := rfl
end semiring_hom
end ring_equiv
namespace mul_equiv
/-- Gives a `ring_equiv` from a `mul_equiv` preserving addition.-/
def to_ring_equiv {R : Type*} {S : Type*} [has_add R] [has_add S] [has_mul R] [has_mul S]
(h : R ≃* S) (H : ∀ x y : R, h (x + y) = h x + h y) : R ≃+* S :=
{..h.to_equiv, ..h, ..add_equiv.mk' h.to_equiv H }
end mul_equiv
namespace ring_equiv
variables [has_add R] [has_add S] [has_mul R] [has_mul S]
/-- Two ring isomorphisms agree if they are defined by the
same underlying function. -/
@[ext] lemma ext {f g : R ≃+* S} (h : ∀ x, f x = g x) : f = g :=
begin
have h₁ : f.to_equiv = g.to_equiv := equiv.ext h,
cases f, cases g, congr,
{ exact (funext h) },
{ exact congr_arg equiv.inv_fun h₁ }
end
@[simp] theorem trans_symm (e : R ≃+* S) : e.trans e.symm = ring_equiv.refl R := ext e.3
@[simp] theorem symm_trans (e : R ≃+* S) : e.symm.trans e = ring_equiv.refl S := ext e.4
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected lemma is_integral_domain {A : Type*} (B : Type*) [ring A] [ring B]
(hB : is_integral_domain B) (e : A ≃+* B) : is_integral_domain A :=
{ mul_comm := λ x y, have e.symm (e x * e y) = e.symm (e y * e x), by rw hB.mul_comm, by simpa,
eq_zero_or_eq_zero_of_mul_eq_zero := λ x y hxy,
have e x * e y = 0, by rw [← e.map_mul, hxy, e.map_zero],
(hB.eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).imp (λ hx, by simpa using congr_arg e.symm hx)
(λ hy, by simpa using congr_arg e.symm hy),
exists_pair_ne := ⟨e.symm 0, e.symm 1,
by { haveI : nontrivial B := hB.to_nontrivial, exact e.symm.injective.ne zero_ne_one }⟩ }
/-- If two rings are isomorphic, and the second is an integral domain, then so is the first. -/
protected def integral_domain {A : Type*} (B : Type*) [ring A] [integral_domain B]
(e : A ≃+* B) : integral_domain A :=
{ .. (‹_› : ring A), .. e.is_integral_domain B (integral_domain.to_is_integral_domain B) }
end ring_equiv
/-- The group of ring automorphisms. -/
@[reducible] def ring_aut (R : Type*) [has_mul R] [has_add R] := ring_equiv R R
namespace ring_aut
variables (R) [has_mul R] [has_add R]
/--
The group operation on automorphisms of a ring is defined by
λ g h, ring_equiv.trans h g.
This means that multiplication agrees with composition, (g*h)(x) = g (h x) .
-/
instance : group (ring_aut R) :=
by refine_struct
{ mul := λ g h, ring_equiv.trans h g,
one := ring_equiv.refl R,
inv := ring_equiv.symm };
intros; ext; try { refl }; apply equiv.left_inv
instance : inhabited (ring_aut R) := ⟨1⟩
/-- Monoid homomorphism from ring automorphisms to additive automorphisms. -/
def to_add_aut : ring_aut R →* add_aut R :=
by refine_struct { to_fun := ring_equiv.to_add_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to multiplicative automorphisms. -/
def to_mul_aut : ring_aut R →* mul_aut R :=
by refine_struct { to_fun := ring_equiv.to_mul_equiv }; intros; refl
/-- Monoid homomorphism from ring automorphisms to permutations. -/
def to_perm : ring_aut R →* equiv.perm R :=
by refine_struct { to_fun := ring_equiv.to_equiv }; intros; refl
end ring_aut
namespace equiv
variables (K : Type*) [division_ring K]
def units_equiv_ne_zero : units K ≃ {a : K | a ≠ 0} :=
⟨λ a, ⟨a.1, a.ne_zero⟩, λ a, units.mk0 _ a.2, λ ⟨_, _, _, _⟩, units.ext rfl, λ ⟨_, _⟩, rfl⟩
variable {K}
@[simp]
lemma coe_units_equiv_ne_zero (a : units K) :
((units_equiv_ne_zero K a) : K) = a := rfl
end equiv
|
166160bb042484b4723fe859fe844363fed31859 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/lean/string_imp2.lean | 28c75e262d17bf1cf2284fe4acb4a9acdc8e23df | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,694 | lean |
def f (s : String) : String :=
s ++ " " ++ s
def g (s : String) : String :=
s.push ' ' ++ s.push '-'
def h (s : String) : String :=
let it₁ := s.mkIterator;
let it₂ := it₁.next;
it₁.remainingToString ++ "-" ++ it₂.remainingToString
#eval "hello" ++ "hello"
#eval f "hello"
#eval (f "αβ").length
#eval "hello".toList
#eval "αβ".toList
#eval "".toList
#eval "αβγ".toList
#eval "αβγ".mkIterator.1
#eval "αβγ".mkIterator.next.1
#eval "αβγ".mkIterator.next.next.1
#eval "αβγ".mkIterator.next.2
#eval "αβ".1
#eval "αβ".push 'a'
#eval g "α"
#eval "".mkIterator.curr
#eval ("αβγ".mkIterator.setCurr 'a').toString
#eval (("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').toString
#eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').next.setCurr 'c').toString
#eval ((("αβγ".mkIterator.setCurr 'a').next.setCurr 'b').prev.setCurr 'c').toString
#eval ("abc".mkIterator.setCurr '0').toString
#eval (("abc".mkIterator.setCurr '0').next.setCurr '1').toString
#eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').next.setCurr '2').toString
#eval ((("abc".mkIterator.setCurr '0').next.setCurr '1').prev.setCurr '2').toString
#eval ("abc".mkIterator.setCurr (Char.ofNat 955)).toString
#eval h "abc"
#eval "abc".mkIterator.remainingToString
#eval ("a".push (Char.ofNat 0)) ++ "bb"
#eval (("a".push (Char.ofNat 0)) ++ "αb").length
#eval "".mkIterator.hasNext
#eval "a".mkIterator.hasNext
#eval "a".mkIterator.next.hasNext
#eval "".mkIterator.hasPrev
#eval "a".mkIterator.next.hasPrev
#eval "αβ".mkIterator.next.hasPrev
#eval "αβ".mkIterator.next.prev.hasPrev
#eval "abc" == "abc"
#eval "abc" == "abd"
#eval "αβγ".drop 1
#eval "αβγ".takeRight 1
|
3e8a68f380a9e13662034d9d51edca17ade9ba07 | 7b02c598aa57070b4cf4fbfe2416d0479220187f | /algebra/free_group.hlean | 125332d7deba2027fc7983a27db9e8e35a951afd | [
"Apache-2.0"
] | permissive | jdchristensen/Spectral | 50d4f0ddaea1484d215ef74be951da6549de221d | 6ded2b94d7ae07c4098d96a68f80a9cd3d433eb8 | refs/heads/master | 1,611,555,010,649 | 1,496,724,191,000 | 1,496,724,191,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,824 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Egbert Rijke
Constructions with groups
-/
import algebra.group_theory hit.set_quotient types.list types.sum
open eq algebra is_trunc set_quotient relation sigma sigma.ops prod sum list trunc function equiv
namespace group
variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup}
/- Free Group of a set -/
variables (X : Set) {l l' : list (X ⊎ X)}
namespace free_group
inductive free_group_rel : list (X ⊎ X) → list (X ⊎ X) → Type :=
| rrefl : Πl, free_group_rel l l
| cancel1 : Πx, free_group_rel [inl x, inr x] []
| cancel2 : Πx, free_group_rel [inr x, inl x] []
| resp_append : Π{l₁ l₂ l₃ l₄}, free_group_rel l₁ l₂ → free_group_rel l₃ l₄ →
free_group_rel (l₁ ++ l₃) (l₂ ++ l₄)
| rtrans : Π{l₁ l₂ l₃}, free_group_rel l₁ l₂ → free_group_rel l₂ l₃ →
free_group_rel l₁ l₃
open free_group_rel
local abbreviation R [reducible] := free_group_rel
attribute free_group_rel.rrefl [refl]
definition free_group_carrier [reducible] : Type := set_quotient (λx y, ∥R X x y∥)
local abbreviation FG := free_group_carrier
definition is_reflexive_R : is_reflexive (λx y, ∥R X x y∥) :=
begin constructor, intro s, apply tr, unfold R end
local attribute is_reflexive_R [instance]
variable {X}
theorem rel_respect_flip (r : R X l l') : R X (map sum.flip l) (map sum.flip l') :=
begin
induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂,
{ reflexivity},
{ repeat esimp [map], exact cancel2 x},
{ repeat esimp [map], exact cancel1 x},
{ rewrite [+map_append], exact resp_append IH₁ IH₂},
{ exact rtrans IH₁ IH₂}
end
theorem rel_respect_reverse (r : R X l l') : R X (reverse l) (reverse l') :=
begin
induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂,
{ reflexivity},
{ repeat esimp [map], exact cancel2 x},
{ repeat esimp [map], exact cancel1 x},
{ rewrite [+reverse_append], exact resp_append IH₂ IH₁},
{ exact rtrans IH₁ IH₂}
end
definition free_group_one [constructor] : FG X := class_of []
definition free_group_inv [unfold 3] : FG X → FG X :=
quotient_unary_map (reverse ∘ map sum.flip)
(λl l', trunc_functor -1 (rel_respect_reverse ∘ rel_respect_flip))
definition free_group_mul [unfold 3 4] : FG X → FG X → FG X :=
quotient_binary_map append (λl l', trunc.elim (λr m m', trunc.elim (λs, tr (resp_append r s))))
section
local notation 1 := free_group_one
local postfix ⁻¹ := free_group_inv
local infix * := free_group_mul
theorem free_group_mul_assoc (g₁ g₂ g₃ : FG X) : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) :=
begin
refine set_quotient.rec_prop _ g₁,
refine set_quotient.rec_prop _ g₂,
refine set_quotient.rec_prop _ g₃,
clear g₁ g₂ g₃, intro g₁ g₂ g₃,
exact ap class_of !append.assoc
end
theorem free_group_one_mul (g : FG X) : 1 * g = g :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
exact ap class_of !append_nil_left
end
theorem free_group_mul_one (g : FG X) : g * 1 = g :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
exact ap class_of !append_nil_right
end
theorem free_group_mul_left_inv (g : FG X) : g⁻¹ * g = 1 :=
begin
refine set_quotient.rec_prop _ g, clear g, intro g,
apply eq_of_rel, apply tr,
induction g with s l IH,
{ reflexivity},
{ rewrite [▸*, map_cons, reverse_cons, concat_append],
refine rtrans _ IH,
apply resp_append, reflexivity,
change R X ([flip s, s] ++ l) ([] ++ l),
apply resp_append,
induction s, apply cancel2, apply cancel1,
reflexivity}
end
end
end free_group open free_group
-- export [reduce_hints] free_group
variables (X)
definition group_free_group [constructor] : group (free_group_carrier X) :=
group.mk _ free_group_mul free_group_mul_assoc free_group_one free_group_one_mul
free_group_mul_one free_group_inv free_group_mul_left_inv
definition free_group [constructor] : Group :=
Group.mk _ (group_free_group X)
/- The universal property of the free group -/
variables {X G}
definition free_group_inclusion [constructor] (x : X) : free_group X :=
class_of [inl x]
definition fgh_helper [unfold 5] (f : X → G) (g : G) (x : X + X) : G :=
g * sum.rec (λx, f x) (λx, (f x)⁻¹) x
theorem fgh_helper_respect_rel (f : X → G) (r : free_group_rel X l l')
: Π(g : G), foldl (fgh_helper f) g l = foldl (fgh_helper f) g l' :=
begin
induction r with l x x l₁ l₂ l₃ l₄ r₁ r₂ IH₁ IH₂ l₁ l₂ l₃ r₁ r₂ IH₁ IH₂: intro g,
{ reflexivity},
{ unfold [foldl], apply mul_inv_cancel_right},
{ unfold [foldl], apply inv_mul_cancel_right},
{ rewrite [+foldl_append, IH₁, IH₂]},
{ exact !IH₁ ⬝ !IH₂}
end
theorem fgh_helper_mul (f : X → G) (l)
: Π(g : G), foldl (fgh_helper f) g l = g * foldl (fgh_helper f) 1 l :=
begin
induction l with s l IH: intro g,
{ unfold [foldl], exact !mul_one⁻¹},
{ rewrite [+foldl_cons, IH], refine _ ⬝ (ap (λx, g * x) !IH⁻¹),
rewrite [-mul.assoc, ↑fgh_helper, one_mul]}
end
definition free_group_hom [constructor] (f : X → G) : free_group X →g G :=
begin
fapply homomorphism.mk,
{ intro g, refine set_quotient.elim _ _ g,
{ intro l, exact foldl (fgh_helper f) 1 l},
{ intro l l' r, esimp at *, refine trunc.rec _ r, clear r, intro r,
exact fgh_helper_respect_rel f r 1}},
{ refine set_quotient.rec_prop _, intro l, refine set_quotient.rec_prop _, intro l',
esimp, refine !foldl_append ⬝ _, esimp, apply fgh_helper_mul}
end
definition fn_of_free_group_hom [unfold_full] (φ : free_group X →g G) : X → G :=
φ ∘ free_group_inclusion
variables (X G)
definition free_group_hom_equiv_fn : (free_group X →g G) ≃ (X → G) :=
begin
fapply equiv.MK,
{ exact fn_of_free_group_hom},
{ exact free_group_hom},
{ intro f, apply eq_of_homotopy, intro x, esimp, unfold [foldl], apply one_mul},
{ intro φ, apply homomorphism_eq, refine set_quotient.rec_prop _, intro l, esimp,
induction l with s l IH,
{ esimp [foldl], exact (respect_one φ)⁻¹},
{ rewrite [foldl_cons, fgh_helper_mul],
refine _ ⬝ (respect_mul φ (class_of [s]) (class_of l))⁻¹,
rewrite [IH], induction s: rewrite [▸*, one_mul], rewrite [-respect_inv φ]}}
end
end group
|
4db92695709c6e069a09610262c99d62e434dcca | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /library/data/int/gcd.lean | 48715c573ada5725833a5d5647f4e531438b1dca | [
"Apache-2.0"
] | permissive | davidmueller13/lean | 65a3ed141b4088cd0a268e4de80eb6778b21a0e9 | c626e2e3c6f3771e07c32e82ee5b9e030de5b050 | refs/heads/master | 1,611,278,313,401 | 1,444,021,177,000 | 1,444,021,177,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,605 | lean | /-
Copyright (c) 2014 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Definitions and properties of gcd, lcm, and coprime.
-/
import .div data.nat.gcd
open eq.ops
namespace int
/- gcd -/
definition gcd (a b : ℤ) : ℤ := of_nat (nat.gcd (nat_abs a) (nat_abs b))
theorem gcd_nonneg (a b : ℤ) : gcd a b ≥ 0 :=
of_nat_nonneg (nat.gcd (nat_abs a) (nat_abs b))
theorem gcd.comm (a b : ℤ) : gcd a b = gcd b a :=
by rewrite [↑gcd, nat.gcd.comm]
theorem gcd_zero_right (a : ℤ) : gcd a 0 = abs a :=
by krewrite [↑gcd, nat.gcd_zero_right, of_nat_nat_abs]
theorem gcd_zero_left (a : ℤ) : gcd 0 a = abs a :=
by rewrite [gcd.comm, gcd_zero_right]
theorem gcd_one_right (a : ℤ) : gcd a 1 = 1 :=
by krewrite [↑gcd, nat.gcd_one_right]
theorem gcd_one_left (a : ℤ) : gcd 1 a = 1 :=
by rewrite [gcd.comm, gcd_one_right]
theorem gcd_abs_left (a b : ℤ) : gcd (abs a) b = gcd a b :=
by rewrite [↑gcd, *nat_abs_abs]
theorem gcd_abs_right (a b : ℤ) : gcd (abs a) b = gcd a b :=
by rewrite [↑gcd, *nat_abs_abs]
theorem gcd_abs_abs (a b : ℤ) : gcd (abs a) (abs b) = gcd a b :=
by rewrite [↑gcd, *nat_abs_abs]
theorem gcd_of_ne_zero (a : ℤ) {b : ℤ} (H : b ≠ 0) : gcd a b = gcd b (abs a mod abs b) :=
have nat_abs b ≠ nat.zero, from assume H', H (eq_zero_of_nat_abs_eq_zero H'),
have (#nat nat_abs b > nat.zero), from nat.pos_of_ne_zero this,
assert nat.gcd (nat_abs a) (nat_abs b) = (#nat nat.gcd (nat_abs b) (nat_abs a mod nat_abs b)),
from @nat.gcd_of_pos (nat_abs a) (nat_abs b) this,
calc
gcd a b = nat.gcd (nat_abs b) (#nat nat_abs a mod nat_abs b) : by rewrite [↑gcd, this]
... = gcd (abs b) (abs a mod abs b) :
by rewrite [↑gcd, -*of_nat_nat_abs, of_nat_mod]
... = gcd b (abs a mod abs b) : by rewrite [↑gcd, *nat_abs_abs]
theorem gcd_of_pos (a : ℤ) {b : ℤ} (H : b > 0) : gcd a b = gcd b (abs a mod b) :=
by rewrite [!gcd_of_ne_zero (ne_of_gt H), abs_of_pos H]
theorem gcd_of_nonneg_of_pos {a b : ℤ} (H1 : a ≥ 0) (H2 : b > 0) : gcd a b = gcd b (a mod b) :=
by rewrite [!gcd_of_pos H2, abs_of_nonneg H1]
theorem gcd_self (a : ℤ) : gcd a a = abs a :=
by rewrite [↑gcd, nat.gcd_self, of_nat_nat_abs]
theorem gcd_dvd_left (a b : ℤ) : gcd a b ∣ a :=
have gcd a b ∣ abs a,
by rewrite [↑gcd, -of_nat_nat_abs, of_nat_dvd_of_nat_iff]; apply nat.gcd_dvd_left,
iff.mp !dvd_abs_iff this
theorem gcd_dvd_right (a b : ℤ) : gcd a b ∣ b :=
by rewrite gcd.comm; apply gcd_dvd_left
theorem dvd_gcd {a b c : ℤ} : a ∣ b → a ∣ c → a ∣ gcd b c :=
begin
rewrite [↑gcd, -*(abs_dvd_iff a), -(dvd_abs_iff _ b), -(dvd_abs_iff _ c), -*of_nat_nat_abs],
rewrite [*of_nat_dvd_of_nat_iff] ,
apply nat.dvd_gcd
end
theorem gcd.assoc (a b c : ℤ) : gcd (gcd a b) c = gcd a (gcd b c) :=
dvd.antisymm !gcd_nonneg !gcd_nonneg
(dvd_gcd
(dvd.trans !gcd_dvd_left !gcd_dvd_left)
(dvd_gcd (dvd.trans !gcd_dvd_left !gcd_dvd_right) !gcd_dvd_right))
(dvd_gcd
(dvd_gcd !gcd_dvd_left (dvd.trans !gcd_dvd_right !gcd_dvd_left))
(dvd.trans !gcd_dvd_right !gcd_dvd_right))
theorem gcd_mul_left (a b c : ℤ) : gcd (a * b) (a * c) = abs a * gcd b c :=
by rewrite [↑gcd, *nat_abs_mul, nat.gcd_mul_left, of_nat_mul, of_nat_nat_abs]
theorem gcd_mul_right (a b c : ℤ) : gcd (a * b) (c * b) = gcd a c * abs b :=
by rewrite [mul.comm a, mul.comm c, mul.comm (gcd a c), gcd_mul_left]
theorem gcd_pos_of_ne_zero_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : gcd a b > 0 :=
have gcd a b ≠ 0, from
suppose gcd a b = 0,
have 0 ∣ a, from this ▸ gcd_dvd_left a b,
show false, from H (eq_zero_of_zero_dvd this),
lt_of_le_of_ne (gcd_nonneg a b) (ne.symm this)
theorem gcd_pos_of_ne_zero_right (a : ℤ) {b : ℤ} (H : b ≠ 0) : gcd a b > 0 :=
by rewrite gcd.comm; apply !gcd_pos_of_ne_zero_left H
theorem eq_zero_of_gcd_eq_zero_left {a b : ℤ} (H : gcd a b = 0) : a = 0 :=
decidable.by_contradiction
(suppose a ≠ 0,
have gcd a b > 0, from !gcd_pos_of_ne_zero_left this,
ne_of_lt this H⁻¹)
theorem eq_zero_of_gcd_eq_zero_right {a b : ℤ} (H : gcd a b = 0) : b = 0 :=
by rewrite gcd.comm at H; apply !eq_zero_of_gcd_eq_zero_left H
theorem gcd_div {a b c : ℤ} (H1 : c ∣ a) (H2 : c ∣ b) :
gcd (a div c) (b div c) = gcd a b div (abs c) :=
decidable.by_cases
(suppose c = 0,
calc
gcd (a div c) (b div c) = gcd 0 0 : by subst c; rewrite *div_zero
... = 0 : gcd_zero_left
... = gcd a b div 0 : div_zero
... = gcd a b div (abs c) : by subst c)
(suppose c ≠ 0,
have abs c ≠ 0, from assume H', this (eq_zero_of_abs_eq_zero H'),
eq.symm (div_eq_of_eq_mul_left this
(eq.symm (calc
gcd (a div c) (b div c) * abs c = gcd (a div c * c) (b div c * c) : gcd_mul_right
... = gcd a (b div c * c) : div_mul_cancel H1
... = gcd a b : div_mul_cancel H2))))
theorem gcd_dvd_gcd_mul_left (a b c : ℤ) : gcd a b ∣ gcd (c * a) b :=
dvd_gcd (dvd.trans !gcd_dvd_left !dvd_mul_left) !gcd_dvd_right
theorem gcd_dvd_gcd_mul_right (a b c : ℤ) : gcd a b ∣ gcd (a * c) b :=
!mul.comm ▸ !gcd_dvd_gcd_mul_left
theorem div_gcd_eq_div_gcd_of_nonneg {a₁ b₁ a₂ b₂ : ℤ} (H : a₁ * b₂ = a₂ * b₁)
(H1 : b₁ ≠ 0) (H2 : b₂ ≠ 0) (H3 : a₁ ≥ 0) (H4 : a₂ ≥ 0) :
a₁ div (gcd a₁ b₁) = a₂ div (gcd a₂ b₂) :=
begin
apply div_eq_div_of_dvd_of_dvd,
repeat (apply gcd_dvd_left),
intro H', apply H1, apply eq_zero_of_gcd_eq_zero_right H',
intro H', apply H2, apply eq_zero_of_gcd_eq_zero_right H',
rewrite [-abs_of_nonneg H3 at {1}, -abs_of_nonneg H4 at {2}],
rewrite [-gcd_mul_left, -gcd_mul_right, H, mul.comm b₁]
end
theorem div_gcd_eq_div_gcd {a₁ b₁ a₂ b₂ : ℤ} (H : a₁ * b₂ = a₂ * b₁) (H1 : b₁ > 0) (H2 : b₂ > 0) :
a₁ div (gcd a₁ b₁) = a₂ div (gcd a₂ b₂) :=
or.elim (le_or_gt 0 a₁)
(assume H3 : a₁ ≥ 0,
have H4 : a₂ * b₁ ≥ 0, by rewrite -H; apply mul_nonneg H3 (le_of_lt H2),
have H5 : a₂ ≥ 0, from nonneg_of_mul_nonneg_right H4 H1,
div_gcd_eq_div_gcd_of_nonneg H (ne_of_gt H1) (ne_of_gt H2) H3 H5)
(assume H3 : a₁ < 0,
have H4 : a₂ * b₁ < 0, by rewrite -H; apply mul_neg_of_neg_of_pos H3 H2,
assert H5 : a₂ < 0, from neg_of_mul_neg_right H4 (le_of_lt H1),
assert H6 : abs a₁ div (gcd (abs a₁) (abs b₁)) = abs a₂ div (gcd (abs a₂) (abs b₂)),
begin
apply div_gcd_eq_div_gcd_of_nonneg,
rewrite [abs_of_pos H1, abs_of_pos H2, abs_of_neg H3, abs_of_neg H5],
rewrite [-*neg_mul_eq_neg_mul, H],
apply ne_of_gt (abs_pos_of_pos H1),
apply ne_of_gt (abs_pos_of_pos H2),
repeat (apply abs_nonneg)
end,
have H7 : -a₁ div (gcd a₁ b₁) = -a₂ div (gcd a₂ b₂),
begin
rewrite [-abs_of_neg H3, -abs_of_neg H5, -gcd_abs_abs a₁],
rewrite [-gcd_abs_abs a₂ b₂],
exact H6
end,
calc
a₁ div (gcd a₁ b₁) = -(-a₁ div (gcd a₁ b₁)) :
by rewrite [neg_div_of_dvd !gcd_dvd_left, neg_neg]
... = -(-a₂ div (gcd a₂ b₂)) : H7
... = a₂ div (gcd a₂ b₂) :
by rewrite [neg_div_of_dvd !gcd_dvd_left, neg_neg])
/- lcm -/
definition lcm (a b : ℤ) : ℤ := of_nat (nat.lcm (nat_abs a) (nat_abs b))
theorem lcm_nonneg (a b : ℤ) : lcm a b ≥ 0 :=
of_nat_nonneg (nat.lcm (nat_abs a) (nat_abs b))
theorem lcm.comm (a b : ℤ) : lcm a b = lcm b a :=
by rewrite [↑lcm, nat.lcm.comm]
theorem lcm_zero_left (a : ℤ) : lcm 0 a = 0 :=
by krewrite [↑lcm, nat.lcm_zero_left]
theorem lcm_zero_right (a : ℤ) : lcm a 0 = 0 :=
!lcm.comm ▸ !lcm_zero_left
theorem lcm_one_left (a : ℤ) : lcm 1 a = abs a :=
by krewrite [↑lcm, nat.lcm_one_left, of_nat_nat_abs]
theorem lcm_one_right (a : ℤ) : lcm a 1 = abs a :=
!lcm.comm ▸ !lcm_one_left
theorem lcm_abs_left (a b : ℤ) : lcm (abs a) b = lcm a b :=
by rewrite [↑lcm, *nat_abs_abs]
theorem lcm_abs_right (a b : ℤ) : lcm (abs a) b = lcm a b :=
by rewrite [↑lcm, *nat_abs_abs]
theorem lcm_abs_abs (a b : ℤ) : lcm (abs a) (abs b) = lcm a b :=
by rewrite [↑lcm, *nat_abs_abs]
theorem lcm_self (a : ℤ) : lcm a a = abs a :=
by krewrite [↑lcm, nat.lcm_self, of_nat_nat_abs]
theorem dvd_lcm_left (a b : ℤ) : a ∣ lcm a b :=
by rewrite [↑lcm, -abs_dvd_iff, -of_nat_nat_abs, of_nat_dvd_of_nat_iff]; apply nat.dvd_lcm_left
theorem dvd_lcm_right (a b : ℤ) : b ∣ lcm a b :=
!lcm.comm ▸ !dvd_lcm_left
theorem gcd_mul_lcm (a b : ℤ) : gcd a b * lcm a b = abs (a * b) :=
begin
rewrite [↑gcd, ↑lcm, -of_nat_nat_abs, -of_nat_mul, of_nat_eq_of_nat_iff, nat_abs_mul],
apply nat.gcd_mul_lcm
end
theorem lcm_dvd {a b c : ℤ} : a ∣ c → b ∣ c → lcm a b ∣ c :=
begin
rewrite [↑lcm, -(abs_dvd_iff a), -(abs_dvd_iff b), -*(dvd_abs_iff _ c), -*of_nat_nat_abs],
rewrite [*of_nat_dvd_of_nat_iff] ,
apply nat.lcm_dvd
end
theorem lcm_assoc (a b c : ℤ) : lcm (lcm a b) c = lcm a (lcm b c) :=
dvd.antisymm !lcm_nonneg !lcm_nonneg
(lcm_dvd
(lcm_dvd !dvd_lcm_left (dvd.trans !dvd_lcm_left !dvd_lcm_right))
(dvd.trans !dvd_lcm_right !dvd_lcm_right))
(lcm_dvd
(dvd.trans !dvd_lcm_left !dvd_lcm_left)
(lcm_dvd (dvd.trans !dvd_lcm_right !dvd_lcm_left) !dvd_lcm_right))
/- coprime -/
abbreviation coprime (a b : ℤ) : Prop := gcd a b = 1
theorem coprime_swap {a b : ℤ} (H : coprime b a) : coprime a b :=
!gcd.comm ▸ H
theorem dvd_of_coprime_of_dvd_mul_right {a b c : ℤ} (H1 : coprime c b) (H2 : c ∣ a * b) : c ∣ a :=
assert H3 : gcd (a * c) (a * b) = abs a, from
calc
gcd (a * c) (a * b) = abs a * gcd c b : gcd_mul_left
... = abs a * 1 : H1
... = abs a : mul_one,
assert H4 : (c ∣ gcd (a * c) (a * b)), from dvd_gcd !dvd_mul_left H2,
by rewrite [-dvd_abs_iff, -H3]; apply H4
theorem dvd_of_coprime_of_dvd_mul_left {a b c : ℤ} (H1 : coprime c a) (H2 : c ∣ a * b) : c ∣ b :=
dvd_of_coprime_of_dvd_mul_right H1 (!mul.comm ▸ H2)
theorem gcd_mul_left_cancel_of_coprime {c : ℤ} (a : ℤ) {b : ℤ} (H : coprime c b) :
gcd (c * a) b = gcd a b :=
begin
revert H, rewrite [↑coprime, ↑gcd, *of_nat_eq_of_nat_iff, nat_abs_mul],
apply nat.gcd_mul_left_cancel_of_coprime
end
theorem gcd_mul_right_cancel_of_coprime (a : ℤ) {c b : ℤ} (H : coprime c b) :
gcd (a * c) b = gcd a b :=
!mul.comm ▸ !gcd_mul_left_cancel_of_coprime H
theorem gcd_mul_left_cancel_of_coprime_right {c a : ℤ} (b : ℤ) (H : coprime c a) :
gcd a (c * b) = gcd a b :=
!gcd.comm ▸ !gcd.comm ▸ !gcd_mul_left_cancel_of_coprime H
theorem gcd_mul_right_cancel_of_coprime_right {c a : ℤ} (b : ℤ) (H : coprime c a) :
gcd a (b * c) = gcd a b :=
!gcd.comm ▸ !gcd.comm ▸ !gcd_mul_right_cancel_of_coprime H
theorem coprime_div_gcd_div_gcd {a b : ℤ} (H : gcd a b ≠ 0) :
coprime (a div gcd a b) (b div gcd a b) :=
calc
gcd (a div gcd a b) (b div gcd a b)
= gcd a b div abs (gcd a b) : gcd_div !gcd_dvd_left !gcd_dvd_right
... = 1 : by rewrite [abs_of_nonneg !gcd_nonneg, div_self H]
theorem not_coprime_of_dvd_of_dvd {m n d : ℤ} (dgt1 : d > 1) (Hm : d ∣ m) (Hn : d ∣ n) :
¬ coprime m n :=
assume co : coprime m n,
assert d ∣ gcd m n, from dvd_gcd Hm Hn,
have d ∣ 1, by rewrite [↑coprime at co, co at this]; apply this,
have d ≤ 1, from le_of_dvd dec_trivial this,
show false, from not_lt_of_ge `d ≤ 1` `d > 1`
theorem exists_coprime {a b : ℤ} (H : gcd a b ≠ 0) :
exists a' b', coprime a' b' ∧ a = a' * gcd a b ∧ b = b' * gcd a b :=
have H1 : a = (a div gcd a b) * gcd a b, from (div_mul_cancel !gcd_dvd_left)⁻¹,
have H2 : b = (b div gcd a b) * gcd a b, from (div_mul_cancel !gcd_dvd_right)⁻¹,
exists.intro _ (exists.intro _ (and.intro (coprime_div_gcd_div_gcd H) (and.intro H1 H2)))
theorem coprime_mul {a b c : ℤ} (H1 : coprime a c) (H2 : coprime b c) : coprime (a * b) c :=
calc
gcd (a * b) c = gcd b c : !gcd_mul_left_cancel_of_coprime H1
... = 1 : H2
theorem coprime_mul_right {c a b : ℤ} (H1 : coprime c a) (H2 : coprime c b) : coprime c (a * b) :=
coprime_swap (coprime_mul (coprime_swap H1) (coprime_swap H2))
theorem coprime_of_coprime_mul_left {c a b : ℤ} (H : coprime (c * a) b) : coprime a b :=
have H1 : (gcd a b ∣ gcd (c * a) b), from !gcd_dvd_gcd_mul_left,
eq_one_of_dvd_one !gcd_nonneg (H ▸ H1)
theorem coprime_of_coprime_mul_right {c a b : ℤ} (H : coprime (a * c) b) : coprime a b :=
coprime_of_coprime_mul_left (!mul.comm ▸ H)
theorem coprime_of_coprime_mul_left_right {c a b : ℤ} (H : coprime a (c * b)) : coprime a b :=
coprime_swap (coprime_of_coprime_mul_left (coprime_swap H))
theorem coprime_of_coprime_mul_right_right {c a b : ℤ} (H : coprime a (b * c)) : coprime a b :=
coprime_of_coprime_mul_left_right (!mul.comm ▸ H)
theorem exists_eq_prod_and_dvd_and_dvd {a b c} (H : c ∣ a * b) :
∃ a' b', c = a' * b' ∧ a' ∣ a ∧ b' ∣ b :=
decidable.by_cases
(suppose gcd c a = 0,
have c = 0, from eq_zero_of_gcd_eq_zero_left `gcd c a = 0`,
have a = 0, from eq_zero_of_gcd_eq_zero_right `gcd c a = 0`,
have c = 0 * b, from `c = 0` ⬝ !zero_mul⁻¹,
have 0 ∣ a, from `a = 0`⁻¹ ▸ !dvd.refl,
have b ∣ b, from !dvd.refl,
exists.intro _ (exists.intro _ (and.intro `c = 0 * b` (and.intro `0 ∣ a` `b ∣ b`))))
(suppose gcd c a ≠ 0,
have gcd c a ∣ c, from !gcd_dvd_left,
have H3 : c div gcd c a ∣ (a * b) div gcd c a, from div_dvd_div this H,
have H4 : (a * b) div gcd c a = (a div gcd c a) * b, from
calc
a * b div gcd c a = b * a div gcd c a : mul.comm
... = b * (a div gcd c a) : !mul_div_assoc !gcd_dvd_right
... = a div gcd c a * b : mul.comm,
have H5 : c div gcd c a ∣ (a div gcd c a) * b, from H4 ▸ H3,
have H6 : coprime (c div gcd c a) (a div gcd c a), from coprime_div_gcd_div_gcd `gcd c a ≠ 0`,
have H7 : c div gcd c a ∣ b, from dvd_of_coprime_of_dvd_mul_left H6 H5,
have H8 : c = gcd c a * (c div gcd c a), from (mul_div_cancel' `gcd c a ∣ c`)⁻¹,
exists.intro _ (exists.intro _ (and.intro H8 (and.intro !gcd_dvd_right H7))))
end int
|
819f4bc30df87660b12fe823a68cdbfd577d8d3f | 29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f | /Exercises week 6/23_exercise_sheet.lean | bc842b5812c37ad633e4bf084e53921f7580a5e9 | [] | no_license | KjellZijlemaker/Logical_Verification_VU | ced0ba95316a30e3c94ba8eebd58ea004fa6f53b | 4578b93bf1615466996157bb333c84122b201d99 | refs/heads/master | 1,585,966,086,108 | 1,549,187,704,000 | 1,549,187,704,000 | 155,690,284 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 8,108 | lean | /- Exercise 2.3: Functional Programming — Monads -/
namespace exercise
/- Question 1: A state monad with failure -/
/- As usual, we start by repeating some material from the lecture. -/
class monad (M : Type → Type) extends has_bind M, has_pure M : Type 1 :=
(pure_bind {α β} (a : α) (f : α → M β) :
pure a >>= f = f a)
(bind_pure {α} (m : M α) :
m >>= pure = m)
(bind_assoc {α β γ} (f : α → M β) (g : β → M γ) (m : M α) :
((m >>= f) >>= g) = (m >>= (λa, f a >>= g)))
attribute [simp] exercise.monad.bind_pure exercise.monad.bind_assoc exercise.monad.pure_bind
open exercise.monad
instance monad_option : monad option :=
{ pure := @option.some,
bind := @option.bind,
pure_bind := assume α β a f, by refl,
bind_pure := assume α m, match m with none := by refl | some a := by refl end,
bind_assoc := assume α β γ f g m, match m with none := by refl | some a := by refl end }
/- For this exercise, we introduce a richer notion of monad that provides an `orelse` operator `<|>`
satisfying some laws, given below. `emp` denotes failure. `x <|> y` tries `x` first, falling back on
`y` on failure. -/
class monad_with_orelse (M : Type → Type) extends monad M, has_orelse M :=
(emp {} {α} : M α)
(emp_orelse {α} (a : M α) :
(emp <|> a) = a)
(orelse_emp {α} (a : M α) :
(a <|> emp) = a)
(orelse_assoc {α} (a b c : M α) :
((a <|> b) <|> c) = (a <|> (b <|> c)))
(emp_bind {α β} (f : α → M β) :
(emp >>= f) = emp)
(bind_emp {α β} (f : M α) :
(f >>= (λa, emp : α → M β)) = emp)
open exercise.monad_with_orelse
attribute [simp] exercise.monad_with_orelse.emp_orelse exercise.monad_with_orelse.orelse_emp
exercise.monad_with_orelse.orelse_assoc exercise.monad_with_orelse.emp_bind
exercise.monad_with_orelse.bind_emp
/- 1.1. We set up the `option` type constructor to be a `monad_with_orelse`. Complete the proofs
below. -/
namespace option
variables {α β γ : Type}
def orelse {α} : option α → option α → option α
| none b := b
| (some a) _ := some a
instance : monad_with_orelse option :=
{ emp := λα, none,
orelse := @option.orelse,
emp_orelse := assume α a, match a with some a := by refl | none := by refl end ,
orelse_emp := assume α a, match a with some a := by refl | none := by refl end,
orelse_assoc := assume α a b c, match a with some a := by refl | none := by refl end,
emp_bind := assume α β f, by refl,
bind_emp := assume α β f, by ...,
.. exercise.monad_option }
@[simp] lemma some_bind (a : α) (g : α → option β) :
(some a >>= g) = g a := by refl
end option
/- Let us enable some convenient pattern matching syntax, by instantiating Lean's `monad_fail` type
class. -/
instance {M} [monad_with_orelse M] : monad_fail M :=
⟨λα msg, emp⟩
/- Now we can write definitions such as the following: -/
def first_of_three {M} [monad_with_orelse M] (c : M (list ℕ)) : M ℕ := do
[n, _, _] ← c, -- look Ma, this list has three elements!
pure n
#eval first_of_three (some [1])
#eval first_of_three (some [1, 2, 3, 4])
#eval first_of_three (some [1, 2, 3])
/- Using `monad_with_orelse` and the `monad_fail` syntax, we can give a much more consise definition
for the `sum_2_5_7` function seen in the lecture. -/
def sum_2_5_7 {M} [monad_with_orelse M] (c : M (list ℕ)) : M ℕ := do
(_ :: n2 :: _ :: _ :: n5 :: _ :: n7 :: _) ← c,
pure (n2 + n5 + n7)
/- 1.2. Now we are ready to define `fstate σ`: a monad with an internal state of type `σ` that can
fail (unlike `state σ`).
We start with defining `fstate σ α`, where `σ` is the type of the internal state, and `α` is the
type of the value stored in the monad. We use `option` to model failure. This means we can also use
the monadic behvior of `option` when defining the monadic opertions on `fstate`.
**Hint:** Remember that `fstate σ α` is an alias for a function type, so you can use pattern
matching and `λs, ...` to define values of type `fstate σ α`.
**Hint:** `fstate` is very similar to `state` in the lecture demonstration. You can look there for
inspiration.
-/
def fstate (σ : Type) (α : Type) := σ → option (α × σ)
/- 1.3. Define the `get` and `set` function for `fstate`, where `get` returns the state passed along
the state monad, and `set s` changes the state to `s` and returns the old state.
-/
def get {σ : Type} : fstate σ σ
| s := (s,s)
def set {σ : Type} (s : σ) : fstate σ unit
| t := ((), s)
namespace fstate
variables {σ α β γ : Type}
/- 1.4. Define the monadic operators (`bind` and `pure`) for `fstate`, in such a way that they
will satisfy the monadic laws. -/
protected def bind (f : fstate σ α) (g : α → fstate σ β) : fstate σ β
| s := function.uncurry g (f s)
-- set up the `>>=` syntax on `fstate`
instance : has_bind (fstate σ) := ⟨@fstate.bind σ⟩
@[simp] lemma bind_apply (f : fstate σ α) (g : α → fstate σ β) (s : σ) :
(f >>= g) s = f s >>= function.uncurry g :=
by refl
protected def pure (a : α) : fstate σ α
:= sorry
-- we already setup the syntax for `pure` on `fstate`
instance : has_pure (fstate σ) := ⟨@fstate.pure σ⟩
@[simp] lemma pure_apply (a : α) (s : σ) :
(pure a : fstate σ α) s = some (a, s) :=
by refl
/- 1.3 `fstate` is a monad:
**Hint:** `pure` and `bind` are introduced using `protected`, so their names are `fstate.pure` and
`fstate.bind`
**Hint**: `funext` is your friend when you need to prove equality between two functions.
**Hint**: Sometimes one `cases` is not enough, especially `uncurry f p` requires that `p` is a pair
of the form `(a, b)`!
**Hint**: `cases (f s)` only works when `f s` is appreaing in your goal, so you may need to unfold
some constants before you can do a `cases`.
-/
instance : monad (fstate σ) :=
{ pure_bind :=
sorry,
bind_pure :=
sorry,
bind_assoc :=
sorry,
.. fstate.has_bind, .. fstate.has_pure }
/- 1.4 `fstate` is a monad which supports failure.
**Hint**: Sometimes one `cases` is not enough, especially `uncurry f p` requires that `p` is a pair
of the form `(a, b)`!
**Hint**: `funext` is your friend when you need to prove equality between two functions.
**Hint**: parts of `fstate` are defined using the `option` monad, so parts of some proofs could
use `emp_orelse`, `orelse_emp`, `orelse_assoc`, `emp_bind`, when talking about `option`. -/
instance : monad_with_orelse (fstate σ) :=
{ emp := λα s, none,
orelse := λα f g s, option.orelse (f s) (g s),
emp_orelse :=
sorry,
orelse_emp :=
sorry,
orelse_assoc :=
sorry,
emp_bind :=
sorry,
bind_emp := assume α β f, funext $ assume s,
sorry,
.. exercise.fstate.exercise.monad }
@[simp] lemma orelse_apply (f g : fstate σ α) (s : σ) :
(f <|> g) s = (f s <|> g s) :=
by refl
@[simp] lemma emp_apply (s : σ) :
(emp : fstate σ α) s = (emp : option (α × σ)) :=
by refl
end fstate
/- Let us use `fstate`. -/
section monad
variables {M : Type → Type} [monad M] {α β : Type}
def mmap (f : α → M β) : list α → M (list β)
| [] := pure []
| (a :: l) := do
b ← f a,
l' ← mmap l,
pure (b :: l')
end monad
example (l : list ℕ) : fstate ℕ (list ℕ) :=
mmap (λp : ℕ, do
prev ← get,
set p,
if prev > p then
emp
else
pure (p - prev)) l
/- Question 2: Kleisli operator: pipelining monadic operations -/
section kleisli_operator
open monad
variables {M : Type → Type} [monad M] {α β γ δ : Type}
variables {f : α → M β} {g : β → M γ} {h : γ → M δ}
def kleisli (f : α → M β) (g : β → M γ) : (α → M γ) :=
λa, f a >>= g
infixr ` >=> `:90 := kleisli
/- 2.1. Prove the following equations for the Kleisli operator.
**Hint**: Remember `funext`. -/
-- `pure` is a left unit for `>=>`
lemma pure_kleisli : pure >=> f = f :=
sorry
-- `pure` is a right unit for `>=>`
lemma kleisli_pure : f >=> pure = f :=
sorry
-- `>=>` is associative
lemma kleisli_assoc : (f >=> g) >=> h = f >=> (g >=> h) :=
sorry
end kleisli_operator
end exercise
|
d435d35cf24290d82870af791d531270c91ef203 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/dottedNameBug.lean | 92040ac6c79179357ab5306dbc7c2eb7b2a5833a | [
"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 | 695 | lean | inductive AltCore (α : Type)
| default (val : α)
| alt (name : String) (val : α)
inductive Code where
| cases (alt: AltCore Code)
| return (id : Nat)
abbrev Alt := AltCore Code
def AltCore.getCode : Alt → Code
| .default c => c
| .alt _ c => c
def AltCore.update (alt : Alt) (c : Code) : Alt :=
match alt with
| .default _ => if true then alt else .default c
| .alt n _ => if true then alt else .alt n c
example (alt : Alt) : Code :=
alt.getCode
def Alt.getCode' : Alt → Code
| .default c => c
| .alt _ c => c
example (alt : Alt) : Code :=
if true then .return 1 else alt.getCode'
example (alt : Alt) : Code :=
if true then alt.getCode' else .return 0
|
e6d2bef2323fdf501ee876a284774c47c20da739 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/slow/nat_wo_hints.lean | 6a81dce99bf70edd164c3b69f8d2c9e61c74e378 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 49,706 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Floris van Doorn. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Floris van Doorn
----------------------------------------------------------------------------------------------------
import standard struc.binary
using tactic num binary eq_proofs
using decidable
namespace experiment
inductive nat : Type :=
zero : nat,
succ : nat → nat
namespace nat
notation `ℕ`:max := nat
definition plus (x y : ℕ) : ℕ
:= nat.rec x (λ n r, succ r) y
definition to_nat [coercion] (n : num) : ℕ
:= num.rec zero (λ n, pos_num.rec (succ zero) (λ n r, plus r (plus r (succ zero))) (λ n r, plus r r) n) n
namespace helper_tactics
definition apply_refl := apply @eq.refl
tactic_hint apply_refl
end helper_tactics
open helper_tactics
theorem nat_rec_zero {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) : nat.rec x f 0 = x
theorem nat_rec_succ {P : ℕ → Type} (x : P 0) (f : ∀m, P m → P (succ m)) (n : ℕ) : nat.rec x f (succ n) = f n (nat.rec x f n)
theorem succ_ne_zero (n : ℕ) : succ n ≠ 0
:= assume H : succ n = 0,
have H2 : true = false, from
let f := (nat.rec false (fun a b, true)) in
calc true = f (succ n) : _
... = f 0 : {H}
... = false : _,
absurd H2 true_ne_false
definition pred (n : ℕ) := nat.rec 0 (fun m x, m) n
theorem pred_zero : pred 0 = 0
theorem pred_succ (n : ℕ) : pred (succ n) = n
theorem zero_or_succ (n : ℕ) : n = 0 ∨ n = succ (pred n)
:= induction_on n
(or.intro_left _ (eq.refl 0))
(take m IH, or.intro_right _
(show succ m = succ (pred (succ m)), from congr_arg succ (pred_succ m⁻¹)))
theorem zero_or_succ2 (n : ℕ) : n = 0 ∨ ∃k, n = succ k
:= or.imp_or (zero_or_succ n) (assume H, H) (assume H : n = succ (pred n), exists_intro (pred n) H)
theorem case {P : ℕ → Prop} (n : ℕ) (H1: P 0) (H2 : ∀m, P (succ m)) : P n
:= induction_on n H1 (take m IH, H2 m)
theorem discriminate {B : Prop} {n : ℕ} (H1: n = 0 → B) (H2 : ∀m, n = succ m → B) : B
:= or.elim (zero_or_succ n)
(take H3 : n = 0, H1 H3)
(take H3 : n = succ (pred n), H2 (pred n) H3)
theorem succ_inj {n m : ℕ} (H : succ n = succ m) : n = m
:= calc
n = pred (succ n) : pred_succ n⁻¹
... = pred (succ m) : {H}
... = m : pred_succ m
theorem succ_ne_self (n : ℕ) : succ n ≠ n
:= induction_on n
(take H : 1 = 0,
have ne : 1 ≠ 0, from succ_ne_zero 0,
absurd H ne)
(take k IH H, IH (succ_inj H))
theorem decidable_eq [instance] (n m : ℕ) : decidable (n = m)
:= have general : ∀n, decidable (n = m), from
rec_on m
(take n,
rec_on n
(inl (eq.refl 0))
(λ m iH, inr (succ_ne_zero m)))
(λ (m' : ℕ) (iH1 : ∀n, decidable (n = m')),
take n, rec_on n
(inr (ne.symm (succ_ne_zero m')))
(λ (n' : ℕ) (iH2 : decidable (n' = succ m')),
have d1 : decidable (n' = m'), from iH1 n',
decidable.rec_on d1
(assume Heq : n' = m', inl (congr_arg succ Heq))
(assume Hne : n' ≠ m',
have H1 : succ n' ≠ succ m', from
assume Heq, absurd (succ_inj Heq) Hne,
inr H1))),
general n
theorem two_step_induction_on {P : ℕ → Prop} (a : ℕ) (H1 : P 0) (H2 : P 1)
(H3 : ∀ (n : ℕ) (IH1 : P n) (IH2 : P (succ n)), P (succ (succ n))) : P a
:= have stronger : P a ∧ P (succ a), from
induction_on a
(and.intro H1 H2)
(take k IH,
have IH1 : P k, from and.elim_left IH,
have IH2 : P (succ k), from and.elim_right IH,
and.intro IH2 (H3 k IH1 IH2)),
and.elim_left stronger
theorem sub_induction {P : ℕ → ℕ → Prop} (n m : ℕ) (H1 : ∀m, P 0 m)
(H2 : ∀n, P (succ n) 0) (H3 : ∀n m, P n m → P (succ n) (succ m)) : P n m
:= have general : ∀m, P n m, from induction_on n
(take m : ℕ, H1 m)
(take k : ℕ,
assume IH : ∀m, P k m,
take m : ℕ,
discriminate
(assume Hm : m = 0,
Hm⁻¹ ▸ (H2 k))
(take l : ℕ,
assume Hm : m = succ l,
Hm⁻¹ ▸ (H3 k l (IH l)))),
general m
-------------------------------------------------- add
definition add (x y : ℕ) : ℕ := plus x y
infixl `+` := add
theorem add_zero_right (n : ℕ) : n + 0 = n
theorem add_succ_right (n m : ℕ) : n + succ m = succ (n + m)
---------- comm, assoc
theorem add_zero_left (n : ℕ) : 0 + n = n
:= induction_on n
(add_zero_right 0)
(take m IH, show 0 + succ m = succ m, from
calc
0 + succ m = succ (0 + m) : add_succ_right _ _
... = succ m : {IH})
theorem add_succ_left (n m : ℕ) : (succ n) + m = succ (n + m)
:= induction_on m
(calc
succ n + 0 = succ n : add_zero_right (succ n)
... = succ (n + 0) : {symm (add_zero_right n)})
(take k IH,
calc
succ n + succ k = succ (succ n + k) : add_succ_right _ _
... = succ (succ (n + k)) : {IH}
... = succ (n + succ k) : {symm (add_succ_right _ _)})
theorem add_comm (n m : ℕ) : n + m = m + n
:= induction_on m
(trans (add_zero_right _) (symm (add_zero_left _)))
(take k IH,
calc
n + succ k = succ (n+k) : add_succ_right _ _
... = succ (k + n) : {IH}
... = succ k + n : symm (add_succ_left _ _))
theorem add_move_succ (n m : ℕ) : succ n + m = n + succ m
:= calc
succ n + m = succ (n + m) : add_succ_left n m
... = n +succ m : symm (add_succ_right n m)
theorem add_comm_succ (n m : ℕ) : n + succ m = m + succ n
:= calc
n + succ m = succ n + m : symm (add_move_succ n m)
... = m + succ n : add_comm (succ n) m
theorem add_assoc (n m k : ℕ) : (n + m) + k = n + (m + k)
:= induction_on k
(calc
(n + m) + 0 = n + m : add_zero_right _
... = n + (m + 0) : {symm (add_zero_right m)})
(take l IH,
calc
(n + m) + succ l = succ ((n + m) + l) : add_succ_right _ _
... = succ (n + (m + l)) : {IH}
... = n + succ (m + l) : symm (add_succ_right _ _)
... = n + (m + succ l) : {symm (add_succ_right _ _)})
theorem add_left_comm (n m k : ℕ) : n + (m + k) = m + (n + k)
:= left_comm add_comm add_assoc n m k
theorem add_right_comm (n m k : ℕ) : n + m + k = n + k + m
:= right_comm add_comm add_assoc n m k
---------- inversion
theorem add_cancel_left {n m k : ℕ} : n + m = n + k → m = k
:=
induction_on n
(take H : 0 + m = 0 + k,
calc
m = 0 + m : symm (add_zero_left m)
... = 0 + k : H
... = k : add_zero_left k)
(take (n : ℕ) (IH : n + m = n + k → m = k) (H : succ n + m = succ n + k),
have H2 : succ (n + m) = succ (n + k),
from calc
succ (n + m) = succ n + m : symm (add_succ_left n m)
... = succ n + k : H
... = succ (n + k) : add_succ_left n k,
have H3 : n + m = n + k, from succ_inj H2,
IH H3)
--rename to and_cancel_right
theorem add_cancel_right {n m k : ℕ} (H : n + m = k + m) : n = k
:=
have H2 : m + n = m + k,
from calc
m + n = n + m : add_comm m n
... = k + m : H
... = m + k : add_comm k m,
add_cancel_left H2
theorem add_eq_zero_left {n m : ℕ} : n + m = 0 → n = 0
:=
induction_on n
(take (H : 0 + m = 0), eq.refl 0)
(take k IH,
assume (H : succ k + m = 0),
absurd
(show succ (k + m) = 0, from
calc
succ (k + m) = succ k + m : symm (add_succ_left k m)
... = 0 : H)
(succ_ne_zero (k + m)))
theorem add_eq_zero_right {n m : ℕ} (H : n + m = 0) : m = 0
:= add_eq_zero_left (trans (add_comm m n) H)
theorem add_eq_zero {n m : ℕ} (H : n + m = 0) : n = 0 ∧ m = 0
:= and.intro (add_eq_zero_left H) (add_eq_zero_right H)
-- add_eq_self below
---------- misc
theorem add_one (n:ℕ) : n + 1 = succ n
:=
calc
n + 1 = succ (n + 0) : add_succ_right _ _
... = succ n : {add_zero_right _}
theorem add_one_left (n:ℕ) : 1 + n = succ n
:=
calc
1 + n = succ (0 + n) : add_succ_left _ _
... = succ n : {add_zero_left _}
--the following theorem has a terrible name, but since the name is not a substring or superstring of another name, it is at least easy to globally replace it
theorem induction_plus_one {P : ℕ → Prop} (a : ℕ) (H1 : P 0)
(H2 : ∀ (n : ℕ) (IH : P n), P (n + 1)) : P a
:= nat.rec H1 (take n IH, (add_one n) ▸ (H2 n IH)) a
-------------------------------------------------- mul
definition mul (n m : ℕ) := nat.rec 0 (fun m x, x + n) m
infixl `*` := mul
theorem mul_zero_right (n:ℕ) : n * 0 = 0
theorem mul_succ_right (n m:ℕ) : n * succ m = n * m + n
set_option unifier.max_steps 100000
---------- comm, distr, assoc, identity
theorem mul_zero_left (n:ℕ) : 0 * n = 0
:= induction_on n
(mul_zero_right 0)
(take m IH,
calc
0 * succ m = 0 * m + 0 : mul_succ_right _ _
... = 0 * m : add_zero_right _
... = 0 : IH)
theorem mul_succ_left (n m:ℕ) : (succ n) * m = (n * m) + m
:= induction_on m
(calc
succ n * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * 0 + 0 : symm (add_zero_right _))
(take k IH,
calc
succ n * succ k = (succ n * k) + succ n : mul_succ_right _ _
... = (n * k) + k + succ n : { IH }
... = (n * k) + (k + succ n) : add_assoc _ _ _
... = (n * k) + (n + succ k) : {add_comm_succ _ _}
... = (n * k) + n + succ k : symm (add_assoc _ _ _)
... = (n * succ k) + succ k : {symm (mul_succ_right n k)})
theorem mul_comm (n m:ℕ) : n * m = m * n
:= induction_on m
(trans (mul_zero_right _) (symm (mul_zero_left _)))
(take k IH,
calc
n * succ k = n * k + n : mul_succ_right _ _
... = k * n + n : {IH}
... = (succ k) * n : symm (mul_succ_left _ _))
theorem mul_add_distr_left (n m k : ℕ) : (n + m) * k = n * k + m * k
:= induction_on k
(calc
(n + m) * 0 = 0 : mul_zero_right _
... = 0 + 0 : symm (add_zero_right _)
... = n * 0 + 0 : eq.refl _
... = n * 0 + m * 0 : eq.refl _)
(take l IH, calc
(n + m) * succ l = (n + m) * l + (n + m) : mul_succ_right _ _
... = n * l + m * l + (n + m) : {IH}
... = n * l + m * l + n + m : symm (add_assoc _ _ _)
... = n * l + n + m * l + m : {add_right_comm _ _ _}
... = n * l + n + (m * l + m) : add_assoc _ _ _
... = n * succ l + (m * l + m) : {symm (mul_succ_right _ _)}
... = n * succ l + m * succ l : {symm (mul_succ_right _ _)})
theorem mul_add_distr_right (n m k : ℕ) : n * (m + k) = n * m + n * k
:= calc
n * (m + k) = (m + k) * n : mul_comm _ _
... = m * n + k * n : mul_add_distr_left _ _ _
... = n * m + k * n : {mul_comm _ _}
... = n * m + n * k : {mul_comm _ _}
theorem mul_assoc (n m k:ℕ) : (n * m) * k = n * (m * k)
:= induction_on k
(calc
(n * m) * 0 = 0 : mul_zero_right _
... = n * 0 : symm (mul_zero_right _)
... = n * (m * 0) : {symm (mul_zero_right _)})
(take l IH,
calc
(n * m) * succ l = (n * m) * l + n * m : mul_succ_right _ _
... = n * (m * l) + n * m : {IH}
... = n * (m * l + m) : symm (mul_add_distr_right _ _ _)
... = n * (m * succ l) : {symm (mul_succ_right _ _)})
theorem mul_comm_left (n m k : ℕ) : n * (m * k) = m * (n * k)
:= left_comm mul_comm mul_assoc n m k
theorem mul_comm_right (n m k : ℕ) : n * m * k = n * k * m
:= right_comm mul_comm mul_assoc n m k
theorem mul_one_right (n : ℕ) : n * 1 = n
:= calc
n * 1 = n * 0 + n : mul_succ_right n 0
... = 0 + n : {mul_zero_right n}
... = n : add_zero_left n
theorem mul_one_left (n : ℕ) : 1 * n = n
:= calc
1 * n = n * 1 : mul_comm _ _
... = n : mul_one_right n
---------- inversion
theorem mul_eq_zero {n m : ℕ} (H : n * m = 0) : n = 0 ∨ m = 0
:=
discriminate
(take Hn : n = 0, or.intro_left _ Hn)
(take (k : ℕ),
assume (Hk : n = succ k),
discriminate
(take (Hm : m = 0), or.intro_right _ Hm)
(take (l : ℕ),
assume (Hl : m = succ l),
have Heq : succ (k * succ l + l) = n * m, from
symm (calc
n * m = n * succ l : { Hl }
... = succ k * succ l : { Hk }
... = k * succ l + succ l : mul_succ_left _ _
... = succ (k * succ l + l) : add_succ_right _ _),
absurd (trans Heq H) (succ_ne_zero _)))
-- see more under "positivity" below
-------------------------------------------------- le
definition le (n m:ℕ) : Prop := ∃k, n + k = m
infix `<=` := le
infix `≤` := le
theorem le_intro {n m k : ℕ} (H : n + k = m) : n ≤ m
:= exists_intro k H
theorem le_elim {n m : ℕ} (H : n ≤ m) : ∃ k, n + k = m
:= H
---------- partial order (totality is part of lt)
theorem le_intro2 (n m : ℕ) : n ≤ n + m
:= le_intro (eq.refl (n + m))
theorem le_refl (n : ℕ) : n ≤ n
:= le_intro (add_zero_right n)
theorem zero_le (n : ℕ) : 0 ≤ n
:= le_intro (add_zero_left n)
theorem le_zero {n : ℕ} (H : n ≤ 0) : n = 0
:=
obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
add_eq_zero_left Hk
theorem not_succ_zero_le (n : ℕ) : ¬ succ n ≤ 0
:= assume H : succ n ≤ 0,
have H2 : succ n = 0, from le_zero H,
absurd H2 (succ_ne_zero n)
theorem le_zero_inv {n : ℕ} (H : n ≤ 0) : n = 0
:= obtain (k : ℕ) (Hk : n + k = 0), from le_elim H,
add_eq_zero_left Hk
theorem le_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m ≤ k) : n ≤ k
:= obtain (l1 : ℕ) (Hl1 : n + l1 = m), from le_elim H1,
obtain (l2 : ℕ) (Hl2 : m + l2 = k), from le_elim H2,
le_intro
(calc
n + (l1 + l2) = n + l1 + l2 : symm (add_assoc n l1 l2)
... = m + l2 : { Hl1 }
... = k : Hl2)
theorem le_antisym {n m : ℕ} (H1 : n ≤ m) (H2 : m ≤ n) : n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H1),
obtain (l : ℕ) (Hl : m + l = n), from (le_elim H2),
have L1 : k + l = 0, from
add_cancel_left
(calc
n + (k + l) = n + k + l : { symm (add_assoc n k l) }
... = m + l : { Hk }
... = n : Hl
... = n + 0 : symm (add_zero_right n)),
have L2 : k = 0, from add_eq_zero_left L1,
calc
n = n + 0 : symm (add_zero_right n)
... = n + k : { symm L2 }
... = m : Hk
---------- interaction with add
theorem add_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k + n ≤ k + m
:= obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
le_intro
(calc
k + n + l = k + (n + l) : add_assoc k n l
... = k + m : { Hl })
theorem add_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n + k ≤ m + k
:= (add_comm k m) ▸ (add_comm k n) ▸ (add_le_left H k)
theorem add_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n + m ≤ k + l
:= le_trans (add_le_right H1 m) (add_le_left H2 k)
theorem add_le_left_inv {n m k : ℕ} (H : k + n ≤ k + m) : n ≤ m
:=
obtain (l : ℕ) (Hl : k + n + l = k + m), from (le_elim H),
le_intro (add_cancel_left
(calc
k + (n + l) = k + n + l : symm (add_assoc k n l)
... = k + m : Hl))
theorem add_le_right_inv {n m k : ℕ} (H : n + k ≤ m + k) : n ≤ m
:= add_le_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ and pred
theorem succ_le {n m : ℕ} (H : n ≤ m) : succ n ≤ succ m
:= add_one m ▸ add_one n ▸ add_le_right H 1
theorem succ_le_cancel {n m : ℕ} (H : succ n ≤ succ m) : n ≤ m
:= add_le_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H)
theorem self_le_succ (n : ℕ) : n ≤ succ n
:= le_intro (add_one n)
theorem le_imp_le_succ {n m : ℕ} (H : n ≤ m) : n ≤ succ m
:= le_trans H (self_le_succ m)
theorem succ_le_left_or {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:= obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : (add_zero_right n)⁻¹
... = n + k : {H3⁻¹}
... = m : Hk,
or.intro_right _ Heq)
(take l:ℕ,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : add_move_succ n l
... = n + k : {H3⁻¹}
... = m : Hk)),
or.intro_left _ Hlt)
theorem succ_le_left {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= or.resolve_left (succ_le_left_or H1) H2
theorem succ_le_right_inv {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m
:= or.imp_or (succ_le_left_or H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
(take H2 : n = succ m, H2)
theorem succ_le_left_inv {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:= obtain (k : ℕ) (H2 : succ n + k = m), from (le_elim H),
and.intro
(have H3 : n + succ k = m,
from calc
n + succ k = succ n + k : symm (add_move_succ n k)
... = m : H2,
show n ≤ m, from le_intro H3)
(assume H3 : n = m,
have H4 : succ n ≤ n, from subst (symm H3) H,
have H5 : succ n = n, from le_antisym H4 (self_le_succ n),
show false, from absurd H5 (succ_ne_self n))
theorem le_pred_self (n : ℕ) : pred n ≤ n
:= case n
(subst (symm pred_zero) (le_refl 0))
(take k : ℕ, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le {n m : ℕ} (H : n ≤ m) : pred n ≤ pred m
:= discriminate
(take Hn : n = 0,
have H2 : pred n = 0,
from calc
pred n = pred 0 : {Hn}
... = 0 : pred_zero,
subst (symm H2) (zero_le (pred m)))
(take k : ℕ,
assume Hn : n = succ k,
obtain (l : ℕ) (Hl : n + l = m), from le_elim H,
have H2 : pred n + l = pred m,
from calc
pred n + l = pred (succ k) + l : {Hn}
... = k + l : {pred_succ k}
... = pred (succ (k + l)) : symm (pred_succ (k + l))
... = pred (succ k + l) : {symm (add_succ_left k l)}
... = pred (n + l) : {symm Hn}
... = pred m : {Hl},
le_intro H2)
theorem pred_le_left_inv {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:= discriminate
(take Hn : n = 0,
or.intro_left _ (subst (symm Hn) (zero_le m)))
(take k : ℕ,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : pred_succ k,
have H3 : k ≤ m, from subst H2 H,
have H4 : succ k ≤ m ∨ k = m, from succ_le_left_or H3,
show n ≤ m ∨ n = succ m, from
or.imp_or H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
-- ### interaction with successor and predecessor
theorem le_imp_succ_le_or_eq {n m : ℕ} (H : n ≤ m) : succ n ≤ m ∨ n = m
:=
obtain (k : ℕ) (Hk : n + k = m), from (le_elim H),
discriminate
(assume H3 : k = 0,
have Heq : n = m,
from calc
n = n + 0 : symm (add_zero_right n)
... = n + k : {symm H3}
... = m : Hk,
or.intro_right _ Heq)
(take l : nat,
assume H3 : k = succ l,
have Hlt : succ n ≤ m, from
(le_intro
(calc
succ n + l = n + succ l : add_move_succ n l
... = n + k : {symm H3}
... = m : Hk)),
or.intro_left _ Hlt)
theorem le_ne_imp_succ_le {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : succ n ≤ m
:= or.resolve_left (le_imp_succ_le_or_eq H1) H2
theorem le_succ_imp_le_or_eq {n m : ℕ} (H : n ≤ succ m) : n ≤ m ∨ n = succ m
:= or.imp_or_left (le_imp_succ_le_or_eq H)
(take H2 : succ n ≤ succ m, show n ≤ m, from succ_le_cancel H2)
theorem succ_le_imp_le_and_ne {n m : ℕ} (H : succ n ≤ m) : n ≤ m ∧ n ≠ m
:=
and.intro
(le_trans (self_le_succ n) H)
(assume H2 : n = m,
have H3 : succ n ≤ n, from subst (symm H2) H,
have H4 : succ n = n, from le_antisym H3 (self_le_succ n),
show false, from absurd H4 (succ_ne_self n))
theorem pred_le_self (n : ℕ) : pred n ≤ n
:=
case n
(subst (symm pred_zero) (le_refl 0))
(take k : nat, subst (symm (pred_succ k)) (self_le_succ k))
theorem pred_le_imp_le_or_eq {n m : ℕ} (H : pred n ≤ m) : n ≤ m ∨ n = succ m
:=
discriminate
(take Hn : n = 0,
or.intro_left _ (subst (symm Hn) (zero_le m)))
(take k : nat,
assume Hn : n = succ k,
have H2 : pred n = k,
from calc
pred n = pred (succ k) : {Hn}
... = k : pred_succ k,
have H3 : k ≤ m, from subst H2 H,
have H4 : succ k ≤ m ∨ k = m, from le_imp_succ_le_or_eq H3,
show n ≤ m ∨ n = succ m, from
or.imp_or H4
(take H5 : succ k ≤ m, show n ≤ m, from subst (symm Hn) H5)
(take H5 : k = m, show n = succ m, from subst H5 Hn))
---------- interaction with mul
theorem mul_le_left {n m : ℕ} (H : n ≤ m) (k : ℕ) : k * n ≤ k * m
:=
obtain (l : ℕ) (Hl : n + l = m), from (le_elim H),
induction_on k
(have H2 : 0 * n = 0 * m,
from calc
0 * n = 0 : mul_zero_left n
... = 0 * m : symm (mul_zero_left m),
show 0 * n ≤ 0 * m, from subst H2 (le_refl (0 * n)))
(take (l : ℕ),
assume IH : l * n ≤ l * m,
have H2 : l * n + n ≤ l * m + m, from add_le IH H,
have H3 : succ l * n ≤ l * m + m, from subst (symm (mul_succ_left l n)) H2,
show succ l * n ≤ succ l * m, from subst (symm (mul_succ_left l m)) H3)
theorem mul_le_right {n m : ℕ} (H : n ≤ m) (k : ℕ) : n * k ≤ m * k
:= mul_comm k m ▸ mul_comm k n ▸ (mul_le_left H k)
theorem mul_le {n m k l : ℕ} (H1 : n ≤ k) (H2 : m ≤ l) : n * m ≤ k * l
:= le_trans (mul_le_right H1 m) (mul_le_left H2 k)
-- mul_le_[left|right]_inv below
-------------------------------------------------- lt
definition lt (n m : ℕ) := succ n ≤ m
infix `<` := lt
theorem lt_intro {n m k : ℕ} (H : succ n + k = m) : n < m
:= le_intro H
theorem lt_elim {n m : ℕ} (H : n < m) : ∃ k, succ n + k = m
:= le_elim H
theorem lt_intro2 (n m : ℕ) : n < n + succ m
:= lt_intro (add_move_succ n m)
-------------------------------------------------- ge, gt
definition ge (n m : ℕ) := m ≤ n
infix `>=` := ge
infix `≥` := ge
definition gt (n m : ℕ) := m < n
infix `>` := gt
---------- basic facts
theorem lt_ne {n m : ℕ} (H : n < m) : n ≠ m
:= and.elim_right (succ_le_left_inv H)
theorem lt_irrefl (n : ℕ) : ¬ n < n
:= assume H : n < n, absurd (eq.refl n) (lt_ne H)
theorem lt_zero (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem lt_zero_inv (n : ℕ) : ¬ n < 0
:= assume H : n < 0,
have H2 : succ n = 0, from le_zero_inv H,
absurd H2 (succ_ne_zero n)
theorem lt_positive {n m : ℕ} (H : n < m) : ∃k, m = succ k
:= discriminate
(take (Hm : m = 0), absurd (subst Hm H) (lt_zero_inv n))
(take (l : ℕ) (Hm : m = succ l), exists_intro l Hm)
---------- interaction with le
theorem lt_imp_le_succ {n m : ℕ} (H : n < m) : succ n ≤ m
:= H
theorem le_succ_imp_lt {n m : ℕ} (H : succ n ≤ m) : n < m
:= H
theorem self_lt_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem lt_imp_le {n m : ℕ} (H : n < m) : n ≤ m
:= and.elim_left (succ_le_imp_le_and_ne H)
theorem le_imp_lt_or_eq {n m : ℕ} (H : n ≤ m) : n < m ∨ n = m
:= le_imp_succ_le_or_eq H
theorem le_ne_imp_lt {n m : ℕ} (H1 : n ≤ m) (H2 : n ≠ m) : n < m
:= le_ne_imp_succ_le H1 H2
theorem le_imp_lt_succ {n m : ℕ} (H : n ≤ m) : n < succ m
:= succ_le H
theorem lt_succ_imp_le {n m : ℕ} (H : n < succ m) : n ≤ m
:= succ_le_cancel H
---------- trans, antisym
theorem lt_le_trans {n m k : ℕ} (H1 : n < m) (H2 : m ≤ k) : n < k
:= le_trans H1 H2
theorem le_lt_trans {n m k : ℕ} (H1 : n ≤ m) (H2 : m < k) : n < k
:= le_trans (succ_le H1) H2
theorem lt_trans {n m k : ℕ} (H1 : n < m) (H2 : m < k) : n < k
:= lt_le_trans H1 (lt_imp_le H2)
theorem le_imp_not_gt {n m : ℕ} (H : n ≤ m) : ¬ n > m
:= assume H2 : m < n, absurd (le_lt_trans H H2) (lt_irrefl n)
theorem lt_imp_not_ge {n m : ℕ} (H : n < m) : ¬ n ≥ m
:= assume H2 : m ≤ n, absurd (lt_le_trans H H2) (lt_irrefl n)
theorem lt_antisym {n m : ℕ} (H : n < m) : ¬ m < n
:= le_imp_not_gt (lt_imp_le H)
---------- interaction with add
theorem add_lt_left {n m : ℕ} (H : n < m) (k : ℕ) : k + n < k + m
:= add_succ_right k n ▸ add_le_left H k
theorem add_lt_right {n m : ℕ} (H : n < m) (k : ℕ) : n + k < m + k
:= add_comm k m ▸ add_comm k n ▸ add_lt_left H k
theorem add_le_lt {n m k l : ℕ} (H1 : n ≤ k) (H2 : m < l) : n + m < k + l
:= le_lt_trans (add_le_right H1 m) (add_lt_left H2 k)
theorem add_lt_le {n m k l : ℕ} (H1 : n < k) (H2 : m ≤ l) : n + m < k + l
:= lt_le_trans (add_lt_right H1 m) (add_le_left H2 k)
theorem add_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n + m < k + l
:= add_lt_le H1 (lt_imp_le H2)
theorem add_lt_left_inv {n m k : ℕ} (H : k + n < k + m) : n < m
:= add_le_left_inv (add_succ_right k n⁻¹ ▸ H)
theorem add_lt_right_inv {n m k : ℕ} (H : n + k < m + k) : n < m
:= add_lt_left_inv (add_comm m k ▸ add_comm n k ▸ H)
---------- interaction with succ (see also the interaction with le)
theorem succ_lt {n m : ℕ} (H : n < m) : succ n < succ m
:= add_one m ▸ add_one n ▸ add_lt_right H 1
theorem succ_lt_inv {n m : ℕ} (H : succ n < succ m) : n < m
:= add_lt_right_inv (add_one m⁻¹ ▸ add_one n⁻¹ ▸ H)
theorem lt_self_succ (n : ℕ) : n < succ n
:= le_refl (succ n)
theorem succ_lt_right {n m : ℕ} (H : n < m) : n < succ m
:= lt_trans H (lt_self_succ m)
---------- totality of lt and le
theorem le_or_lt (n m : ℕ) : n ≤ m ∨ m < n
:= induction_on n
(or.intro_left _ (zero_le m))
(take (k : ℕ),
assume IH : k ≤ m ∨ m < k,
or.elim IH
(assume H : k ≤ m,
obtain (l : ℕ) (Hl : k + l = m), from le_elim H,
discriminate
(assume H2 : l = 0,
have H3 : m = k,
from calc
m = k + l : symm Hl
... = k + 0 : {H2}
... = k : add_zero_right k,
have H4 : m < succ k, from subst H3 (lt_self_succ m),
or.intro_right _ H4)
(take l2 : ℕ,
assume H2 : l = succ l2,
have H3 : succ k + l2 = m,
from calc
succ k + l2 = k + succ l2 : add_move_succ k l2
... = k + l : {symm H2}
... = m : Hl,
or.intro_left _ (le_intro H3)))
(assume H : m < k, or.intro_right _ (succ_lt_right H)))
theorem trichotomy_alt (n m : ℕ) : (n < m ∨ n = m) ∨ m < n
:= or.imp_or (le_or_lt n m) (assume H : n ≤ m, le_imp_lt_or_eq H) (assume H : m < n, H)
theorem trichotomy (n m : ℕ) : n < m ∨ n = m ∨ m < n
:= iff.elim_left or.assoc (trichotomy_alt n m)
theorem le_total (n m : ℕ) : n ≤ m ∨ m ≤ n
:= or.imp_or (le_or_lt n m) (assume H : n ≤ m, H) (assume H : m < n, lt_imp_le H)
-- interaction with mul under "positivity"
theorem strong_induction_on {P : ℕ → Prop} (n : ℕ) (IH : ∀n, (∀m, m < n → P m) → P n) : P n
:= have stronger : ∀k, k ≤ n → P k, from
induction_on n
(take (k : ℕ),
assume H : k ≤ 0,
have H2 : k = 0, from le_zero_inv H,
have H3 : ∀m, m < k → P m, from
(take m : ℕ,
assume H4 : m < k,
have H5 : m < 0, from subst H2 H4,
absurd H5 (lt_zero_inv m)),
show P k, from IH k H3)
(take l : ℕ,
assume IHl : ∀k, k ≤ l → P k,
take k : ℕ,
assume H : k ≤ succ l,
or.elim (succ_le_right_inv H)
(assume H2 : k ≤ l, show P k, from IHl k H2)
(assume H2 : k = succ l,
have H3 : ∀m, m < k → P m, from
(take m : ℕ,
assume H4 : m < k,
have H5 : m ≤ l, from lt_succ_imp_le (subst H2 H4),
show P m, from IHl m H5),
show P k, from IH k H3)),
stronger n (le_refl n)
theorem case_strong_induction_on {P : ℕ → Prop} (a : ℕ) (H0 : P 0) (Hind : ∀(n : ℕ), (∀m, m ≤ n → P m) → P (succ n)) : P a
:= strong_induction_on a
(take n, case n
(assume H : (∀m, m < 0 → P m), H0)
(take n, assume H : (∀m, m < succ n → P m),
Hind n (take m, assume H1 : m ≤ n, H m (le_imp_lt_succ H1))))
theorem add_eq_self {n m : ℕ} (H : n + m = n) : m = 0
:= discriminate
(take Hm : m = 0, Hm)
(take k : ℕ,
assume Hm : m = succ k,
have H2 : succ n + k = n,
from calc
succ n + k = n + succ k : add_move_succ n k
... = n + m : {symm Hm}
... = n : H,
have H3 : n < n, from lt_intro H2,
have H4 : n ≠ n, from lt_ne H3,
absurd (eq.refl n) H4)
-------------------------------------------------- positivity
-- we use " _ > 0" as canonical way of denoting that a number is positive
---------- basic
theorem zero_or_positive (n : ℕ) : n = 0 ∨ n > 0
:= or.imp_or (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H) (take H : n > 0, H)
theorem succ_positive {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (lt_zero m)
theorem ne_zero_positive {n : ℕ} (H : n ≠ 0) : n > 0
:= or.elim (zero_or_positive n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2)
theorem pos_imp_eq_succ {n : ℕ} (H : n > 0) : ∃l, n = succ l
:= discriminate
(take H2, absurd (subst H2 H) (lt_irrefl 0))
(take l Hl, exists_intro l Hl)
theorem add_positive_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= obtain (l : ℕ) (Hl : k = succ l), from pos_imp_eq_succ H,
subst (symm Hl) (lt_intro2 n l)
theorem add_positive_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_positive_right n H)
-- Positivity
-- ---------
--
-- Writing "t > 0" is the preferred way to assert that a natural number is positive.
-- ### basic
-- See also succ_pos.
theorem succ_pos (n : ℕ) : 0 < succ n
:= succ_le (zero_le n)
theorem case_zero_pos {P : ℕ → Prop} (y : ℕ) (H0 : P 0) (H1 : ∀y, y > 0 → P y) : P y
:= case y H0 (take y', H1 _ (succ_pos _))
theorem zero_or_pos (n : ℕ) : n = 0 ∨ n > 0
:= or.imp_or_left (or.swap (le_imp_lt_or_eq (zero_le n))) (take H : 0 = n, symm H)
theorem succ_imp_pos {n m : ℕ} (H : n = succ m) : n > 0
:= subst (symm H) (succ_pos m)
theorem ne_zero_pos {n : ℕ} (H : n ≠ 0) : n > 0
:= or.elim (zero_or_pos n) (take H2 : n = 0, absurd H2 H) (take H2 : n > 0, H2)
theorem add_pos_right (n : ℕ) {k : ℕ} (H : k > 0) : n + k > n
:= subst (add_zero_right n) (add_lt_left H n)
theorem add_pos_left (n : ℕ) {k : ℕ} (H : k > 0) : k + n > n
:= subst (add_comm n k) (add_pos_right n H)
---------- mul
theorem mul_positive {n m : ℕ} (Hn : n > 0) (Hm : m > 0) : n * m > 0
:= obtain (k : ℕ) (Hk : n = succ k), from pos_imp_eq_succ Hn,
obtain (l : ℕ) (Hl : m = succ l), from pos_imp_eq_succ Hm,
succ_positive (calc
n * m = succ k * m : {Hk}
... = succ k * succ l : {Hl}
... = succ k * l + succ k : mul_succ_right (succ k) l
... = succ (succ k * l + k) : add_succ_right _ _)
theorem mul_positive_inv_left {n m : ℕ} (H : n * m > 0) : n > 0
:= discriminate
(assume H2 : n = 0,
have H3 : n * m = 0,
from calc
n * m = 0 * m : {H2}
... = 0 : mul_zero_left m,
have H4 : 0 > 0, from subst H3 H,
absurd H4 (lt_irrefl 0))
(take l : ℕ,
assume Hl : n = succ l,
subst (symm Hl) (lt_zero l))
theorem mul_positive_inv_right {n m : ℕ} (H : n * m > 0) : m > 0
:= mul_positive_inv_left (subst (mul_comm n m) H)
theorem mul_left_inj {n m k : ℕ} (Hn : n > 0) (H : n * m = n * k) : m = k
:=
have general : ∀m, n * m = n * k → m = k, from
induction_on k
(take m:ℕ,
assume H : n * m = n * 0,
have H2 : n * m = 0,
from calc
n * m = n * 0 : H
... = 0 : mul_zero_right n,
have H3 : n = 0 ∨ m = 0, from mul_eq_zero H2,
or.resolve_right H3 (ne.symm (lt_ne Hn)))
(take (l : ℕ),
assume (IH : ∀ m, n * m = n * l → m = l),
take (m : ℕ),
assume (H : n * m = n * succ l),
have H2 : n * succ l > 0, from mul_positive Hn (lt_zero l),
have H3 : m > 0, from mul_positive_inv_right (subst (symm H) H2),
obtain (l2:ℕ) (Hm : m = succ l2), from pos_imp_eq_succ H3,
have H4 : n * l2 + n = n * l + n,
from calc
n * l2 + n = n * succ l2 : symm (mul_succ_right n l2)
... = n * m : {symm Hm}
... = n * succ l : H
... = n * l + n : mul_succ_right n l,
have H5 : n * l2 = n * l, from add_cancel_right H4,
calc
m = succ l2 : Hm
... = succ l : {IH l2 H5}),
general m H
theorem mul_right_inj {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k
:= mul_left_inj Hm (subst (mul_comm k m) (subst (mul_comm n m) H))
-- mul_eq_one below
---------- interaction of mul with le and lt
theorem mul_lt_left {n m k : ℕ} (Hk : k > 0) (H : n < m) : k * n < k * m
:=
have H2 : k * n < k * n + k, from add_positive_right (k * n) Hk,
have H3 : k * n + k ≤ k * m, from subst (mul_succ_right k n) (mul_le_left H k),
lt_le_trans H2 H3
theorem mul_lt_right {n m k : ℕ} (Hk : k > 0) (H : n < m) : n * k < m * k
:= subst (mul_comm k m) (subst (mul_comm k n) (mul_lt_left Hk H))
theorem mul_le_lt {n m k l : ℕ} (Hk : k > 0) (H1 : n ≤ k) (H2 : m < l) : n * m < k * l
:= le_lt_trans (mul_le_right H1 m) (mul_lt_left Hk H2)
theorem mul_lt_le {n m k l : ℕ} (Hl : l > 0) (H1 : n < k) (H2 : m ≤ l) : n * m < k * l
:= le_lt_trans (mul_le_left H2 n) (mul_lt_right Hl H1)
theorem mul_lt {n m k l : ℕ} (H1 : n < k) (H2 : m < l) : n * m < k * l
:=
have H3 : n * m ≤ k * m, from mul_le_right (lt_imp_le H1) m,
have H4 : k * m < k * l, from mul_lt_left (le_lt_trans (zero_le n) H1) H2,
le_lt_trans H3 H4
theorem mul_lt_left_inv {n m k : ℕ} (H : k * n < k * m) : n < m
:=
have general : ∀ m, k * n < k * m → n < m, from
induction_on n
(take m : ℕ,
assume H2 : k * 0 < k * m,
have H3 : 0 < k * m, from mul_zero_right k ▸ H2,
show 0 < m, from mul_positive_inv_right H3)
(take l : ℕ,
assume IH : ∀ m, k * l < k * m → l < m,
take m : ℕ,
assume H2 : k * succ l < k * m,
have H3 : 0 < k * m, from le_lt_trans (zero_le _) H2,
have H4 : 0 < m, from mul_positive_inv_right H3,
obtain (l2 : ℕ) (Hl2 : m = succ l2), from pos_imp_eq_succ H4,
have H5 : k * l + k < k * m, from mul_succ_right k l ▸ H2,
have H6 : k * l + k < k * succ l2, from Hl2 ▸ H5,
have H7 : k * l + k < k * l2 + k, from mul_succ_right k l2 ▸ H6,
have H8 : k * l < k * l2, from add_lt_right_inv H7,
have H9 : l < l2, from IH l2 H8,
have H10 : succ l < succ l2, from succ_lt H9,
show succ l < m, from Hl2⁻¹ ▸ H10),
general m H
theorem mul_lt_right_inv {n m k : ℕ} (H : n * k < m * k) : n < m
:= mul_lt_left_inv (mul_comm m k ▸ mul_comm n k ▸ H)
theorem mul_le_left_inv {n m k : ℕ} (H : succ k * n ≤ succ k * m) : n ≤ m
:=
have H2 : succ k * n < succ k * m + succ k, from le_lt_trans H (lt_intro2 _ _),
have H3 : succ k * n < succ k * succ m, from subst (symm (mul_succ_right (succ k) m)) H2,
have H4 : n < succ m, from mul_lt_left_inv H3,
show n ≤ m, from lt_succ_imp_le H4
theorem mul_le_right_inv {n m k : ℕ} (H : n * succ m ≤ k * succ m) : n ≤ k
:= mul_le_left_inv (subst (mul_comm k (succ m)) (subst (mul_comm n (succ m)) H))
theorem mul_eq_one_left {n m : ℕ} (H : n * m = 1) : n = 1
:=
have H2 : n * m > 0, from subst (symm H) (lt_zero 0),
have H3 : n > 0, from mul_positive_inv_left H2,
have H4 : m > 0, from mul_positive_inv_right H2,
or.elim (le_or_lt n 1)
(assume H5 : n ≤ 1,
show n = 1, from le_antisym H5 H3)
(assume H5 : n > 1,
have H6 : n * m ≥ 2 * 1, from mul_le H5 H4,
have H7 : 1 ≥ 2, from subst (mul_one_right 2) (subst H H6),
absurd (self_lt_succ 1) (le_imp_not_gt H7))
theorem mul_eq_one_right {n m : ℕ} (H : n * m = 1) : m = 1
:= mul_eq_one_left (subst (mul_comm n m) H)
theorem mul_eq_one {n m : ℕ} (H : n * m = 1) : n = 1 ∧ m = 1
:= and.intro (mul_eq_one_left H) (mul_eq_one_right H)
-------------------------------------------------- sub
definition sub (n m : ℕ) : ℕ := nat.rec n (fun m x, pred x) m
infixl `-` := sub
theorem sub_zero_right (n : ℕ) : n - 0 = n
theorem sub_succ_right (n m : ℕ) : n - succ m = pred (n - m)
theorem sub_zero_left (n : ℕ) : 0 - n = 0
:= induction_on n (sub_zero_right 0)
(take k : ℕ,
assume IH : 0 - k = 0,
calc
0 - succ k = pred (0 - k) : sub_succ_right 0 k
... = pred 0 : {IH}
... = 0 : pred_zero)
theorem sub_succ_succ (n m : ℕ) : succ n - succ m = n - m
:= induction_on m
(calc
succ n - 1 = pred (succ n - 0) : sub_succ_right (succ n) 0
... = pred (succ n) : {sub_zero_right (succ n)}
... = n : pred_succ n
... = n - 0 : symm (sub_zero_right n))
(take k : ℕ,
assume IH : succ n - succ k = n - k,
calc
succ n - succ (succ k) = pred (succ n - succ k) : sub_succ_right (succ n) (succ k)
... = pred (n - k) : {IH}
... = n - succ k : symm (sub_succ_right n k))
theorem sub_one (n : ℕ) : n - 1 = pred n
:= calc
n - 1 = pred (n - 0) : sub_succ_right n 0
... = pred n : {sub_zero_right n}
theorem sub_self (n : ℕ) : n - n = 0
:= induction_on n (sub_zero_right 0) (take k IH, trans (sub_succ_succ k k) IH)
theorem sub_add_add_right (n m k : ℕ) : (n + k) - (m + k) = n - m
:= induction_on k
(calc
(n + 0) - (m + 0) = n - (m + 0) : {add_zero_right _}
... = n - m : {add_zero_right _})
(take l : ℕ,
assume IH : (n + l) - (m + l) = n - m,
calc
(n + succ l) - (m + succ l) = succ (n + l) - (m + succ l) : {add_succ_right _ _}
... = succ (n + l) - succ (m + l) : {add_succ_right _ _}
... = (n + l) - (m + l) : sub_succ_succ _ _
... = n - m : IH)
theorem sub_add_add_left (n m k : ℕ) : (k + n) - (k + m) = n - m
:= subst (add_comm m k) (subst (add_comm n k) (sub_add_add_right n m k))
theorem sub_add_left (n m : ℕ) : n + m - m = n
:= induction_on m
(subst (symm (add_zero_right n)) (sub_zero_right n))
(take k : ℕ,
assume IH : n + k - k = n,
calc
n + succ k - succ k = succ (n + k) - succ k : {add_succ_right n k}
... = n + k - k : sub_succ_succ _ _
... = n : IH)
theorem sub_sub (n m k : ℕ) : n - m - k = n - (m + k)
:= induction_on k
(calc
n - m - 0 = n - m : sub_zero_right _
... = n - (m + 0) : {symm (add_zero_right m)})
(take l : ℕ,
assume IH : n - m - l = n - (m + l),
calc
n - m - succ l = pred (n - m - l) : sub_succ_right (n - m) l
... = pred (n - (m + l)) : {IH}
... = n - succ (m + l) : symm (sub_succ_right n (m + l))
... = n - (m + succ l) : {symm (add_succ_right m l)})
theorem succ_sub_sub (n m k : ℕ) : succ n - m - succ k = n - m - k
:= calc
succ n - m - succ k = succ n - (m + succ k) : sub_sub _ _ _
... = succ n - succ (m + k) : {add_succ_right m k}
... = n - (m + k) : sub_succ_succ _ _
... = n - m - k : symm (sub_sub n m k)
theorem sub_add_right_eq_zero (n m : ℕ) : n - (n + m) = 0
:= calc
n - (n + m) = n - n - m : symm (sub_sub n n m)
... = 0 - m : {sub_self n}
... = 0 : sub_zero_left m
theorem sub_comm (m n k : ℕ) : m - n - k = m - k - n
:= calc
m - n - k = m - (n + k) : sub_sub m n k
... = m - (k + n) : {add_comm n k}
... = m - k - n : symm (sub_sub m k n)
theorem succ_sub_one (n : ℕ) : succ n - 1 = n
:= sub_succ_succ n 0 ⬝ sub_zero_right n
---------- mul
theorem mul_pred_left (n m : ℕ) : pred n * m = n * m - m
:= induction_on n
(calc
pred 0 * m = 0 * m : {pred_zero}
... = 0 : mul_zero_left _
... = 0 - m : symm (sub_zero_left m)
... = 0 * m - m : {symm (mul_zero_left m)})
(take k : ℕ,
assume IH : pred k * m = k * m - m,
calc
pred (succ k) * m = k * m : {pred_succ k}
... = k * m + m - m : symm (sub_add_left _ _)
... = succ k * m - m : {symm (mul_succ_left k m)})
theorem mul_pred_right (n m : ℕ) : n * pred m = n * m - n
:= calc n * pred m = pred m * n : mul_comm _ _
... = m * n - n : mul_pred_left m n
... = n * m - n : {mul_comm m n}
theorem mul_sub_distr_left (n m k : ℕ) : (n - m) * k = n * k - m * k
:= induction_on m
(calc
(n - 0) * k = n * k : {sub_zero_right n}
... = n * k - 0 : symm (sub_zero_right _)
... = n * k - 0 * k : {symm (mul_zero_left _)})
(take l : ℕ,
assume IH : (n - l) * k = n * k - l * k,
calc
(n - succ l) * k = pred (n - l) * k : {sub_succ_right n l}
... = (n - l) * k - k : mul_pred_left _ _
... = n * k - l * k - k : {IH}
... = n * k - (l * k + k) : sub_sub _ _ _
... = n * k - (succ l * k) : {symm (mul_succ_left l k)})
theorem mul_sub_distr_right (n m k : ℕ) : n * (m - k) = n * m - n * k
:= calc
n * (m - k) = (m - k) * n : mul_comm _ _
... = m * n - k * n : mul_sub_distr_left _ _ _
... = n * m - k * n : {mul_comm _ _}
... = n * m - n * k : {mul_comm _ _}
-------------------------------------------------- max, min, iteration, maybe: sub, div
theorem succ_sub {m n : ℕ} : m ≥ n → succ m - n = succ (m - n)
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
succ k - 0 = succ k : sub_zero_right (succ k)
... = succ (k - 0) : {symm (sub_zero_right k)})
(take k,
assume H : succ k ≤ 0,
absurd H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → succ l - k = succ (l - k),
take H : succ k ≤ succ l,
calc
succ (succ l) - succ k = succ l - k : sub_succ_succ (succ l) k
... = succ (l - k) : IH (succ_le_cancel H)
... = succ (succ l - succ k) : {symm (sub_succ_succ l k)})
theorem le_imp_sub_eq_zero {n m : ℕ} (H : n ≤ m) : n - m = 0
:= obtain (k : ℕ) (Hk : n + k = m), from le_elim H, subst Hk (sub_add_right_eq_zero n k)
theorem add_sub_le {n m : ℕ} : n ≤ m → n + (m - n) = m
:= sub_induction n m
(take k,
assume H : 0 ≤ k,
calc
0 + (k - 0) = k - 0 : add_zero_left (k - 0)
... = k : sub_zero_right k)
(take k, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k))
(take k l,
assume IH : k ≤ l → k + (l - k) = l,
take H : succ k ≤ succ l,
calc
succ k + (succ l - succ k) = succ k + (l - k) : {sub_succ_succ l k}
... = succ (k + (l - k)) : add_succ_left k (l - k)
... = succ l : {IH (succ_le_cancel H)})
theorem add_sub_ge_left {n m : ℕ} : n ≥ m → n - m + m = n
:= subst (add_comm m (n - m)) add_sub_le
theorem add_sub_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n
:= calc
n + (m - n) = n + 0 : {le_imp_sub_eq_zero H}
... = n : add_zero_right n
theorem add_sub_le_left {n m : ℕ} : n ≤ m → n - m + m = m
:= subst (add_comm m (n - m)) add_sub_ge
theorem le_add_sub_left (n m : ℕ) : n ≤ n + (m - n)
:= or.elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) H)
(assume H : m ≤ n, subst (symm (add_sub_ge H)) (le_refl n))
theorem le_add_sub_right (n m : ℕ) : m ≤ n + (m - n)
:= or.elim (le_total n m)
(assume H : n ≤ m, subst (symm (add_sub_le H)) (le_refl m))
(assume H : m ≤ n, subst (symm (add_sub_ge H)) H)
theorem sub_split {P : ℕ → Prop} {n m : ℕ} (H1 : n ≤ m → P 0) (H2 : ∀k, m + k = n -> P k)
: P (n - m)
:= or.elim (le_total n m)
(assume H3 : n ≤ m, subst (symm (le_imp_sub_eq_zero H3)) (H1 H3))
(assume H3 : m ≤ n, H2 (n - m) (add_sub_le H3))
theorem sub_le_self (n m : ℕ) : n - m ≤ n
:=
sub_split
(assume H : n ≤ m, zero_le n)
(take k : ℕ, assume H : m + k = n, le_intro (subst (add_comm m k) H))
theorem le_elim_sub (n m : ℕ) (H : n ≤ m) : ∃k, m - k = n
:=
obtain (k : ℕ) (Hk : n + k = m), from le_elim H,
exists_intro k
(calc
m - k = n + k - k : {symm Hk}
... = n : sub_add_left n k)
theorem add_sub_assoc {m k : ℕ} (H : k ≤ m) (n : ℕ) : n + m - k = n + (m - k)
:= have l1 : k ≤ m → n + m - k = n + (m - k), from
sub_induction k m
(take m : ℕ,
assume H : 0 ≤ m,
calc
n + m - 0 = n + m : sub_zero_right (n + m)
... = n + (m - 0) : {symm (sub_zero_right m)})
(take k : ℕ, assume H : succ k ≤ 0, absurd H (not_succ_zero_le k))
(take k m,
assume IH : k ≤ m → n + m - k = n + (m - k),
take H : succ k ≤ succ m,
calc
n + succ m - succ k = succ (n + m) - succ k : {add_succ_right n m}
... = n + m - k : sub_succ_succ (n + m) k
... = n + (m - k) : IH (succ_le_cancel H)
... = n + (succ m - succ k) : {symm (sub_succ_succ m k)}),
l1 H
theorem sub_eq_zero_imp_le {n m : ℕ} : n - m = 0 → n ≤ m
:= sub_split
(assume H1 : n ≤ m, assume H2 : 0 = 0, H1)
(take k : ℕ,
assume H1 : m + k = n,
assume H2 : k = 0,
have H3 : n = m, from subst (add_zero_right m) (subst H2 (symm H1)),
subst H3 (le_refl n))
theorem sub_sub_split {P : ℕ → ℕ → Prop} {n m : ℕ} (H1 : ∀k, n = m + k -> P k 0)
(H2 : ∀k, m = n + k → P 0 k) : P (n - m) (m - n)
:= or.elim (le_total n m)
(assume H3 : n ≤ m,
le_imp_sub_eq_zero H3⁻¹ ▸ (H2 (m - n) (add_sub_le H3⁻¹)))
(assume H3 : m ≤ n,
le_imp_sub_eq_zero H3⁻¹ ▸ (H1 (n - m) (add_sub_le H3⁻¹)))
theorem sub_intro {n m k : ℕ} (H : n + m = k) : k - n = m
:= have H2 : k - n + n = m + n, from
calc
k - n + n = k : add_sub_ge_left (le_intro H)
... = n + m : symm H
... = m + n : add_comm n m,
add_cancel_right H2
theorem sub_lt {x y : ℕ} (xpos : x > 0) (ypos : y > 0) : x - y < x
:= obtain (x' : ℕ) (xeq : x = succ x'), from pos_imp_eq_succ xpos,
obtain (y' : ℕ) (yeq : y = succ y'), from pos_imp_eq_succ ypos,
have xsuby_eq : x - y = x' - y', from
calc
x - y = succ x' - y : {xeq}
... = succ x' - succ y' : {yeq}
... = x' - y' : sub_succ_succ _ _,
have H1 : x' - y' ≤ x', from sub_le_self _ _,
have H2 : x' < succ x', from self_lt_succ _,
show x - y < x, from xeq⁻¹ ▸ xsuby_eq⁻¹ ▸ le_lt_trans H1 H2
-- Max, min, iteration, and absolute difference
-- --------------------------------------------
definition max (n m : ℕ) : ℕ := n + (m - n)
definition min (n m : ℕ) : ℕ := m - (m - n)
theorem max_le {n m : ℕ} (H : n ≤ m) : n + (m - n) = m := add_sub_le H
theorem max_ge {n m : ℕ} (H : n ≥ m) : n + (m - n) = n := add_sub_ge H
theorem left_le_max (n m : ℕ) : n ≤ n + (m - n) := le_add_sub_left n m
theorem right_le_max (n m : ℕ) : m ≤ max n m := le_add_sub_right n m
-- ### absolute difference
-- This section is still incomplete
definition dist (n m : ℕ) := (n - m) + (m - n)
theorem dist_comm (n m : ℕ) : dist n m = dist m n
:= add_comm (n - m) (m - n)
theorem dist_eq_zero {n m : ℕ} (H : dist n m = 0) : n = m
:=
have H2 : n - m = 0, from add_eq_zero_left H,
have H3 : n ≤ m, from sub_eq_zero_imp_le H2,
have H4 : m - n = 0, from add_eq_zero_right H,
have H5 : m ≤ n, from sub_eq_zero_imp_le H4,
le_antisym H3 H5
theorem dist_le {n m : ℕ} (H : n ≤ m) : dist n m = m - n
:= calc
dist n m = (n - m) + (m - n) : eq.refl _
... = 0 + (m - n) : {le_imp_sub_eq_zero H}
... = m - n : add_zero_left (m - n)
theorem dist_ge {n m : ℕ} (H : n ≥ m) : dist n m = n - m
:= subst (dist_comm m n) (dist_le H)
theorem dist_zero_right (n : ℕ) : dist n 0 = n
:= trans (dist_ge (zero_le n)) (sub_zero_right n)
theorem dist_zero_left (n : ℕ) : dist 0 n = n
:= trans (dist_le (zero_le n)) (sub_zero_right n)
theorem dist_intro {n m k : ℕ} (H : n + m = k) : dist k n = m
:= calc
dist k n = k - n : dist_ge (le_intro H)
... = m : sub_intro H
theorem dist_add_right (n k m : ℕ) : dist (n + k) (m + k) = dist n m
:=
calc
dist (n + k) (m + k) = ((n+k) - (m+k)) + ((m+k)-(n+k)) : eq.refl _
... = (n - m) + ((m + k) - (n + k)) : {sub_add_add_right _ _ _}
... = (n - m) + (m - n) : {sub_add_add_right _ _ _}
theorem dist_add_left (k n m : ℕ) : dist (k + n) (k + m) = dist n m
:= subst (add_comm m k) (subst (add_comm n k) (dist_add_right n k m))
theorem dist_ge_add_right {n m : ℕ} (H : n ≥ m) : dist n m + m = n
:= calc
dist n m + m = n - m + m : {dist_ge H}
... = n : add_sub_ge_left H
theorem dist_eq_intro {n m k l : ℕ} (H : n + m = k + l) : dist n k = dist l m
:= calc
dist n k = dist (n + m) (k + m) : symm (dist_add_right n m k)
... = dist (k + l) (k + m) : {H}
... = dist l m : dist_add_left k l m
end nat
end experiment
|
f0719c710b5b02a2b51f77aca6ca74129fe2f443 | 87a08a8e9b222ec02f3327dca4ae24590c1b3de9 | /src/set_theory/cardinal.lean | ecd3106ff6ee38f6b57c414c9a7a36d249341462 | [
"Apache-2.0"
] | permissive | naussicaa/mathlib | 86d05223517a39e80920549a8052f9cf0e0b77b8 | 1ef2c2df20cf45c21675d855436228c7ae02d47a | refs/heads/master | 1,592,104,950,080 | 1,562,073,069,000 | 1,562,073,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 39,713 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl, Mario Carneiro
Cardinal arithmetic.
Cardinals are represented as quotient over equinumerous types.
-/
import data.set.countable data.quot logic.function set_theory.schroeder_bernstein
open function lattice set
local attribute [instance] classical.prop_decidable
universes u v w x
variables {α β : Type u}
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα β, nonempty (α ≃ β),
iseqv := ⟨λα,
⟨equiv.refl α⟩,
λα β ⟨e⟩, ⟨e.symm⟩,
λα β γ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal of a type -/
def mk : Type u → cardinal := quotient.mk
@[simp] theorem mk_def (α : Type u) : @eq cardinal ⟦α⟧ (mk α) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
instance : has_le cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, nonempty $ α ↪ β) $
assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
propext ⟨assume ⟨e⟩, ⟨e.congr e₁ e₂⟩, assume ⟨e⟩, ⟨e.congr e₁.symm e₂.symm⟩⟩⟩
theorem mk_le_of_injective {α β : Type u} {f : α → β} (hf : injective f) : mk α ≤ mk β :=
⟨⟨f, hf⟩⟩
theorem mk_le_of_surjective {α β : Type u} {f : α → β} (hf : surjective f) : mk β ≤ mk α :=
⟨embedding.of_surjective hf⟩
theorem le_mk_iff_exists_set {c : cardinal} {α : Type u} :
c ≤ mk α ↔ ∃ p : set α, mk p = c :=
⟨quotient.induction_on c $ λ β ⟨⟨f, hf⟩⟩,
⟨set.range f, eq.symm $ quot.sound ⟨equiv.set.range f hf⟩⟩,
λ ⟨p, e⟩, e ▸ ⟨⟨subtype.val, λ a b, subtype.eq⟩⟩⟩
theorem out_embedding {c c' : cardinal} : c ≤ c' ↔ nonempty (c.out ↪ c'.out) :=
by { transitivity _, rw [←quotient.out_eq c, ←quotient.out_eq c'], refl }
instance : linear_order cardinal.{u} :=
{ le := (≤),
le_refl := by rintros ⟨α⟩; exact ⟨embedding.refl _⟩,
le_trans := by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨e₁.trans e₂⟩,
le_antisymm := by rintros ⟨α⟩ ⟨β⟩ ⟨e₁⟩ ⟨e₂⟩; exact quotient.sound (e₁.antisymm e₂),
le_total := by rintros ⟨α⟩ ⟨β⟩; exact embedding.total }
noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance
instance : has_zero cardinal.{u} := ⟨⟦pempty⟧⟩
instance : inhabited cardinal.{u} := ⟨0⟩
theorem ne_zero_iff_nonempty {α : Type u} : mk α ≠ 0 ↔ nonempty α :=
not_iff_comm.1
⟨λ h, quotient.sound ⟨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pempty⟩,
λ e, let ⟨h⟩ := quotient.exact e in λ ⟨a⟩, (h a).elim⟩
instance : has_one cardinal.{u} := ⟨⟦punit⟧⟩
instance : zero_ne_one_class cardinal.{u} :=
{ zero := 0, one := 1, zero_ne_one :=
ne.symm $ ne_zero_iff_nonempty.2 ⟨punit.star⟩ }
theorem le_one_iff_subsingleton {α : Type u} : mk α ≤ 1 ↔ subsingleton α :=
⟨λ ⟨f⟩, ⟨λ a b, f.inj (subsingleton.elim _ _)⟩,
λ ⟨h⟩, ⟨⟨λ a, punit.star, λ a b _, h _ _⟩⟩⟩
instance : has_add cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α ⊕ β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.sum_congr e₁ e₂⟩⟩
@[simp] theorem add_def (α β) : mk α + mk β = mk (α ⊕ β) := rfl
instance : has_mul cardinal.{u} :=
⟨λq₁ q₂, quotient.lift_on₂ q₁ q₂ (λα β, mk (α × β)) $ assume α β γ δ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.prod_congr e₁ e₂⟩⟩
@[simp] theorem mul_def (α β : Type u) : mk α * mk β = mk (α × β) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.sum_comm α β⟩
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_on₂ a b $ assume α β, quotient.sound ⟨equiv.prod_comm α β⟩
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_sum α⟩
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.pempty_prod α⟩
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume α, quotient.sound ⟨equiv.punit_prod α⟩
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ assume α β γ, quotient.sound ⟨equiv.prod_sum_distrib α β γ⟩
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_assoc α β γ⟩,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := λa b c, quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.prod_assoc α β γ⟩,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk α ^ mk β` is the cardinal of `β → α`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_on₂ a b (λα β, mk (β → α)) $ assume α₁ α₂ β₁ β₂ ⟨e₁⟩ ⟨e₂⟩,
quotient.sound ⟨equiv.arrow_congr e₂ e₁⟩
instance : has_pow cardinal cardinal := ⟨cardinal.power⟩
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (α β) : mk α ^ mk β = mk (β → α) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.pempty_arrow_equiv_punit α⟩
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.punit_arrow_equiv α⟩
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume α, quotient.sound
⟨equiv.arrow_punit_equiv_punit α⟩
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound ⟨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem zero_power {a : cardinal} : a ≠ 0 → 0 ^ a = 0 :=
quotient.induction_on a $ assume α heq,
nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a,
quotient.sound ⟨equiv.equiv_pempty $ assume f, pempty.rec (λ _, false) (f a)⟩
theorem power_ne_zero {a : cardinal} (b) : a ≠ 0 → a ^ b ≠ 0 :=
quotient.induction_on₂ a b $ λ α β h,
let ⟨a⟩ := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 ⟨λ _, a⟩
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_prod_equiv_prod_arrow α β γ⟩
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.sum_arrow_equiv_prod_arrow β γ α⟩
theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) :=
by rw [_root_.mul_comm b c];
from (quotient.induction_on₃ a b c $ assume α β γ,
quotient.sound ⟨equiv.arrow_arrow_equiv_prod_arrow γ β α⟩)
section order_properties
open sum
theorem zero_le : ∀(a : cardinal), 0 ≤ a :=
by rintro ⟨α⟩; exact ⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim⟩
theorem le_zero (a : cardinal) : a ≤ 0 ↔ a = 0 :=
by simp [le_antisymm_iff, zero_le]
theorem pos_iff_ne_zero {o : cardinal} : 0 < o ↔ o ≠ 0 :=
by simp [lt_iff_le_and_ne, eq_comm, zero_le]
theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c ≤ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem add_le_add : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a + c ≤ b + d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.sum_congr e₁ e₂⟩
theorem add_le_add_left (a) {b c : cardinal} : b ≤ c → a + b ≤ a + c :=
add_le_add (le_refl _)
theorem add_le_add_right {a b : cardinal} (c) (h : a ≤ b) : a + c ≤ b + c :=
add_le_add h (le_refl _)
theorem le_add_right (a b : cardinal) : a ≤ a + b :=
by simpa using add_le_add_left a (zero_le b)
theorem le_add_left (a b : cardinal) : a ≤ b + a :=
by simpa using add_le_add_right a (zero_le b)
theorem mul_le_mul : ∀{a b c d : cardinal}, a ≤ b → c ≤ d → a * c ≤ b * d :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ ⟨δ⟩ ⟨e₁⟩ ⟨e₂⟩; exact ⟨embedding.prod_congr e₁ e₂⟩
theorem mul_le_mul_left (a) {b c : cardinal} : b ≤ c → a * b ≤ a * c :=
mul_le_mul (le_refl _)
theorem mul_le_mul_right {a b : cardinal} (c) (h : a ≤ b) : a * c ≤ b * c :=
mul_le_mul h (le_refl _)
theorem power_le_power_left : ∀{a b c : cardinal}, a ≠ 0 → b ≤ c → a ^ b ≤ a ^ c :=
by rintros ⟨α⟩ ⟨β⟩ ⟨γ⟩ hα ⟨e⟩; exact
let ⟨a⟩ := ne_zero_iff_nonempty.1 hα in
⟨@embedding.arrow_congr_right _ _ _ ⟨a⟩ e⟩
theorem power_le_power_right {a b c : cardinal} : a ≤ b → a ^ c ≤ b ^ c :=
quotient.induction_on₃ a b c $ assume α β γ ⟨e⟩, ⟨embedding.arrow_congr_left e⟩
theorem le_iff_exists_add {a b : cardinal} : a ≤ b ↔ ∃ c, b = a + c :=
⟨quotient.induction_on₂ a b $ λ α β ⟨⟨f, hf⟩⟩,
have (α ⊕ ↥-range f) ≃ β, from
(equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
⟨⟦(-range f : set β)⟧, quotient.sound ⟨this.symm⟩⟩,
λ ⟨c, e⟩, add_zero a ▸ e.symm ▸ add_le_add_left _ (zero_le _)⟩
end order_properties
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := zero_le, ..cardinal.linear_order }
instance : canonically_ordered_monoid cardinal.{u} :=
{ add_le_add_left := λ a b h c, add_le_add_left _ h,
lt_of_add_lt_add_left := λ a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _),
le_iff_exists_add := @le_iff_exists_add,
..cardinal.lattice.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
theorem cantor : ∀(a : cardinal.{u}), a < 2 ^ a :=
by rw ← prop_eq_two; rintros ⟨a⟩; exact ⟨
⟨⟨λ a b, ⟨a = b⟩, λ a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rfl⟩⟩,
λ ⟨⟨f, hf⟩⟩, cantor_injective (λ s, f (λ a, ⟨s a⟩)) $
λ s t h, by funext a; injection congr_fun (hf h) a⟩
instance : no_top_order cardinal.{u} :=
{ no_top := λ a, ⟨_, cantor a⟩, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ι} (I : nonempty ι) (f : ι → cardinal) : cardinal :=
f $ classical.some $
@embedding.injective_min _ (λ i, (f i).out) I
theorem min_eq {ι} (I) (f : ι → cardinal) : ∃ i, min I f = f i :=
⟨_, rfl⟩
theorem min_le {ι I} (f : ι → cardinal) (i) : min I f ≤ f i :=
by rw [← mk_out (min I f), ← mk_out (f i)]; exact
let ⟨g⟩ := classical.some_spec
(@embedding.injective_min _ (λ i, (f i).out) I) in
⟨g i⟩
theorem le_min {ι I} {f : ι → cardinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i :=
⟨λ h i, le_trans h (min_le _ _),
λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩
protected theorem wf : @well_founded cardinal.{u} (<) :=
⟨λ a, classical.by_contradiction $ λ h,
let ι := {c :cardinal // ¬ acc (<) c},
f : ι → cardinal := subtype.val,
⟨⟨c, hc⟩, hi⟩ := @min_eq ι ⟨⟨_, h⟩⟩ f in
hc (acc.intro _ (λ j ⟨_, h'⟩,
classical.by_contradiction $ λ hj, h' $
by have := min_le f ⟨j, hj⟩; rwa hi at this))⟩
instance has_wf : @has_well_founded cardinal.{u} := ⟨(<), cardinal.wf⟩
instance wo : @is_well_order cardinal.{u} (<) := ⟨cardinal.wf⟩
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} ⟨⟨_, cantor _⟩⟩ subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _), λ h,
by exact min_le _ (subtype.mk b h)⟩
theorem lt_succ {a b : cardinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 ≤ succ c :=
begin
refine quot.induction_on c (λ α, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r α)) (λ β h, _),
cases h.left with f,
have : ¬ surjective f := λ hn,
ne_of_lt h (quotient.sound ⟨equiv.of_bijective ⟨f.inj, hn⟩⟩),
cases classical.not_forall.1 this with b nex,
refine ⟨⟨sum.rec (by exact f) _, _⟩⟩,
{ exact λ _, b },
{ intros a b h, rcases a with a|⟨⟨⟨⟩⟩⟩; rcases b with b|⟨⟨⟨⟩⟩⟩,
{ rw f.inj h },
{ exact nex.elim ⟨_, h⟩ },
{ exact nex.elim ⟨_, h.symm⟩ },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c ≠ 0 :=
by { rw [←pos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ι} (f : ι → cardinal) : cardinal := mk Σ i, (f i).out
theorem le_sum {ι} (f : ι → cardinal) (i) : f i ≤ sum f :=
by rw ← quotient.out_eq (f i); exact
⟨⟨λ a, ⟨i, a⟩, λ a b h, eq_of_heq $ by injection h⟩⟩
@[simp] theorem sum_mk {ι} (f : ι → Type*) : sum (λ i, mk (f i)) = mk (Σ i, f i) :=
quot.sound ⟨equiv.sigma_congr_right $ λ i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)⟩
theorem sum_const (ι : Type u) (a : cardinal.{u}) : sum (λ _:ι, a) = mk ι * a :=
quotient.induction_on a $ λ α, by simp; exact
quotient.sound ⟨equiv.sigma_equiv_prod _ _⟩
theorem sum_le_sum {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sum f ≤ sum g :=
⟨embedding.sigma_congr_right $ λ i, classical.choice $
by have := H i; rwa [← quot.out_eq (f i), ← quot.out_eq (g i)] at this⟩
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ι} (f : ι → cardinal) : cardinal :=
@min {c // ∀ i, f i ≤ c} ⟨⟨sum f, le_sum f⟩⟩ (λ a, a.1)
theorem le_sup {ι} (f : ι → cardinal) (i) : f i ≤ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ι} {f : ι → cardinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h,
λ h, by dsimp [sup]; change a with (⟨a, h⟩:subtype _).1; apply min_le⟩
theorem sup_le_sup {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : sup f ≤ sup g :=
sup_le.2 $ λ i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ι} (f : ι → cardinal) : sup f ≤ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ι : Type u} (f : ι → cardinal.{u}) : sum f ≤ mk ι * sup.{u u} f :=
by rw ← sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ι} {f : ι → cardinal} (h : ι → false) : sup f = 0 :=
by { rw [←le_zero, sup_le], intro x, exfalso, exact h x }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ι : Type u} (f : ι → cardinal) : cardinal := mk (Π i, (f i).out)
@[simp] theorem prod_mk {ι} (f : ι → Type*) : prod (λ i, mk (f i)) = mk (Π i, f i) :=
quot.sound ⟨equiv.Pi_congr_right $ λ i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)⟩
theorem prod_const (ι : Type u) (a : cardinal.{u}) : prod (λ _:ι, a) = a ^ mk ι :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i ≤ g i) : prod f ≤ prod g :=
⟨embedding.Pi_congr_right $ λ i, classical.choice $
by have := H i; rwa [← mk_out (f i), ← mk_out (g i)] at this⟩
theorem prod_ne_zero {ι} (f : ι → cardinal) : prod f ≠ 0 ↔ ∀ i, f i ≠ 0 :=
begin
conv in (f _) {rw ← mk_out (f i)},
simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def],
exact ⟨λ ⟨F⟩ i, ⟨F i⟩, λ h, ⟨λ i, classical.choice (h i)⟩⟩,
end
theorem prod_eq_zero {ι} (f : ι → cardinal) : prod f = 0 ↔ ∃ i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (λ α, ⟦ulift α⟧) $ λ α β ⟨e⟩,
quotient.sound ⟨equiv.ulift.trans $ e.trans equiv.ulift.symm⟩
theorem lift_mk (α) : lift.{u v} (mk α) = mk (ulift.{v u} α) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ λ α, quot.sound ⟨equiv.ulift⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ λ α,
quotient.sound ⟨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symm⟩
theorem lift_mk_le {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) ≤ lift.{v (max u w)} (mk β) ↔ nonempty (α ↪ β) :=
⟨λ ⟨f⟩, ⟨embedding.congr equiv.ulift equiv.ulift f⟩,
λ ⟨f⟩, ⟨embedding.congr equiv.ulift.symm equiv.ulift.symm f⟩⟩
theorem lift_mk_eq {α : Type u} {β : Type v} :
lift.{u (max v w)} (mk α) = lift.{v (max u w)} (mk β) ↔ nonempty (α ≃ β) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨equiv.ulift.symm.trans $ f.trans equiv.ulift⟩,
λ ⟨f⟩, ⟨equiv.ulift.trans $ f.trans equiv.ulift.symm⟩⟩
@[simp] theorem lift_le {a b : cardinal} : lift a ≤ lift b ↔ a ≤ b :=
quotient.induction_on₂ a b $ λ α β,
by rw ← lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b ↔ a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b ↔ a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨equiv.ulift.trans equiv.pempty_equiv_pempty⟩
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨equiv.ulift.trans equiv.punit_equiv_punit⟩
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_on₂ a b $ λ α β,
quotient.sound ⟨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symm⟩
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ι I} (f : ι → cardinal) : lift (min I f) = min I (lift ∘ f) :=
le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $
let ⟨i, e⟩ := min_eq I (lift ∘ f) in
by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $
by have := min_le (lift ∘ f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a → ∃ a', lift a' = b :=
quotient.induction_on₂ a b $ λ α β,
by dsimp; rw [← lift_id (mk β), ← lift_umax, ← lift_umax.{u v}, lift_mk_le]; exact
λ ⟨f⟩, ⟨mk (set.range f), eq.symm $ lift_mk_eq.2
⟨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ λ ⟨a, ⟨b, e⟩⟩, ⟨b, subtype.eq e⟩⟩⟩
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a :=
⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a ↔ ∃ a', lift a' = b ∧ a' < a :=
⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
⟨a', e, lift_lt.1 $ e.symm ▸ h⟩,
λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ λ h, begin
rcases lt_lift_iff.1 h with ⟨b, e, h⟩,
rw [lt_succ, ← lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
/-- `ω` is the smallest infinite cardinal, also known as ℵ₀. -/
def omega : cardinal.{u} := lift (mk ℕ)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega ≠ 0 :=
ne_zero_iff_nonempty.2 ⟨⟨0⟩⟩
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
@[simp] theorem mk_fin : ∀ (n : ℕ), mk (fin n) = n
| 0 := quotient.sound ⟨(equiv.pempty_of_not_nonempty $ λ ⟨h⟩, h.elim0)⟩
| (n+1) := by rw [nat.cast_succ, ← mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n; simp *
theorem lift_mk_fin (n : ℕ) : lift (mk (fin n)) = n := by simp
theorem fintype_card (α : Type u) [fintype α] : mk α = fintype.card α :=
by rw [← lift_mk_fin.{u}, ← lift_id (mk α), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {α} (s : finset α) :
(s.card : cardinal) ≤ cardinal.mk α :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk (↑s : set α)),
{ exact ⟨function.embedding.subtype _⟩ },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp] theorem nat_cast_pow {m n : ℕ} : (↑(pow m n) : cardinal) = m ^ n :=
by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : cardinal) ≤ n ↔ m ≤ n :=
by rw [← lift_mk_fin, ← lift_mk_fin, lift_le]; exact
⟨λ ⟨⟨f, hf⟩⟩, begin
have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf,
simp at this,
rw [← fintype.card_fin n, ← this],
exact finset.card_le_of_subset (finset.subset_univ _)
end,
λ h, ⟨⟨λ i, ⟨i.1, lt_of_lt_of_le i.2 h⟩, λ a b h,
have _, from fin.veq_of_eq h, fin.eq_of_veq this⟩⟩⟩
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : cardinal) < n ↔ m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : cardinal) = n ↔ m = n :=
by simp [le_antisymm_iff]
@[simp] theorem nat_succ (n : ℕ) : succ n = n.succ :=
le_antisymm (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _) (add_one_le_succ _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by simpa using nat_succ 0
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [← succ_le, (by simpa using nat_succ 1 : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 ≤ c ↔ 0 < c :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 ≤ c ↔ c ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : ℕ) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [nat_succ, ← lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
⟨⟨fin.val, λ a b, fin.eq_of_veq⟩⟩
theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega ↔ ∃ n : ℕ, c = n :=
⟨λ h, begin
rcases lt_lift_iff.1 h with ⟨c, rfl, h'⟩,
rcases le_mk_iff_exists_set.1 h'.1 with ⟨S, rfl⟩,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [← lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : ∀ (n : ℕ) (IH : ∀ i<n, S), ∃ a : S, ¬ ∃ y h, IH y h = a :=
λ n IH,
let g : {i | i < n} → S := λ ⟨i, h⟩, IH i h in
classical.not_forall.1 (λ h, nf
⟨fintype.of_surjective g (λ a, subtype.exists.2 (h a))⟩),
let F : ℕ → S := nat.lt_wf.fix (λ n IH, classical.some (P n IH)),
refine not_le_of_lt h' ⟨⟨F, _⟩⟩,
suffices : ∀ (n : ℕ) (m < n), F m ≠ F n,
{ refine λ m n, not_imp_not.1 (λ ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (λ y _, F y)),
rw [← show F n = classical.some (P n (λ y _, F y)),
from nat.lt_wf.fix_eq (λ n IH, classical.some (P n IH)) n] at this,
exact λ e, this ⟨m, h, e⟩,
end, λ ⟨n, e⟩, e.symm ▸ nat_lt_omega _⟩
theorem omega_le {c : cardinal.{u}} : omega ≤ c ↔ ∀ n : ℕ, (n:cardinal) ≤ c :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ h, le_of_not_lt $ λ hn, begin
rcases lt_omega.1 hn with ⟨n, rfl⟩,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
end⟩
theorem lt_omega_iff_fintype {α : Type u} : mk α < omega ↔ nonempty (fintype α) :=
lt_omega.trans ⟨λ ⟨n, e⟩, begin
rw [← lift_mk_fin n] at e,
cases quotient.exact e with f,
exact ⟨fintype.of_equiv _ f.symm⟩
end, λ ⟨_⟩, by exactI ⟨_, fintype_card _⟩⟩
theorem lt_omega_iff_finite {α} {S : set α} : mk S < omega ↔ finite S :=
lt_omega_iff_fintype
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_add]; apply nat_lt_omega
end
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat.cast_mul]; apply nat_lt_omega
end
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, ⟨m, rfl⟩, ⟨n, rfl⟩ := by rw [← nat_cast_pow]; apply nat_lt_omega
end
theorem infinite_iff {α : Type u} : infinite α ↔ omega ≤ mk α :=
by rw [←not_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma countable_iff (s : set α) : countable s ↔ mk s ≤ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro ⟨f, hf⟩, exact ⟨embedding.trans ⟨f, hf⟩ equiv.ulift.symm.to_embedding⟩,
rintro ⟨f'⟩, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact ⟨f, hf⟩
end
lemma denumerable_iff {α : Type u} : nonempty (denumerable α) ↔ mk α = omega :=
⟨λ⟨h⟩, quotient.sound $ by exactI ⟨ (denumerable.eqv α).trans equiv.ulift.symm ⟩,
λ h, by { cases quotient.exact h with f, exact ⟨denumerable.mk' $ f.trans equiv.ulift⟩ }⟩
lemma mk_int : mk ℤ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma mk_pnat : mk ℕ+ = omega :=
denumerable_iff.mp ⟨by apply_instance⟩
lemma two_le_iff : (2 : cardinal) ≤ mk α ↔ ∃x y : α, x ≠ y :=
begin
split,
{ rintro ⟨f⟩, refine ⟨f $ sum.inl ⟨⟩, f $ sum.inr ⟨⟩, _⟩, intro h, cases f.2 h },
{ rintro ⟨x, y, h⟩, by_contra h',
rw [not_le, ←nat.cast_two, ←nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : α) : (2 : cardinal) ≤ mk α ↔ ∃y : α, x ≠ y :=
begin
rw [two_le_iff],
split,
{ rintro ⟨y, z, h⟩, refine classical.by_cases (λ(h' : x = y), _) (λ h', ⟨y, h'⟩),
rw [←h'] at h, exact ⟨z, h⟩ },
{ rintro ⟨y, h⟩, exact ⟨x, y, h⟩ }
end
/-- König's theorem -/
theorem sum_lt_prod {ι} (f g : ι → cardinal) (H : ∀ i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ λ ⟨F⟩, begin
have : inhabited (Π (i : ι), (g i).out),
{ refine ⟨λ i, classical.choice $ ne_zero_iff_nonempty.1 _⟩,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show ∀ i, ∃ b, ∀ a, G ⟨i, a⟩ i ≠ b,
{ assume i,
simp only [- not_exists, not_exists.symm, classical.not_forall.symm],
refine λ h, not_le_of_lt (H i) _,
rw [← mk_out (f i), ← mk_out (g i)],
exact ⟨embedding.of_surjective h⟩ },
exact (let ⟨⟨i, a⟩, h⟩ := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : ¬ p) : mk (plift p) = 0 :=
quotient.sound ⟨equiv.plift.trans $ equiv.equiv_pempty h⟩
@[simp] theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {α : Type u} (x : α) : mk ({x} : set α) = 1 :=
quotient.sound ⟨equiv.set.singleton x⟩
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound ⟨equiv.plift.trans $ equiv.prop_equiv_punit h⟩
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound ⟨equiv.bool_equiv_punit_sum_punit⟩
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound ⟨equiv.Prop_equiv_bool⟩ : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_option {α : Type u} : mk (option α) = mk α + 1 :=
quotient.sound ⟨equiv.option_equiv_sum_punit α⟩
theorem mk_list_eq_sum_pow (α : Type u) : mk (list α) = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) :=
calc mk (list α)
= mk (Σ n, vector α n) : quotient.sound ⟨equiv.equiv_sigma_subtype list.length⟩
... = mk (Σ n, fin n → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩⟩
... = mk (Σ n : ℕ, ulift.{u} (fin n) → α) : quotient.sound ⟨equiv.sigma_congr_right $ λ n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl α)⟩
... = sum (λ n : ℕ, (mk α)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {α : Type u} {r : α → α → Prop} : mk (quot r) ≤ mk α :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {α : Type u} {s : setoid α} : mk (quotient s) ≤ mk α :=
mk_quot_le
theorem mk_subtype_le {α : Type u} {s : set α} : mk s ≤ mk α :=
mk_le_of_injective subtype.val_injective
@[simp] theorem mk_emptyc (α : Type u) : mk (∅ : set α) = 0 :=
quotient.sound ⟨equiv.set.pempty α⟩
theorem mk_univ {α : Type u} : mk (@univ α) = mk α :=
quotient.sound ⟨equiv.set.univ α⟩
theorem mk_image_le {α β : Type u} {f : α → β} {s : set α} : mk (f '' s) ≤ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_range_le {α β : Type u} {f : α → β} : mk (range f) ≤ mk α :=
mk_le_of_surjective surjective_onto_range
lemma mk_range_eq (f : α → β) (h : injective f) : mk (range f) = mk α :=
quotient.sound ⟨(equiv.set.range f h).symm⟩
theorem mk_image_eq {α β : Type u} {f : α → β} {s : set α} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image f s hf).symm⟩
theorem mk_Union_le_sum_mk {α ι : Type u} {f : ι → set α} : mk (⋃ i, f i) ≤ sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) ≤ mk (Σ i, f i) : mk_le_of_surjective (set.surjective_sigma_to_Union f)
... = sum (λ i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {α ι : Type u} {f : ι → set α} (h : ∀i j, i ≠ j → disjoint (f i) (f j)) :
mk (⋃ i, f i) = sum (λ i, mk (f i)) :=
calc mk (⋃ i, f i) = mk (Σi, f i) : quot.sound ⟨set.Union_eq_sigma_of_disjoint h⟩
... = sum (λi, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {α ι : Type u} (f : ι → set α) :
mk (⋃ i, f i) ≤ mk ι * cardinal.sup.{u u} (λ i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {α : Type u} (A : set (set α)) :
mk (⋃₀ A) ≤ mk A * cardinal.sup.{u u} (λ s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ι α : Type u} (A : ι → set α) (s : set ι) :
mk (⋃(x ∈ s), A x) ≤ mk s * cardinal.sup.{u u} (λ x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {α : Type u} {s : finset α} : ↑(finset.card s) = mk (↑s : set α) :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset α) : mk (↑s : set α) < omega :=
by { rw [lt_omega_iff_fintype], exact ⟨finset.subtype.fintype s⟩ }
theorem mk_union_add_mk_inter {α : Type u} {S T : set α} : mk (S ∪ T : set α) + mk (S ∩ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union_sum_inter S T⟩
theorem mk_union_of_disjoint {α : Type u} {S T : set α} (H : disjoint S T) : mk (S ∪ T : set α) = mk S + mk T :=
quot.sound ⟨equiv.set.union (disjoint_iff.1 H)⟩
lemma mk_le_mk_of_subset {α} {s t : set α} (h : s ⊆ t) : mk s ≤ mk t :=
⟨ set.embedding_of_subset h ⟩
lemma mk_subtype_mono {p q : α → Prop} (h : ∀x, p x → q x) : mk {x // p x} ≤ mk {x // q x} :=
⟨embedding_of_subset h⟩
lemma mk_set_le (s : set α) : mk s ≤ mk α :=
⟨⟨subtype.val, subtype.val_injective⟩⟩
lemma mk_image_eq_lift {α : Type u} {β : Type v} (f : α → β) (s : set α) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image f s h).symm⟩
lemma mk_image_eq_of_inj_on_lift {α : Type u} {β : Type v} (f : α → β) (s : set α)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_image_eq_of_inj_on {α β : Type u} (f : α → β) (s : set α) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound ⟨(equiv.set.image_of_inj_on f s h).symm⟩
lemma mk_subtype_of_equiv {α β : Type u} (p : α → Prop) (e : α ≃ β) :
mk {a : α // p a} = mk {b : β // p (e.symm b)} :=
quotient.sound ⟨equiv.subtype_equiv_of_subtype' e⟩
lemma mk_sep (s : set α) (t : α → Prop) : mk ({ x ∈ s | t x } : set α) = mk { x : s | t x.1 } :=
quotient.sound ⟨equiv.set.sep s t⟩
lemma mk_preimage_of_injective_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : injective f) : lift.{u v} (mk (f ⁻¹' s)) ≤ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (λ x, f x.1) (λ x, x.2),
apply subtype.coind_injective, exact injective_comp h subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {α : Type u} {β : Type v} (f : α → β) (s : set β)
(h : s ⊆ range f) : lift.{v u} (mk s) ≤ lift.{u v} (mk (f ⁻¹' s)) :=
begin
rw lift_mk_le.{v u 0},
refine ⟨⟨_, _⟩⟩,
{ rintro ⟨y, hy⟩, rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩, exact ⟨x, hy⟩ },
rintro ⟨y, hy⟩ ⟨y', hy'⟩, dsimp,
rcases classical.subtype_of_exists (h hy) with ⟨x, rfl⟩,
rcases classical.subtype_of_exists (h hy') with ⟨x', rfl⟩,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {β : Type v} (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : lift.{u v} (mk (f ⁻¹' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : α → β) (s : set β) (h : injective f) :
mk (f ⁻¹' s) ≤ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : α → β) (s : set β)
(h : s ⊆ range f) : mk s ≤ mk (f ⁻¹' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : α → β) (s : set β)
(h : injective f) (h2 : s ⊆ range f) : mk (f ⁻¹' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {α : Type u} {β : Type v} (f : α → β) {s : set α}
{t : set β} (h : t ⊆ f '' s) :
lift.{v u} (mk t) ≤ lift.{u v} (mk ({ x ∈ s | f x ∈ t } : set α)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : α → β) {s : set α} {t : set β} (h : t ⊆ f '' s) :
mk t ≤ mk ({ x ∈ s | f x ∈ t } : set α) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {α : Type u} {s : set α} :
c ≤ mk s ↔ ∃ p : set α, p ⊆ s ∧ mk p = c :=
begin
rw [le_mk_iff_exists_set, ←subtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function α^{<β}, defined to be sup_{γ < β} α^γ.
We index over {s : set β.out // mk s < β } instead of {γ // γ < β}, because the latter lives in a
higher universe -/
noncomputable def powerlt (α β : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (λ(s : {s : set β.out // mk s < β}), α ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
∃(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk ↥(range ⇑f) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact ⟨⟨range f, by convert h⟩, this⟩
end
lemma le_powerlt {c₁ c₂ c₃ : cardinal} (h : c₂ < c₃) : c₁ ^ c₂ ≤ c₁ ^< c₃ :=
by { rcases powerlt_aux h with ⟨s, rfl⟩, apply le_sup _ s }
lemma powerlt_le {c₁ c₂ c₃ : cardinal} : c₁ ^< c₂ ≤ c₃ ↔ ∀(c₄ < c₂), c₁ ^ c₄ ≤ c₃ :=
begin
rw [powerlt, sup_le],
split,
{ intros h c₄ hc₄, rcases powerlt_aux hc₄ with ⟨s, rfl⟩, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b ≤ c) : a ^< b ≤ a ^< c :=
by { rw [powerlt, sup_le], rintro ⟨s, hs⟩, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {c₁ c₂ : cardinal} (h : c₁ ≠ 0) : c₁ ^< c₂.succ = c₁ ^ c₂ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros c₃ h2, apply power_le_power_left h, rwa [←lt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {c₁ c₂ c₃ : cardinal} : c₁ ^< max c₂ c₃ = max (c₁ ^< c₂) (c₁ ^< c₃) :=
by { cases le_total c₂ c₃; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a ≠ 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
by { apply sup_eq_zero, rintro ⟨x, hx⟩, rw [←not_le] at hx, apply hx, apply zero_le }
end cardinal
|
1408fa14e8a13d41e1c12d15e314297181e28ca9 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebraic_topology/dold_kan/homotopy_equivalence.lean | 8db3a58d5be9b44699d607aa44ed522e52194a29 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,808 | lean | /-
Copyright (c) 2022 Joël Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joël Riou
-/
import algebraic_topology.dold_kan.normalized
/-!
# The normalized Moore complex and the alternating face map complex are homotopy equivalent
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, when the category `A` is abelian, we obtain the homotopy equivalence
`homotopy_equiv_normalized_Moore_complex_alternating_face_map_complex` between the
normalized Moore complex and the alternating face map complex of a simplicial object in `A`.
-/
open category_theory category_theory.category category_theory.limits
category_theory.preadditive
open_locale simplicial dold_kan
noncomputable theory
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C] (X : simplicial_object C)
/-- Inductive construction of homotopies from `P q` to `𝟙 _` -/
noncomputable def homotopy_P_to_id : Π (q : ℕ),
homotopy (P q : K[X] ⟶ _) (𝟙 _)
| 0 := homotopy.refl _
| (q+1) := begin
refine homotopy.trans (homotopy.of_eq _)
(homotopy.trans
(homotopy.add (homotopy_P_to_id q) (homotopy.comp_left (homotopy_Hσ_to_zero q) (P q)))
(homotopy.of_eq _)),
{ unfold P, simp only [comp_add, comp_id], },
{ simp only [add_zero, comp_zero], },
end
/-- The complement projection `Q q` to `P q` is homotopic to zero. -/
def homotopy_Q_to_zero (q : ℕ) : homotopy (Q q : K[X] ⟶ _) 0 :=
homotopy.equiv_sub_zero.to_fun (homotopy_P_to_id X q).symm
lemma homotopy_P_to_id_eventually_constant {q n : ℕ} (hqn : n<q):
((homotopy_P_to_id X (q+1)).hom n (n+1) : X _[n] ⟶ X _[n+1]) =
(homotopy_P_to_id X q).hom n (n+1) :=
begin
unfold homotopy_P_to_id,
simp only [homotopy_Hσ_to_zero, hσ'_eq_zero hqn (c_mk (n+1) n rfl), homotopy.trans_hom,
pi.add_apply, homotopy.of_eq_hom, pi.zero_apply, homotopy.add_hom, homotopy.comp_left_hom,
homotopy.null_homotopy'_hom, complex_shape.down_rel, eq_self_iff_true, dite_eq_ite,
if_true, comp_zero, add_zero, zero_add],
end
variable (X)
/-- Construction of the homotopy from `P_infty` to the identity using eventually
(termwise) constant homotopies from `P q` to the identity for all `q` -/
@[simps]
def homotopy_P_infty_to_id :
homotopy (P_infty : K[X] ⟶ _) (𝟙 _) :=
{ hom := λ i j, (homotopy_P_to_id X (j+1)).hom i j,
zero' := λ i j hij, homotopy.zero _ i j hij,
comm := λ n, begin
cases n,
{ simpa only [homotopy.d_next_zero_chain_complex, homotopy.prev_d_chain_complex, P_f_0_eq,
zero_add, homological_complex.id_f, P_infty_f] using (homotopy_P_to_id X 2).comm 0, },
{ simpa only [homotopy.d_next_succ_chain_complex, homotopy.prev_d_chain_complex,
homological_complex.id_f, P_infty_f, ← P_is_eventually_constant (rfl.le : n+1 ≤ n+1),
homotopy_P_to_id_eventually_constant X (lt_add_one (n+1))]
using (homotopy_P_to_id X (n+2)).comm (n+1), },
end }
/-- The inclusion of the Moore complex in the alternating face map complex
is an homotopy equivalence -/
@[simps]
def homotopy_equiv_normalized_Moore_complex_alternating_face_map_complex {A : Type*}
[category A] [abelian A] {Y : simplicial_object A} :
homotopy_equiv ((normalized_Moore_complex A).obj Y) ((alternating_face_map_complex A).obj Y) :=
{ hom := inclusion_of_Moore_complex_map Y,
inv := P_infty_to_normalized_Moore_complex Y,
homotopy_hom_inv_id := homotopy.of_eq (split_mono_inclusion_of_Moore_complex_map Y).id,
homotopy_inv_hom_id := homotopy.trans
(homotopy.of_eq (P_infty_to_normalized_Moore_complex_comp_inclusion_of_Moore_complex_map Y))
(homotopy_P_infty_to_id Y), }
end dold_kan
end algebraic_topology
|
92dc6365f6505c1f7f8d0e03a9eca3eb052afb4b | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/geometry/euclidean/monge_point.lean | 9bffce455ca4bfdb07f0eda371bc36e0a335507c | [
"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 | 38,624 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import geometry.euclidean.circumcenter
/-!
# Monge point and orthocenter
This file defines the orthocenter of a triangle, via its n-dimensional
generalization, the Monge point of a simplex.
## Main definitions
* `monge_point` is the Monge point of a simplex, defined in terms of
its position on the Euler line and then shown to be the point of
concurrence of the Monge planes.
* `monge_plane` is a Monge plane of an (n+2)-simplex, which is the
(n+1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an n-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude).
* `altitude` is the line that passes through a vertex of a simplex and
is orthogonal to the opposite face.
* `orthocenter` is defined, for the case of a triangle, to be the same
as its Monge point, then shown to be the point of concurrence of the
altitudes.
* `orthocentric_system` is a predicate on sets of points that says
whether they are four points, one of which is the orthocenter of the
other three (in which case various other properties hold, including
that each is the orthocenter of the other three).
## References
* <https://en.wikipedia.org/wiki/Altitude_(triangle)>
* <https://en.wikipedia.org/wiki/Monge_point>
* <https://en.wikipedia.org/wiki/Orthocentric_system>
* Małgorzata Buba-Brzozowa, [The Monge Point and the 3(n+1) Point
Sphere of an
n-Simplex](https://pdfs.semanticscholar.org/6f8b/0f623459c76dac2e49255737f8f0f4725d16.pdf)
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace affine
namespace simplex
open finset affine_subspace euclidean_geometry points_with_circumcenter_index
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The Monge point of a simplex (in 2 or more dimensions) is a
generalization of the orthocenter of a triangle. It is defined to be
the intersection of the Monge planes, where a Monge plane is the
(n-1)-dimensional affine subspace of the subspace spanned by the
simplex that passes through the centroid of an (n-2)-dimensional face
and is orthogonal to the opposite edge (in 2 dimensions, this is the
same as an altitude). The circumcenter O, centroid G and Monge point
M are collinear in that order on the Euler line, with OG : GM = (n-1)
: 2. Here, we use that ratio to define the Monge point (so resulting
in a point that equals the centroid in 0 or 1 dimensions), and then
show in subsequent lemmas that the point so defined lies in the Monge
planes and is their unique point of intersection. -/
def monge_point {n : ℕ} (s : simplex ℝ P n) : P :=
(((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter
/-- The position of the Monge point in relation to the circumcenter
and centroid. -/
lemma monge_point_eq_smul_vsub_vadd_circumcenter {n : ℕ} (s : simplex ℝ P n) :
s.monge_point = (((n + 1 : ℕ) : ℝ) / (((n - 1) : ℕ) : ℝ)) •
((univ : finset (fin (n + 1))).centroid ℝ s.points -ᵥ s.circumcenter) +ᵥ
s.circumcenter :=
rfl
/-- The Monge point lies in the affine span. -/
lemma monge_point_mem_affine_span {n : ℕ} (s : simplex ℝ P n) :
s.monge_point ∈ affine_span ℝ (set.range s.points) :=
smul_vsub_vadd_mem _ _
(centroid_mem_affine_span_of_card_eq_add_one ℝ _ (card_fin (n + 1)))
s.circumcenter_mem_affine_span
s.circumcenter_mem_affine_span
/-- Two simplices with the same points have the same Monge point. -/
lemma monge_point_eq_of_range_eq {n : ℕ} {s₁ s₂ : simplex ℝ P n}
(h : set.range s₁.points = set.range s₂.points) : s₁.monge_point = s₂.monge_point :=
by simp_rw [monge_point_eq_smul_vsub_vadd_circumcenter, centroid_eq_of_range_eq h,
circumcenter_eq_of_range_eq h]
omit V
/-- The weights for the Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
def monge_point_weights_with_circumcenter (n : ℕ) : points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := (((n + 1) : ℕ) : ℝ)⁻¹
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_weights_with_circumcenter` sums to 1. -/
@[simp] lemma sum_monge_point_weights_with_circumcenter (n : ℕ) :
∑ i, monge_point_weights_with_circumcenter n i = 1 :=
begin
simp_rw [sum_points_with_circumcenter, monge_point_weights_with_circumcenter, sum_const,
card_fin, nsmul_eq_mul],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1],
ring
end
include V
/-- The Monge point of an (n+2)-simplex, in terms of
`points_with_circumcenter`. -/
lemma monge_point_eq_affine_combination_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) :
s.monge_point = (univ : finset (points_with_circumcenter_index (n + 2))).affine_combination
s.points_with_circumcenter (monge_point_weights_with_circumcenter n) :=
begin
rw [monge_point_eq_smul_vsub_vadd_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
circumcenter_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub, ←linear_map.map_smul,
weighted_vsub_vadd_affine_combination],
congr' with i,
rw [pi.add_apply, pi.smul_apply, smul_eq_mul, pi.sub_apply],
have hn1 : (n + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
cases i;
simp_rw [centroid_weights_with_circumcenter, circumcenter_weights_with_circumcenter,
monge_point_weights_with_circumcenter];
rw [nat.add_sub_assoc (dec_trivial : 1 ≤ 2), (dec_trivial : 2 - 1 = 1)],
{ rw [if_pos (mem_univ _), sub_zero, add_zero, card_fin],
have hn3 : (n + 2 + 1 : ℝ) ≠ 0,
{ exact_mod_cast nat.succ_ne_zero _ },
field_simp [hn1, hn3, mul_comm] },
{ field_simp [hn1],
ring }
end
omit V
/-- The weights for the Monge point of an (n+2)-simplex, minus the
centroid of an n-dimensional face, in terms of
`points_with_circumcenter`. This definition is only valid when `i₁ ≠ i₂`. -/
def monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ} (i₁ i₂ : fin (n + 3)) :
points_with_circumcenter_index (n + 2) → ℝ
| (point_index i) := if i = i₁ ∨ i = i₂ then (((n + 1) : ℕ) : ℝ)⁻¹ else 0
| circumcenter_index := (-2 / (((n + 1) : ℕ) : ℝ))
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` is the
result of subtracting `centroid_weights_with_circumcenter` from
`monge_point_weights_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ =
monge_point_weights_with_circumcenter n -
centroid_weights_with_circumcenter ({i₁, i₂}ᶜ) :=
begin
ext i,
cases i,
{ rw [pi.sub_apply, monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter],
have hu : card ({i₁, i₂}ᶜ : finset (fin (n + 3))) = n + 1,
{ simp [card_compl, fintype.card_fin, h] },
rw hu,
by_cases hi : i = i₁ ∨ i = i₂;
simp [compl_eq_univ_sdiff, hi] },
{ simp [monge_point_weights_with_circumcenter, centroid_weights_with_circumcenter,
monge_point_vsub_face_centroid_weights_with_circumcenter] }
end
/-- `monge_point_vsub_face_centroid_weights_with_circumcenter` sums to 0. -/
@[simp] lemma sum_monge_point_vsub_face_centroid_weights_with_circumcenter {n : ℕ}
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
∑ i, monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂ i = 0 :=
begin
rw monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h,
simp_rw [pi.sub_apply, sum_sub_distrib, sum_monge_point_weights_with_circumcenter],
rw [sum_centroid_weights_with_circumcenter, sub_self],
simp [←card_pos, card_compl, h]
end
include V
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, in terms of `points_with_circumcenter`. -/
lemma monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter {n : ℕ}
(s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points =
(univ : finset (points_with_circumcenter_index (n + 2))).weighted_vsub
s.points_with_circumcenter (monge_point_vsub_face_centroid_weights_with_circumcenter i₁ i₂) :=
by simp_rw [monge_point_eq_affine_combination_of_points_with_circumcenter,
centroid_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub,
monge_point_vsub_face_centroid_weights_with_circumcenter_eq_sub h]
/-- The Monge point of an (n+2)-simplex, minus the centroid of an
n-dimensional face, is orthogonal to the difference of the two
vertices not in that face. -/
lemma inner_monge_point_vsub_face_centroid_vsub {n : ℕ} (s : simplex ℝ P (n + 2))
{i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
⟪s.monge_point -ᵥ ({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points,
s.points i₁ -ᵥ s.points i₂⟫ = 0 :=
begin
simp_rw [monge_point_vsub_face_centroid_eq_weighted_vsub_of_points_with_circumcenter s h,
point_eq_affine_combination_of_points_with_circumcenter,
affine_combination_vsub],
have hs : ∑ i, (point_weights_with_circumcenter i₁ - point_weights_with_circumcenter i₂) i = 0,
{ simp },
rw [inner_weighted_vsub _ (sum_monge_point_vsub_face_centroid_weights_with_circumcenter h) _ hs,
sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter],
simp only [monge_point_vsub_face_centroid_weights_with_circumcenter,
points_with_circumcenter_point],
let fs : finset (fin (n + 3)) := {i₁, i₂},
have hfs : ∀ i : fin (n + 3),
i ∉ fs → (i ≠ i₁ ∧ i ≠ i₂),
{ intros i hi,
split ; { intro hj, simpa [←hj] using hi } },
rw ←sum_subset fs.subset_univ _,
{ simp_rw [sum_points_with_circumcenter, points_with_circumcenter_eq_circumcenter,
points_with_circumcenter_point, pi.sub_apply, point_weights_with_circumcenter],
rw [←sum_subset fs.subset_univ _],
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
repeat { rw ←sum_subset fs.subset_univ _ },
{ simp_rw [sum_insert (not_mem_singleton.2 h), sum_singleton],
simp [h, h.symm, dist_comm (s.points i₁)] },
all_goals { intros i hu hi, simp [hfs i hi] } },
{ intros i hu hi,
simp [hfs i hi, point_weights_with_circumcenter] } },
{ intros i hu hi,
simp [hfs i hi] }
end
/-- A Monge plane of an (n+2)-simplex is the (n+1)-dimensional affine
subspace of the subspace spanned by the simplex that passes through
the centroid of an n-dimensional face and is orthogonal to the
opposite edge (in 2 dimensions, this is the same as an altitude).
This definition is only intended to be used when `i₁ ≠ i₂`. -/
def monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
affine_subspace ℝ P :=
mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of a Monge plane. -/
lemma monge_plane_def {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = mk' (({i₁, i₂}ᶜ : finset (fin (n + 3))).centroid ℝ s.points)
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- The Monge plane associated with vertices `i₁` and `i₂` equals that
associated with `i₂` and `i₁`. -/
lemma monge_plane_comm {n : ℕ} (s : simplex ℝ P (n + 2)) (i₁ i₂ : fin (n + 3)) :
s.monge_plane i₁ i₂ = s.monge_plane i₂ i₁ :=
begin
simp_rw monge_plane_def,
congr' 3,
{ congr' 1,
exact insert_singleton_comm _ _ },
{ ext,
simp_rw submodule.mem_span_singleton,
split,
all_goals { rintros ⟨r, rfl⟩, use -r, rw [neg_smul, ←smul_neg, neg_vsub_eq_vsub_rev] } }
end
/-- The Monge point lies in the Monge planes. -/
lemma monge_point_mem_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)}
(h : i₁ ≠ i₂) : s.monge_point ∈ s.monge_plane i₁ i₂ :=
begin
rw [monge_plane_def, mem_inf_iff, ←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _),
direction_mk', submodule.mem_orthogonal'],
refine ⟨_, s.monge_point_mem_affine_span⟩,
intros v hv,
rcases submodule.mem_span_singleton.mp hv with ⟨r, rfl⟩,
rw [inner_smul_right, s.inner_monge_point_vsub_face_centroid_vsub h, mul_zero]
end
-- This doesn't actually need the `i₁ ≠ i₂` hypothesis, but it's
-- convenient for the proof and `monge_plane` isn't intended to be
-- useful without that hypothesis.
/-- The direction of a Monge plane. -/
lemma direction_monge_plane {n : ℕ} (s : simplex ℝ P (n + 2)) {i₁ i₂ : fin (n + 3)} (h : i₁ ≠ i₂) :
(s.monge_plane i₁ i₂).direction = (ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [monge_plane_def, direction_inf_of_mem_inf (s.monge_point_mem_monge_plane h), direction_mk',
direction_affine_span]
/-- The Monge point is the only point in all the Monge planes from any
one vertex. -/
lemma eq_monge_point_of_forall_mem_monge_plane {n : ℕ} {s : simplex ℝ P (n + 2)}
{i₁ : fin (n + 3)} {p : P} (h : ∀ i₂, i₁ ≠ i₂ → p ∈ s.monge_plane i₁ i₂) :
p = s.monge_point :=
begin
rw ←@vsub_eq_zero_iff_eq V,
have h' : ∀ i₂, i₁ ≠ i₂ → p -ᵥ s.monge_point ∈
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ ⊓ vector_span ℝ (set.range s.points),
{ intros i₂ hne,
rw [←s.direction_monge_plane hne,
vsub_right_mem_direction_iff_mem (s.monge_point_mem_monge_plane hne)],
exact h i₂ hne },
have hi : p -ᵥ s.monge_point ∈ ⨅ (i₂ : {i // i₁ ≠ i}),
(ℝ ∙ (s.points i₁ -ᵥ s.points i₂))ᗮ,
{ rw submodule.mem_infi,
exact λ i, (submodule.mem_inf.1 (h' i i.property)).1 },
rw [submodule.infi_orthogonal, ←submodule.span_Union] at hi,
have hu : (⋃ (i : {i // i₁ ≠ i}), ({s.points i₁ -ᵥ s.points i} : set V)) =
(-ᵥ) (s.points i₁) '' (s.points '' (set.univ \ {i₁})),
{ rw [set.image_image],
ext x,
simp_rw [set.mem_Union, set.mem_image, set.mem_singleton_iff, set.mem_diff_singleton],
split,
{ rintros ⟨i, rfl⟩,
use [i, ⟨set.mem_univ _, i.property.symm⟩] },
{ rintros ⟨i, ⟨hiu, hi⟩, rfl⟩,
use [⟨i, hi.symm⟩, rfl] } },
rw [hu, ←vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_univ _),
set.image_univ] at hi,
have hv : p -ᵥ s.monge_point ∈ vector_span ℝ (set.range s.points),
{ let s₁ : finset (fin (n + 3)) := univ.erase i₁,
obtain ⟨i₂, h₂⟩ :=
card_pos.1 (show 0 < card s₁, by simp [card_erase_of_mem]),
have h₁₂ : i₁ ≠ i₂ := (ne_of_mem_erase h₂).symm,
exact (submodule.mem_inf.1 (h' i₂ h₁₂)).2 },
exact submodule.disjoint_def.1 ((vector_span ℝ (set.range s.points)).orthogonal_disjoint)
_ hv hi,
end
/-- An altitude of a simplex is the line that passes through a vertex
and is orthogonal to the opposite face. -/
def altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) : affine_subspace ℝ P :=
mk' (s.points i) (affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points)
/-- The definition of an altitude. -/
lemma altitude_def {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.altitude i = mk' (s.points i)
(affine_span ℝ (s.points '' ↑(univ.erase i))).directionᗮ ⊓
affine_span ℝ (set.range s.points) :=
rfl
/-- A vertex lies in the corresponding altitude. -/
lemma mem_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
s.points i ∈ s.altitude i :=
(mem_inf_iff _ _ _).2 ⟨self_mem_mk' _ _, mem_affine_span ℝ (set.mem_range_self _)⟩
/-- The direction of an altitude. -/
lemma direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
(s.altitude i).direction = (vector_span ℝ (s.points '' ↑(finset.univ.erase i)))ᗮ ⊓
vector_span ℝ (set.range s.points) :=
by rw [altitude_def,
direction_inf_of_mem (self_mem_mk' (s.points i) _)
(mem_affine_span ℝ (set.mem_range_self _)), direction_mk', direction_affine_span,
direction_affine_span]
/-- The vector span of the opposite face lies in the direction
orthogonal to an altitude. -/
lemma vector_span_le_altitude_direction_orthogonal {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) :
vector_span ℝ (s.points '' ↑(finset.univ.erase i)) ≤ (s.altitude i).directionᗮ :=
begin
rw direction_altitude,
exact le_trans
(vector_span ℝ (s.points '' ↑(finset.univ.erase i))).le_orthogonal_orthogonal
(submodule.orthogonal_le inf_le_left)
end
open finite_dimensional
/-- An altitude is finite-dimensional. -/
instance finite_dimensional_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) : finite_dimensional ℝ ((s.altitude i).direction) :=
begin
rw direction_altitude,
apply_instance
end
/-- An altitude is one-dimensional (i.e., a line). -/
@[simp] lemma finrank_direction_altitude {n : ℕ} (s : simplex ℝ P (n + 1)) (i : fin (n + 2)) :
finrank ℝ ((s.altitude i).direction) = 1 :=
begin
rw direction_altitude,
have h := submodule.finrank_add_inf_finrank_orthogonal
(vector_span_mono ℝ (set.image_subset_range s.points ↑(univ.erase i))),
have hc : card (univ.erase i) = n + 1, { rw card_erase_of_mem (mem_univ _), simp },
refine add_left_cancel (trans h _),
rw [finrank_vector_span_of_affine_independent s.independent (fintype.card_fin _),
← finset.coe_image, finrank_vector_span_image_finset_of_affine_independent s.independent hc]
end
/-- A line through a vertex is the altitude through that vertex if and
only if it is orthogonal to the opposite face. -/
lemma affine_span_insert_singleton_eq_altitude_iff {n : ℕ} (s : simplex ℝ P (n + 1))
(i : fin (n + 2)) (p : P) :
affine_span ℝ {p, s.points i} = s.altitude i ↔ (p ≠ s.points i ∧
p ∈ affine_span ℝ (set.range s.points) ∧
p -ᵥ s.points i ∈ (affine_span ℝ (s.points '' ↑(finset.univ.erase i))).directionᗮ) :=
begin
rw [eq_iff_direction_eq_of_mem
(mem_affine_span ℝ (set.mem_insert_of_mem _ (set.mem_singleton _))) (s.mem_altitude _),
←vsub_right_mem_direction_iff_mem (mem_affine_span ℝ (set.mem_range_self i)) p,
direction_affine_span, direction_affine_span, direction_affine_span],
split,
{ intro h,
split,
{ intro heq,
rw [heq, set.pair_eq_singleton, vector_span_singleton] at h,
have hd : finrank ℝ (s.altitude i).direction = 0,
{ rw [←h, finrank_bot] },
simpa using hd },
{ rw [←submodule.mem_inf, inf_comm, ←direction_altitude, ←h],
exact vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _)) } },
{ rintro ⟨hne, h⟩,
rw [←submodule.mem_inf, inf_comm, ←direction_altitude] at h,
rw [vector_span_eq_span_vsub_set_left_ne ℝ (set.mem_insert _ _),
set.insert_diff_of_mem _ (set.mem_singleton _),
set.diff_singleton_eq_self (λ h, hne (set.mem_singleton_iff.1 h)), set.image_singleton],
refine eq_of_le_of_finrank_eq _ _,
{ rw submodule.span_le,
simpa using h },
{ rw [finrank_direction_altitude, finrank_span_set_eq_card],
{ simp },
{ refine linear_independent_singleton _,
simpa using hne } } }
end
end simplex
namespace triangle
open euclidean_geometry finset simplex affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- The orthocenter of a triangle is the intersection of its
altitudes. It is defined here as the 2-dimensional case of the
Monge point. -/
def orthocenter (t : triangle ℝ P) : P := t.monge_point
/-- The orthocenter equals the Monge point. -/
lemma orthocenter_eq_monge_point (t : triangle ℝ P) : t.orthocenter = t.monge_point := rfl
/-- The position of the orthocenter in relation to the circumcenter
and centroid. -/
lemma orthocenter_eq_smul_vsub_vadd_circumcenter (t : triangle ℝ P) :
t.orthocenter = (3 : ℝ) •
((univ : finset (fin 3)).centroid ℝ t.points -ᵥ t.circumcenter : V) +ᵥ t.circumcenter :=
begin
rw [orthocenter_eq_monge_point, monge_point_eq_smul_vsub_vadd_circumcenter],
norm_num
end
/-- The orthocenter lies in the affine span. -/
lemma orthocenter_mem_affine_span (t : triangle ℝ P) :
t.orthocenter ∈ affine_span ℝ (set.range t.points) :=
t.monge_point_mem_affine_span
/-- Two triangles with the same points have the same orthocenter. -/
lemma orthocenter_eq_of_range_eq {t₁ t₂ : triangle ℝ P}
(h : set.range t₁.points = set.range t₂.points) : t₁.orthocenter = t₂.orthocenter :=
monge_point_eq_of_range_eq h
/-- In the case of a triangle, altitudes are the same thing as Monge
planes. -/
lemma altitude_eq_monge_plane (t : triangle ℝ P) {i₁ i₂ i₃ : fin 3} (h₁₂ : i₁ ≠ i₂)
(h₁₃ : i₁ ≠ i₃) (h₂₃ : i₂ ≠ i₃) : t.altitude i₁ = t.monge_plane i₂ i₃ :=
begin
have hs : ({i₂, i₃}ᶜ : finset (fin 3)) = {i₁}, by dec_trivial!,
have he : univ.erase i₁ = {i₂, i₃}, by dec_trivial!,
rw [monge_plane_def, altitude_def, direction_affine_span, hs, he, centroid_singleton,
coe_insert, coe_singleton,
vector_span_image_eq_span_vsub_set_left_ne ℝ _ (set.mem_insert i₂ _)],
simp [h₂₃, submodule.span_insert_eq_span]
end
/-- The orthocenter lies in the altitudes. -/
lemma orthocenter_mem_altitude (t : triangle ℝ P) {i₁ : fin 3} :
t.orthocenter ∈ t.altitude i₁ :=
begin
obtain ⟨i₂, i₃, h₁₂, h₂₃, h₁₃⟩ : ∃ i₂ i₃, i₁ ≠ i₂ ∧ i₂ ≠ i₃ ∧ i₁ ≠ i₃, by dec_trivial!,
rw [orthocenter_eq_monge_point, t.altitude_eq_monge_plane h₁₂ h₁₃ h₂₃],
exact t.monge_point_mem_monge_plane h₂₃
end
/-- The orthocenter is the only point lying in any two of the
altitudes. -/
lemma eq_orthocenter_of_forall_mem_altitude {t : triangle ℝ P} {i₁ i₂ : fin 3} {p : P}
(h₁₂ : i₁ ≠ i₂) (h₁ : p ∈ t.altitude i₁) (h₂ : p ∈ t.altitude i₂) : p = t.orthocenter :=
begin
obtain ⟨i₃, h₂₃, h₁₃⟩ : ∃ i₃, i₂ ≠ i₃ ∧ i₁ ≠ i₃, { clear h₁ h₂, dec_trivial! },
rw t.altitude_eq_monge_plane h₁₃ h₁₂ h₂₃.symm at h₁,
rw t.altitude_eq_monge_plane h₂₃ h₁₂.symm h₁₃.symm at h₂,
rw orthocenter_eq_monge_point,
have ha : ∀ i, i₃ ≠ i → p ∈ t.monge_plane i₃ i,
{ intros i hi,
have hi₁₂ : i₁ = i ∨ i₂ = i, { clear h₁ h₂, dec_trivial! },
cases hi₁₂,
{ exact hi₁₂ ▸ h₂ },
{ exact hi₁₂ ▸ h₁ } },
exact eq_monge_point_of_forall_mem_monge_plane ha
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius. -/
lemma dist_orthocenter_reflection_circumcenter (t : triangle ℝ P) {i₁ i₂ : fin 3} (h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' {i₁, i₂})) t.circumcenter) =
t.circumradius :=
begin
rw [←mul_self_inj_of_nonneg dist_nonneg t.circumradius_nonneg,
t.reflection_circumcenter_eq_affine_combination_of_points_with_circumcenter h,
t.orthocenter_eq_monge_point,
monge_point_eq_affine_combination_of_points_with_circumcenter,
dist_affine_combination t.points_with_circumcenter
(sum_monge_point_weights_with_circumcenter _)
(sum_reflection_circumcenter_weights_with_circumcenter h)],
simp_rw [sum_points_with_circumcenter, pi.sub_apply, monge_point_weights_with_circumcenter,
reflection_circumcenter_weights_with_circumcenter],
have hu : ({i₁, i₂} : finset (fin 3)) ⊆ univ := subset_univ _,
obtain ⟨i₃, hi₃, hi₃₁, hi₃₂⟩ :
∃ i₃, univ \ ({i₁, i₂} : finset (fin 3)) = {i₃} ∧ i₃ ≠ i₁ ∧ i₃ ≠ i₂, by dec_trivial!,
simp_rw [←sum_sdiff hu, hi₃],
simp [hi₃₁, hi₃₂],
norm_num
end
/-- The distance from the orthocenter to the reflection of the
circumcenter in a side equals the circumradius, variant using a
`finset`. -/
lemma dist_orthocenter_reflection_circumcenter_finset (t : triangle ℝ P) {i₁ i₂ : fin 3}
(h : i₁ ≠ i₂) :
dist t.orthocenter (reflection (affine_span ℝ (t.points '' ↑({i₁, i₂} : finset (fin 3))))
t.circumcenter) =
t.circumradius :=
by { convert dist_orthocenter_reflection_circumcenter _ h, simp }
/-- The affine span of the orthocenter and a vertex is contained in
the altitude. -/
lemma affine_span_orthocenter_point_le_altitude (t : triangle ℝ P) (i : fin 3) :
affine_span ℝ {t.orthocenter, t.points i} ≤ t.altitude i :=
begin
refine span_points_subset_coe_of_subset_coe _,
rw [set.insert_subset, set.singleton_subset_iff],
exact ⟨t.orthocenter_mem_altitude, t.mem_altitude i⟩
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then an altitude of `t₂` from
a vertex that was not replaced is the corresponding side of `t₁`. -/
lemma altitude_replace_orthocenter_eq_affine_span {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.altitude j₂ = affine_span ℝ {t₁.points i₁, t₁.points i₂} :=
begin
symmetry,
rw [←h₂, t₂.affine_span_insert_singleton_eq_altitude_iff],
rw [h₂],
use (injective_of_affine_independent t₁.independent).ne hi₁₂,
have he : affine_span ℝ (set.range t₂.points) = affine_span ℝ (set.range t₁.points),
{ refine ext_of_direction_eq _
⟨t₁.points i₃, mem_affine_span ℝ ⟨j₃, h₃⟩, mem_affine_span ℝ (set.mem_range_self _)⟩,
refine eq_of_le_of_finrank_eq (direction_le (span_points_subset_coe_of_subset_coe _)) _,
{ have hu : (finset.univ : finset (fin 3)) = {j₁, j₂, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [←set.image_univ, ←finset.coe_univ, hu, finset.coe_insert, finset.coe_insert,
finset.coe_singleton, set.image_insert_eq, set.image_insert_eq, set.image_singleton,
h₁, h₂, h₃, set.insert_subset, set.insert_subset, set.singleton_subset_iff],
exact ⟨t₁.orthocenter_mem_affine_span,
mem_affine_span ℝ (set.mem_range_self _),
mem_affine_span ℝ (set.mem_range_self _)⟩ },
{ rw [direction_affine_span, direction_affine_span,
finrank_vector_span_of_affine_independent t₁.independent (fintype.card_fin _),
finrank_vector_span_of_affine_independent t₂.independent (fintype.card_fin _)] } },
rw he,
use mem_affine_span ℝ (set.mem_range_self _),
have hu : finset.univ.erase j₂ = {j₁, j₃}, { clear h₁ h₂ h₃, dec_trivial! },
rw [hu, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton,
h₁, h₃],
have hle : (t₁.altitude i₃).directionᗮ ≤
(affine_span ℝ ({t₁.orthocenter, t₁.points i₃} : set P)).directionᗮ :=
submodule.orthogonal_le (direction_le (affine_span_orthocenter_point_le_altitude _ _)),
refine hle ((t₁.vector_span_le_altitude_direction_orthogonal i₃) _),
have hui : finset.univ.erase i₃ = {i₁, i₂}, { clear hle h₂ h₃, dec_trivial! },
rw [hui, finset.coe_insert, finset.coe_singleton, set.image_insert_eq, set.image_singleton],
refine vsub_mem_vector_span ℝ (set.mem_insert _ _)
(set.mem_insert_of_mem _ (set.mem_singleton _))
end
/-- Suppose we are given a triangle `t₁`, and replace one of its
vertices by its orthocenter, yielding triangle `t₂` (with vertices not
necessarily listed in the same order). Then the orthocenter of `t₂`
is the vertex of `t₁` that was replaced. -/
lemma orthocenter_replace_orthocenter_eq_point {t₁ t₂ : triangle ℝ P} {i₁ i₂ i₃ j₁ j₂ j₃ : fin 3}
(hi₁₂ : i₁ ≠ i₂) (hi₁₃ : i₁ ≠ i₃) (hi₂₃ : i₂ ≠ i₃) (hj₁₂ : j₁ ≠ j₂) (hj₁₃ : j₁ ≠ j₃)
(hj₂₃ : j₂ ≠ j₃) (h₁ : t₂.points j₁ = t₁.orthocenter) (h₂ : t₂.points j₂ = t₁.points i₂)
(h₃ : t₂.points j₃ = t₁.points i₃) :
t₂.orthocenter = t₁.points i₁ :=
begin
refine (triangle.eq_orthocenter_of_forall_mem_altitude hj₂₃ _ _).symm,
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₂ hi₁₃ hi₂₃ hj₁₂ hj₁₃ hj₂₃ h₁ h₂ h₃,
exact mem_affine_span ℝ (set.mem_insert _ _) },
{ rw altitude_replace_orthocenter_eq_affine_span hi₁₃ hi₁₂ hi₂₃.symm hj₁₃ hj₁₂ hj₂₃.symm h₁ h₃ h₂,
exact mem_affine_span ℝ (set.mem_insert _ _) }
end
end triangle
end affine
namespace euclidean_geometry
open affine affine_subspace finite_dimensional
variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P]
[normed_add_torsor V P]
include V
/-- Four points form an orthocentric system if they consist of the
vertices of a triangle and its orthocenter. -/
def orthocentric_system (s : set P) : Prop :=
∃ t : triangle ℝ P,
t.orthocenter ∉ set.range t.points ∧ s = insert t.orthocenter (set.range t.points)
/-- This is an auxiliary lemma giving information about the relation
of two triangles in an orthocentric system; it abstracts some
reasoning, with no geometric content, that is common to some other
lemmas. Suppose the orthocentric system is generated by triangle `t`,
and we are given three points `p` in the orthocentric system. Then
either we can find indices `i₁`, `i₂` and `i₃` for `p` such that `p
i₁` is the orthocenter of `t` and `p i₂` and `p i₃` are points `j₂`
and `j₃` of `t`, or `p` has the same points as `t`. -/
lemma exists_of_range_subset_orthocentric_system {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
(∃ (i₁ i₂ i₃ j₂ j₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧
(∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃) ∧ p i₁ = t.orthocenter ∧ j₂ ≠ j₃ ∧
t.points j₂ = p i₂ ∧ t.points j₃ = p i₃) ∨ set.range p = set.range t.points :=
begin
by_cases h : t.orthocenter ∈ set.range p,
{ left,
rcases h with ⟨i₁, h₁⟩,
obtain ⟨i₂, i₃, h₁₂, h₁₃, h₂₃, h₁₂₃⟩ :
∃ (i₂ i₃ : fin 3), i₁ ≠ i₂ ∧ i₁ ≠ i₃ ∧ i₂ ≠ i₃ ∧ ∀ i : fin 3, i = i₁ ∨ i = i₂ ∨ i = i₃,
{ clear h₁, dec_trivial! },
have h : ∀ i, i₁ ≠ i → ∃ (j : fin 3), t.points j = p i,
{ intros i hi,
replace hps := set.mem_of_mem_insert_of_ne
(set.mem_of_mem_of_subset (set.mem_range_self i) hps) (h₁ ▸ hpi.ne hi.symm),
exact hps },
rcases h i₂ h₁₂ with ⟨j₂, h₂⟩,
rcases h i₃ h₁₃ with ⟨j₃, h₃⟩,
have hj₂₃ : j₂ ≠ j₃,
{ intro he,
rw [he, h₃] at h₂,
exact h₂₃.symm (hpi h₂) },
exact ⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ },
{ right,
have hs := set.subset_diff_singleton hps h,
rw set.insert_diff_self_of_not_mem ho at hs,
refine set.eq_of_subset_of_card_le hs _,
rw [set.card_range_of_injective hpi,
set.card_range_of_injective (injective_of_affine_independent t.independent)] }
end
/-- For any three points in an orthocentric system generated by
triangle `t`, there is a point in the subspace spanned by the triangle
from which the distance of all those three points equals the circumradius. -/
lemma exists_dist_eq_circumradius_of_subset_insert_orthocenter {t : triangle ℝ P}
(ho : t.orthocenter ∉ set.range t.points) {p : fin 3 → P}
(hps : set.range p ⊆ insert t.orthocenter (set.range t.points)) (hpi : function.injective p) :
∃ c ∈ affine_span ℝ (set.range t.points), ∀ p₁ ∈ set.range p, dist p₁ c = t.circumradius :=
begin
rcases exists_of_range_subset_orthocentric_system ho hps hpi with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ use [reflection (affine_span ℝ (t.points '' {j₂, j₃})) t.circumcenter,
reflection_mem_of_le_of_mem (affine_span_mono ℝ (set.image_subset_range _ _))
t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rcases hp₁ with ⟨i, rfl⟩,
replace h₁₂₃ := h₁₂₃ i,
repeat { cases h₁₂₃ },
{ rw h₁,
exact triangle.dist_orthocenter_reflection_circumcenter t hj₂₃ },
{ rw [←h₂,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _ (set.mem_insert _ _)))],
exact t.dist_circumcenter_eq_circumradius _ },
{ rw [←h₃,
dist_reflection_eq_of_mem _
(mem_affine_span ℝ (set.mem_image_of_mem _
(set.mem_insert_of_mem _ (set.mem_singleton _))))],
exact t.dist_circumcenter_eq_circumradius _ } },
{ use [t.circumcenter, t.circumcenter_mem_affine_span],
intros p₁ hp₁,
rw hs at hp₁,
rcases hp₁ with ⟨i, rfl⟩,
exact t.dist_circumcenter_eq_circumradius _ }
end
/-- Any three points in an orthocentric system are affinely independent. -/
lemma orthocentric_system.affine_independent {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_independent ℝ p :=
begin
rcases ho with ⟨t, hto, hst⟩,
rw hst at hps,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto hps hpi with ⟨c, hcs, hc⟩,
exact cospherical.affine_independent ⟨c, t.circumradius, hc⟩ set.subset.rfl hpi
end
/-- Any three points in an orthocentric system span the same subspace
as the whole orthocentric system. -/
lemma affine_span_of_orthocentric_system {s : set P} (ho : orthocentric_system s)
{p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) :
affine_span ℝ (set.range p) = affine_span ℝ s :=
begin
have ha := ho.affine_independent hps hpi,
rcases ho with ⟨t, hto, hts⟩,
have hs : affine_span ℝ s = affine_span ℝ (set.range t.points),
{ rw [hts, affine_span_insert_eq_affine_span ℝ t.orthocenter_mem_affine_span] },
refine ext_of_direction_eq _
⟨p 0, mem_affine_span ℝ (set.mem_range_self _), mem_affine_span ℝ (hps (set.mem_range_self _))⟩,
have hfd : finite_dimensional ℝ (affine_span ℝ s).direction, { rw hs, apply_instance },
haveI := hfd,
refine eq_of_le_of_finrank_eq (direction_le (affine_span_mono ℝ hps)) _,
rw [hs, direction_affine_span, direction_affine_span,
finrank_vector_span_of_affine_independent ha (fintype.card_fin _),
finrank_vector_span_of_affine_independent t.independent (fintype.card_fin _)]
end
/-- All triangles in an orthocentric system have the same circumradius. -/
lemma orthocentric_system.exists_circumradius_eq {s : set P} (ho : orthocentric_system s) :
∃ r : ℝ, ∀ t : triangle ℝ P, set.range t.points ⊆ s → t.circumradius = r :=
begin
rcases ho with ⟨t, hto, hts⟩,
use t.circumradius,
intros t₂ ht₂,
have ht₂s := ht₂,
rw hts at ht₂,
rcases exists_dist_eq_circumradius_of_subset_insert_orthocenter hto ht₂
(injective_of_affine_independent t₂.independent) with ⟨c, hc, h⟩,
rw set.forall_range_iff at h,
have hs : set.range t.points ⊆ s,
{ rw hts,
exact set.subset_insert _ _ },
rw [affine_span_of_orthocentric_system ⟨t, hto, hts⟩ hs
(injective_of_affine_independent t.independent),
←affine_span_of_orthocentric_system ⟨t, hto, hts⟩ ht₂s
(injective_of_affine_independent t₂.independent)] at hc,
exact (t₂.eq_circumradius_of_dist_eq hc h).symm
end
/-- Given any triangle in an orthocentric system, the fourth point is
its orthocenter. -/
lemma orthocentric_system.eq_insert_orthocenter {s : set P} (ho : orthocentric_system s)
{t : triangle ℝ P} (ht : set.range t.points ⊆ s) :
s = insert t.orthocenter (set.range t.points) :=
begin
rcases ho with ⟨t₀, ht₀o, ht₀s⟩,
rw ht₀s at ht,
rcases exists_of_range_subset_orthocentric_system ht₀o ht
(injective_of_affine_independent t.independent) with
⟨i₁, i₂, i₃, j₂, j₃, h₁₂, h₁₃, h₂₃, h₁₂₃, h₁, hj₂₃, h₂, h₃⟩ | hs,
{ obtain ⟨j₁, hj₁₂, hj₁₃, hj₁₂₃⟩ :
∃ j₁ : fin 3, j₁ ≠ j₂ ∧ j₁ ≠ j₃ ∧ ∀ j : fin 3, j = j₁ ∨ j = j₂ ∨ j = j₃,
{ clear h₂ h₃, dec_trivial! },
suffices h : t₀.points j₁ = t.orthocenter,
{ have hui : (set.univ : set (fin 3)) = {i₁, i₂, i₃}, { ext x, simpa using h₁₂₃ x },
have huj : (set.univ : set (fin 3)) = {j₁, j₂, j₃}, { ext x, simpa using hj₁₂₃ x },
rw [←h, ht₀s, ←set.image_univ, huj, ←set.image_univ, hui],
simp_rw [set.image_insert_eq, set.image_singleton, h₁, ←h₂, ←h₃],
rw set.insert_comm },
exact (triangle.orthocenter_replace_orthocenter_eq_point
hj₁₂ hj₁₃ hj₂₃ h₁₂ h₁₃ h₂₃ h₁ h₂.symm h₃.symm).symm },
{ rw hs,
convert ht₀s using 2,
exact triangle.orthocenter_eq_of_range_eq hs }
end
end euclidean_geometry
|
58291d48e464546cc7b365e26936f27d5241d953 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/ring_theory/integral_domain.lean | d1b93bd0ba86945a0a347cbe7b4532f6b26243c0 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 6,779 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Chris Hughes
-/
import data.fintype.card
import data.polynomial.ring_division
import group_theory.order_of_element
import algebra.geom_sum
/-!
# Integral domains
-/
section
open finset polynomial function
open_locale big_operators nat
variables {R : Type*} {G : Type*} [integral_domain R] [group G] [fintype G]
lemma card_nth_roots_subgroup_units (f : G →* R) (hf : injective f) {n : ℕ} (hn : 0 < n) (g₀ : G) :
({g ∈ univ | g ^ n = g₀} : finset G).card ≤ (nth_roots n (f g₀)).card :=
begin
apply card_le_card_of_inj_on f,
{ intros g hg, rw [sep_def, mem_filter] at hg, rw [mem_nth_roots hn, ← f.map_pow, hg.2] },
{ intros, apply hf, assumption }
end
/-- A finite subgroup of the unit group of an integral domain is cyclic. -/
lemma is_cyclic_of_subgroup_integral_domain (f : G →* R) (hf : injective f) : is_cyclic G :=
begin
haveI := classical.dec_eq G,
apply is_cyclic_of_card_pow_eq_one_le,
intros n hn,
convert (le_trans (card_nth_roots_subgroup_units f hf hn 1) (card_nth_roots n (f 1)))
end
/-- The unit group of a finite integral domain is cyclic. -/
instance [fintype R] : is_cyclic (units R) :=
is_cyclic_of_subgroup_integral_domain (units.coe_hom R) $ units.ext
/-- Every finite integral domain is a field. -/
def field_of_integral_domain [fintype R] [decidable_eq R] : field R :=
{ inv := λ a, if h : a = 0 then 0
else fintype.bij_inv (show function.bijective (* a),
from fintype.injective_iff_bijective.1 $ λ _ _, mul_right_cancel' h) 1,
mul_inv_cancel := λ a ha, show a * dite _ _ _ = _, by rw [dif_neg ha, mul_comm];
exact fintype.right_inverse_bij_inv (show function.bijective (* a), from _) 1,
inv_zero := dif_pos rfl,
..show integral_domain R, by apply_instance }
section
variables (S : set (units R)) [is_subgroup S] [fintype S]
/-- A finite subgroup of the units of an integral domain is cyclic. -/
instance subgroup_units_cyclic : is_cyclic S :=
begin
refine is_cyclic_of_subgroup_integral_domain ⟨(coe : S → R), _, _⟩
(units.ext.comp subtype.val_injective),
{ simp only [is_submonoid.coe_one, units.coe_one, coe_coe] },
{ intros, simp only [is_submonoid.coe_mul, units.coe_mul, coe_coe] },
end
end
lemma card_fiber_eq_of_mem_range {H : Type*} [group H] [decidable_eq H]
(f : G →* H) {x y : H} (hx : x ∈ set.range f) (hy : y ∈ set.range f) :
(univ.filter $ λ g, f g = x).card = (univ.filter $ λ g, f g = y).card :=
begin
rcases hx with ⟨x, rfl⟩,
rcases hy with ⟨y, rfl⟩,
refine card_congr (λ g _, g * x⁻¹ * y) _ _ (λ g hg, ⟨g * y⁻¹ * x, _⟩),
{ simp only [mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv,
eq_self_iff_true, monoid_hom.map_mul_inv, and_self, forall_true_iff] {contextual := tt} },
{ simp only [mul_left_inj, imp_self, forall_2_true_iff], },
{ simp only [true_and, mem_filter, mem_univ] at hg,
simp only [hg, mem_filter, one_mul, monoid_hom.map_mul, mem_univ, mul_right_inv,
eq_self_iff_true, exists_prop_of_true, monoid_hom.map_mul_inv, and_self,
mul_inv_cancel_right, inv_mul_cancel_right], }
end
/-- In an integral domain, a sum indexed by a nontrivial homomorphism from a finite group is zero. -/
lemma sum_hom_units_eq_zero (f : G →* R) (hf : f ≠ 1) : ∑ g : G, f g = 0 :=
begin
classical,
obtain ⟨x, hx⟩ : ∃ x : set.range f.to_hom_units, ∀ y : set.range f.to_hom_units, y ∈ powers x,
from is_cyclic.exists_monoid_generator (set.range (f.to_hom_units)),
have hx1 : x ≠ 1,
{ rintro rfl,
apply hf,
ext g,
rw [monoid_hom.one_apply],
cases hx ⟨f.to_hom_units g, g, rfl⟩ with n hn,
rwa [subtype.ext_iff, units.ext_iff, subtype.coe_mk, monoid_hom.coe_to_hom_units,
is_submonoid.coe_pow, units.coe_pow, is_submonoid.coe_one, units.coe_one,
_root_.one_pow, eq_comm] at hn, },
replace hx1 : (x : R) - 1 ≠ 0,
from λ h, hx1 (subtype.eq (units.ext (sub_eq_zero.1 h))),
let c := (univ.filter (λ g, f.to_hom_units g = 1)).card,
calc ∑ g : G, f g
= ∑ g : G, f.to_hom_units g : rfl
... = ∑ u : units R in univ.image f.to_hom_units, (univ.filter (λ g, f.to_hom_units g = u)).card • u :
sum_comp (coe : units R → R) f.to_hom_units
... = ∑ u : units R in univ.image f.to_hom_units, c • u :
sum_congr rfl (λ u hu, congr_arg2 _ _ rfl) -- remaining goal 1, proven below
... = ∑ b : set.range f.to_hom_units, c • ↑b : finset.sum_subtype
(by simp only [mem_image, set.mem_range, forall_const, iff_self, mem_univ, exists_prop_of_true]) _
... = c • ∑ b : set.range f.to_hom_units, (b : R) : smul_sum.symm
... = c • 0 : congr_arg2 _ rfl _ -- remaining goal 2, proven below
... = 0 : smul_zero _,
{ -- remaining goal 1
show (univ.filter (λ (g : G), f.to_hom_units g = u)).card = c,
apply card_fiber_eq_of_mem_range f.to_hom_units,
{ simpa only [mem_image, mem_univ, exists_prop_of_true, set.mem_range] using hu, },
{ exact ⟨1, f.to_hom_units.map_one⟩ } },
-- remaining goal 2
show ∑ b : set.range f.to_hom_units, (b : R) = 0,
calc ∑ b : set.range f.to_hom_units, (b : R)
= ∑ n in range (order_of x), x ^ n :
eq.symm $ sum_bij (λ n _, x ^ n)
(by simp only [mem_univ, forall_true_iff])
(by simp only [is_submonoid.coe_pow, eq_self_iff_true, units.coe_pow, coe_coe, forall_true_iff])
(λ m n hm hn, pow_injective_of_lt_order_of _
(by simpa only [mem_range] using hm)
(by simpa only [mem_range] using hn))
(λ b hb, let ⟨n, hn⟩ := hx b in ⟨n % order_of x, mem_range.2 (nat.mod_lt _ (order_of_pos _)),
by rw [← pow_eq_mod_order_of, hn]⟩)
... = 0 : _,
rw [← mul_left_inj' hx1, zero_mul, ← geom_series, geom_sum_mul, coe_coe],
norm_cast,
rw [pow_order_of_eq_one, is_submonoid.coe_one, units.coe_one, sub_self],
end
/-- In an integral domain, a sum indexed by a homomorphism from a finite group is zero,
unless the homomorphism is trivial, in which case the sum is equal to the cardinality of the group. -/
lemma sum_hom_units (f : G →* R) [decidable (f = 1)] :
∑ g : G, f g = if f = 1 then fintype.card G else 0 :=
begin
split_ifs with h h,
{ simp [h, card_univ] },
{ exact sum_hom_units_eq_zero f h }
end
lemma left_dvd_or_dvd_right_of_dvd_prime_mul {a : R} :
∀ {b p : R}, prime p → a ∣ p * b → p ∣ a ∨ a ∣ b :=
begin
rintros b p hp ⟨c, hc⟩,
rcases hp.2.2 a c (hc ▸ dvd_mul_right _ _) with h | ⟨x, rfl⟩,
{ exact or.inl h },
{ rw [mul_left_comm, mul_right_inj' hp.ne_zero] at hc,
exact or.inr (hc.symm ▸ dvd_mul_right _ _) }
end
end
|
2d847acc3a324c5c482ea07d872067e7a27a22ee | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/analysis/convex/topology.lean | 2dc0866f40c4fad89d3f9dce52156b54feac9776 | [
"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 | 8,575 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudriashov
-/
import analysis.convex.basic
import analysis.normed_space.finite_dimension
import topology.path_connected
/-!
# Topological and metric properties of convex sets
We prove the following facts:
* `convex.interior` : interior of a convex set is convex;
* `convex.closure` : closure of a convex set is convex;
* `set.finite.compact_convex_hull` : convex hull of a finite set is compact;
* `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed;
* `convex_on_dist` : distance to a fixed point is convex on any convex set;
* `convex_hull_ediam`, `convex_hull_diam` : convex hull of a set has the same (e)metric diameter
as the original set;
* `bounded_convex_hull` : convex hull of a set is bounded if and only if the original set
is bounded.
* `bounded_std_simplex`, `is_closed_std_simplex`, `compact_std_simplex`: topological properties
of the standard simplex;
-/
variables {ι : Type*} {E : Type*}
open set
lemma real.convex_iff_is_preconnected {s : set ℝ} : convex s ↔ is_preconnected s :=
real.convex_iff_ord_connected.trans is_preconnected_iff_ord_connected.symm
alias real.convex_iff_is_preconnected ↔ convex.is_preconnected is_preconnected.convex
/-! ### Standard simplex -/
section std_simplex
variables [fintype ι]
/-- Every vector in `std_simplex ι` has `max`-norm at most `1`. -/
lemma std_simplex_subset_closed_ball :
std_simplex ι ⊆ metric.closed_ball 0 1 :=
begin
assume f hf,
rw [metric.mem_closed_ball, dist_zero_right],
refine (nnreal.coe_one ▸ nnreal.coe_le_coe.2 $ finset.sup_le $ λ x hx, _),
change abs (f x) ≤ 1,
rw [abs_of_nonneg $ hf.1 x],
exact (mem_Icc_of_mem_std_simplex hf x).2
end
variable (ι)
/-- `std_simplex ι` is bounded. -/
lemma bounded_std_simplex : metric.bounded (std_simplex ι) :=
(metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩
/-- `std_simplex ι` is closed. -/
lemma is_closed_std_simplex : is_closed (std_simplex ι) :=
(std_simplex_eq_inter ι).symm ▸ is_closed_inter
(is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i))
(is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const)
/-- `std_simplex ι` is compact. -/
lemma compact_std_simplex : is_compact (std_simplex ι) :=
metric.compact_iff_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩
end std_simplex
/-! ### Topological vector space -/
section has_continuous_smul
variables [add_comm_group E] [vector_space ℝ E] [topological_space E]
[topological_add_group E] [has_continuous_smul ℝ E]
/-- In a topological vector space, the interior of a convex set is convex. -/
lemma convex.interior {s : set E} (hs : convex s) : convex (interior s) :=
convex_iff_pointwise_add_subset.mpr $ λ a b ha hb hab,
have h : is_open (a • interior s + b • interior s), from
or.elim (classical.em (a = 0))
(λ heq,
have hne : b ≠ 0, by { rw [heq, zero_add] at hab, rw hab, exact one_ne_zero },
by { rw ← image_smul,
exact (is_open_map_smul' hne _ is_open_interior).add_left } )
(λ hne,
by { rw ← image_smul,
exact (is_open_map_smul' hne _ is_open_interior).add_right }),
(subset_interior_iff_subset_of_open h).mpr $ subset.trans
(by { simp only [← image_smul], apply add_subset_add; exact image_subset _ interior_subset })
(convex_iff_pointwise_add_subset.mp hs ha hb hab)
/-- In a topological vector space, the closure of a convex set is convex. -/
lemma convex.closure {s : set E} (hs : convex s) : convex (closure s) :=
λ x y hx hy a b ha hb hab,
let f : E → E → E := λ x' y', a • x' + b • y' in
have hf : continuous (λ p : E × E, f p.1 p.2), from
(continuous_const.smul continuous_fst).add (continuous_const.smul continuous_snd),
show f x y ∈ closure s, from
mem_closure_of_continuous2 hf hx hy (λ x' hx' y' hy', subset_closure
(hs hx' hy' ha hb hab))
/-- Convex hull of a finite set is compact. -/
lemma set.finite.compact_convex_hull {s : set E} (hs : finite s) :
is_compact (convex_hull s) :=
begin
rw [hs.convex_hull_eq_image],
apply (compact_std_simplex _).image,
haveI := hs.fintype,
apply linear_map.continuous_on_pi
end
/-- Convex hull of a finite set is closed. -/
lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : finite s) :
is_closed (convex_hull s) :=
hs.compact_convex_hull.is_closed
end has_continuous_smul
/-! ### Normed vector space -/
section normed_space
variables [normed_group E] [normed_space ℝ E]
lemma convex_on_dist (z : E) (s : set E) (hs : convex s) :
convex_on s (λz', dist z' z) :=
and.intro hs $
assume x y hx hy a b ha hb hab,
calc
dist (a • x + b • y) z = ∥ (a • x + b • y) - (a + b) • z ∥ :
by rw [hab, one_smul, normed_group.dist_eq]
... = ∥a • (x - z) + b • (y - z)∥ :
by rw [add_smul, smul_sub, smul_sub, sub_eq_add_neg, sub_eq_add_neg, sub_eq_add_neg, neg_add,
←add_assoc, add_assoc (a • x), add_comm (b • y)]; simp only [add_assoc]
... ≤ ∥a • (x - z)∥ + ∥b • (y - z)∥ :
norm_add_le (a • (x - z)) (b • (y - z))
... = a * dist x z + b * dist y z :
by simp [norm_smul, normed_group.dist_eq, real.norm_eq_abs, abs_of_nonneg ha, abs_of_nonneg hb]
lemma convex_ball (a : E) (r : ℝ) : convex (metric.ball a r) :=
by simpa only [metric.ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_lt r
lemma convex_closed_ball (a : E) (r : ℝ) : convex (metric.closed_ball a r) :=
by simpa only [metric.closed_ball, sep_univ] using (convex_on_dist a _ convex_univ).convex_le r
/-- Given a point `x` in the convex hull of `s` and a point `y`, there exists a point
of `s` at distance at least `dist x y` from `y`. -/
lemma convex_hull_exists_dist_ge {s : set E} {x : E} (hx : x ∈ convex_hull s) (y : E) :
∃ x' ∈ s, dist x y ≤ dist x' y :=
(convex_on_dist y _ (convex_convex_hull _)).exists_ge_of_mem_convex_hull hx
/-- Given a point `x` in the convex hull of `s` and a point `y` in the convex hull of `t`,
there exist points `x' ∈ s` and `y' ∈ t` at distance at least `dist x y`. -/
lemma convex_hull_exists_dist_ge2 {s t : set E} {x y : E}
(hx : x ∈ convex_hull s) (hy : y ∈ convex_hull t) :
∃ (x' ∈ s) (y' ∈ t), dist x y ≤ dist x' y' :=
begin
rcases convex_hull_exists_dist_ge hx y with ⟨x', hx', Hx'⟩,
rcases convex_hull_exists_dist_ge hy x' with ⟨y', hy', Hy'⟩,
use [x', hx', y', hy'],
exact le_trans Hx' (dist_comm y x' ▸ dist_comm y' x' ▸ Hy')
end
/-- Emetric diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/
@[simp] lemma convex_hull_ediam (s : set E) :
emetric.diam (convex_hull s) = emetric.diam s :=
begin
refine (emetric.diam_le $ λ x hx y hy, _).antisymm (emetric.diam_mono $ subset_convex_hull s),
rcases convex_hull_exists_dist_ge2 hx hy with ⟨x', hx', y', hy', H⟩,
rw edist_dist,
apply le_trans (ennreal.of_real_le_of_real H),
rw ← edist_dist,
exact emetric.edist_le_diam_of_mem hx' hy'
end
/-- Diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/
@[simp] lemma convex_hull_diam (s : set E) :
metric.diam (convex_hull s) = metric.diam s :=
by simp only [metric.diam, convex_hull_ediam]
/-- Convex hull of `s` is bounded if and only if `s` is bounded. -/
@[simp] lemma bounded_convex_hull {s : set E} :
metric.bounded (convex_hull s) ↔ metric.bounded s :=
by simp only [metric.bounded_iff_ediam_ne_top, convex_hull_ediam]
lemma convex.is_path_connected {s : set E} (hconv : convex s) (hne : s.nonempty) :
is_path_connected s :=
begin
refine is_path_connected_iff.mpr ⟨hne, _⟩,
intros x y x_in y_in,
let f := λ θ : ℝ, x + θ • (y - x),
have hf : continuous f, by continuity,
have h₀ : f 0 = x, by simp [f],
have h₁ : f 1 = y, by { dsimp [f], rw one_smul, abel },
have H := hconv.segment_subset x_in y_in,
rw segment_eq_image' at H,
exact joined_in.of_line hf.continuous_on h₀ h₁ H
end
@[priority 100]
instance normed_space.path_connected : path_connected_space E :=
path_connected_space_iff_univ.mpr $ convex_univ.is_path_connected ⟨(0 : E), trivial⟩
@[priority 100]
instance normed_space.loc_path_connected : loc_path_connected_space E :=
loc_path_connected_of_bases (λ x, metric.nhds_basis_ball)
(λ x r r_pos, (convex_ball x r).is_path_connected $ by simp [r_pos])
end normed_space
|
23ae231d250af2cee16898bd44e4c964db9e2f40 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/tensor_product.lean | c5f504961e7b404d2ef55c150650af3d2c773150 | [
"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 | 43,472 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Mario Carneiro
-/
import group_theory.congruence
import algebra.module.submodule.bilinear
/-!
# Tensor product of modules over commutative semirings.
This file constructs the tensor product of modules over commutative semirings. Given a semiring
`R` and modules over it `M` and `N`, the standard construction of the tensor product is
`tensor_product R M N`. It is also a module over `R`.
It comes with a canonical bilinear map `M → N → tensor_product R M N`.
Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose
composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear
map `M → N → P`.
We start by proving basic lemmas about bilinear maps.
## Notations
This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well
as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`.
## Tags
bilinear, tensor, tensor product
-/
section semiring
variables {R : Type*} [comm_semiring R]
variables {R' : Type*} [monoid R']
variables {R'' : Type*} [semiring R'']
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q]
[add_comm_monoid S]
variables [module R M] [module R N] [module R P] [module R Q] [module R S]
variables [distrib_mul_action R' M]
variables [module R'' M]
include R
variables (M N)
namespace tensor_product
section
-- open free_add_monoid
variables (R)
/-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is
the tensor product. -/
inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop
| of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0
| of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0
| of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv
(free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n))
| of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv
(free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂))
| of_smul : ∀ (r : R) (m : M) (n : N), eqv
(free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n))
| add_comm : ∀ x y, eqv (x + y) (y + x)
end
end tensor_product
variables (R)
/-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`.
The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/
def tensor_product : Type* :=
(add_con_gen (tensor_product.eqv R M N)).quotient
variables {R}
localized "infix (name := tensor_product.infer)
` ⊗ `:100 := tensor_product hole!" in tensor_product
localized "notation (name := tensor_product)
M ` ⊗[`:100 R `] `:0 N:100 := tensor_product R M N" in tensor_product
namespace tensor_product
section module
instance : add_zero_class (M ⊗[R] N) :=
{ .. (add_con_gen (tensor_product.eqv R M N)).add_monoid }
instance : add_comm_semigroup (M ⊗[R] N) :=
{ add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $
add_con_gen.rel.of _ _ $ eqv.add_comm _ _,
.. (add_con_gen (tensor_product.eqv R M N)).add_monoid }
instance : inhabited (M ⊗[R] N) := ⟨0⟩
variables (R) {M N}
/-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`,
accessed by `open_locale tensor_product`. -/
def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n)
variables {R}
infix ` ⊗ₜ `:100 := tmul _
notation x ` ⊗ₜ[`:100 R `] `:0 y:100 := tmul R x y
@[elab_as_eliminator]
protected theorem induction_on
{C : (M ⊗[R] N) → Prop}
(z : M ⊗[R] N)
(C0 : C 0)
(C1 : ∀ {x y}, C $ x ⊗ₜ[R] y)
(Cp : ∀ {x y}, C x → C y → C (x + y)) : C z :=
add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih,
by { rw add_con.coe_add, exact Cp C1 ih }
variables (M)
@[simp] lemma zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _
variables {M}
lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _
variables (N)
@[simp] lemma tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 :=
quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _
variables {N}
lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ :=
eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _
section
variables (R R' M N)
/--
A typeclass for `has_smul` structures which can be moved across a tensor product.
This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that
we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if
`R` does not support negation.
Note that `module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only
needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is
used.
-/
class compatible_smul [distrib_mul_action R' N] :=
(smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n))
end
/-- Note that this provides the default `compatible_smul R R M N` instance through
`mul_action.is_scalar_tower.left`. -/
@[priority 100]
instance compatible_smul.is_scalar_tower
[has_smul R' R] [is_scalar_tower R' R M] [distrib_mul_action R' N] [is_scalar_tower R' R N] :
compatible_smul R R' M N :=
⟨λ r m n, begin
conv_lhs {rw ← one_smul R m},
conv_rhs {rw ← one_smul R n},
rw [←smul_assoc, ←smul_assoc],
exact (quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _),
end⟩
/-- `smul` can be moved from one side of the product to the other .-/
lemma smul_tmul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) :
(r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) :=
compatible_smul.smul_tmul _ _ _
/-- Auxiliary function to defining scalar multiplication on tensor product. -/
def smul.aux {R' : Type*} [has_smul R' M] (r : R') : free_add_monoid (M × N) →+ M ⊗[R] N :=
free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2
theorem smul.aux_of {R' : Type*} [has_smul R' M] (r : R') (m : M) (n : N) :
smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ[R] n :=
rfl
variables [smul_comm_class R R' M]
variables [smul_comm_class R R'' M]
/-- Given two modules over a commutative semiring `R`, if one of the factors carries a
(distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then
the tensor product (over `R`) carries an action of `R'`.
This instance defines this `R'` action in the case that it is the left module which has the `R'`
action. Two natural ways in which this situation arises are:
* Extension of scalars
* A tensor product of a group representation with a module not carrying an action
Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar
action on a tensor product of two modules. This special case is important enough that, for
performance reasons, we define it explicitly below. -/
instance left_has_smul : has_smul R' (M ⊗[R] N) :=
⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r : _ →+ M ⊗[R] N) $
add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add]
| _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $
by rw [smul.aux_of, smul.aux_of, ←smul_comm, smul_tmul]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end⟩
instance : has_smul R (M ⊗[R] N) := tensor_product.left_has_smul
protected theorem smul_zero (r : R') : (r • 0 : M ⊗[R] N) = 0 :=
add_monoid_hom.map_zero _
protected theorem smul_add (r : R') (x y : M ⊗[R] N) :
r • (x + y) = r • x + r • y :=
add_monoid_hom.map_add _ _ _
protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 :=
have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl,
tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [this, zero_smul, zero_tmul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero])
protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x :=
have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl,
tensor_product.induction_on x
(by rw tensor_product.smul_zero)
(λ m n, by rw [this, one_smul])
(λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy])
protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x :=
have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl,
tensor_product.induction_on x
(by simp_rw [tensor_product.smul_zero, add_zero])
(λ m n, by simp_rw [this, add_smul, add_tmul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] })
instance : add_comm_monoid (M ⊗[R] N) :=
{ nsmul := λ n v, n • v,
nsmul_zero' := by simp [tensor_product.zero_smul],
nsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul],
.. tensor_product.add_comm_semigroup _ _, .. tensor_product.add_zero_class _ _}
instance left_distrib_mul_action : distrib_mul_action R' (M ⊗[R] N) :=
have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl,
{ smul := (•),
smul_add := λ r x y, tensor_product.smul_add r x y,
mul_smul := λ r s x, tensor_product.induction_on x
(by simp_rw tensor_product.smul_zero)
(λ m n, by simp_rw [this, mul_smul])
(λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }),
one_smul := tensor_product.one_smul,
smul_zero := tensor_product.smul_zero }
instance : distrib_mul_action R (M ⊗[R] N) := tensor_product.left_distrib_mul_action
theorem smul_tmul' (r : R') (m : M) (n : N) :
r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n :=
rfl
@[simp] lemma tmul_smul
[distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (x : M) (y : N) :
x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) :=
(smul_tmul _ _ _).symm
lemma smul_tmul_smul (r s : R) (m : M) (n : N) : (r • m) ⊗ₜ[R] (s • n) = (r * s) • (m ⊗ₜ[R] n) :=
by simp only [tmul_smul, smul_tmul, mul_smul]
instance left_module : module R'' (M ⊗[R] N) :=
{ smul := (•),
add_smul := tensor_product.add_smul,
zero_smul := tensor_product.zero_smul,
..tensor_product.left_distrib_mul_action }
instance : module R (M ⊗[R] N) := tensor_product.left_module
instance [module R''ᵐᵒᵖ M] [is_central_scalar R'' M] : is_central_scalar R'' (M ⊗[R] N) :=
{ op_smul_eq_smul := λ r x,
tensor_product.induction_on x
(by rw [smul_zero, smul_zero])
(λ x y, by rw [smul_tmul', smul_tmul', op_smul_eq_smul])
(λ x y hx hy, by rw [smul_add, smul_add, hx, hy]) }
section
-- Like `R'`, `R'₂` provides a `distrib_mul_action R'₂ (M ⊗[R] N)`
variables {R'₂ : Type*} [monoid R'₂] [distrib_mul_action R'₂ M]
variables [smul_comm_class R R'₂ M] [has_smul R'₂ R']
/-- `is_scalar_tower R'₂ R' M` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/
instance is_scalar_tower_left [is_scalar_tower R'₂ R' M] :
is_scalar_tower R'₂ R' (M ⊗[R] N) :=
⟨λ s r x, tensor_product.induction_on x
(by simp)
(λ m n, by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc])
(λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩
variables [distrib_mul_action R'₂ N] [distrib_mul_action R' N]
variables [compatible_smul R R'₂ M N] [compatible_smul R R' M N]
/-- `is_scalar_tower R'₂ R' N` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/
instance is_scalar_tower_right [is_scalar_tower R'₂ R' N] :
is_scalar_tower R'₂ R' (M ⊗[R] N) :=
⟨λ s r x, tensor_product.induction_on x
(by simp)
(λ m n, by rw [←tmul_smul, ←tmul_smul, ←tmul_smul, smul_assoc])
(λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩
end
/-- A short-cut instance for the common case, where the requirements for the `compatible_smul`
instances are sufficient. -/
instance is_scalar_tower [has_smul R' R] [is_scalar_tower R' R M] :
is_scalar_tower R' R (M ⊗[R] N) :=
tensor_product.is_scalar_tower_left -- or right
variables (R M N)
/-- The canonical bilinear map `M → N → M ⊗[R] N`. -/
def mk : M →ₗ[R] N →ₗ[R] M ⊗[R] N :=
linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul
variables {R M N}
@[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl
lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
(if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 :=
by { split_ifs; simp }
lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] :
x₁ ⊗ₜ[R] (if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 :=
by { split_ifs; simp }
section
open_locale big_operators
lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) :
(∑ a in s, m a) ⊗ₜ[R] n = ∑ a in s, m a ⊗ₜ[R] n :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, add_tmul, ih], },
end
lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) :
m ⊗ₜ[R] (∑ a in s, n a) = ∑ a in s, m ⊗ₜ[R] n a :=
begin
classical,
induction s using finset.induction with a s has ih h,
{ simp, },
{ simp [finset.sum_insert has, tmul_add, ih], },
end
end
variables (R M N)
/-- The simple (aka pure) elements span the tensor product. -/
lemma span_tmul_eq_top :
submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ :=
begin
ext t, simp only [submodule.mem_top, iff_true],
apply t.induction_on,
{ exact submodule.zero_mem _, },
{ intros m n, apply submodule.subset_span, use [m, n], },
{ intros t₁ t₂ ht₁ ht₂, exact submodule.add_mem _ ht₁ ht₂, },
end
@[simp] lemma map₂_mk_top_top_eq_top : submodule.map₂ (mk R M N) ⊤ ⊤ = ⊤ :=
begin
rw [← top_le_iff, ← span_tmul_eq_top, submodule.map₂_eq_span_image2],
exact submodule.span_mono (λ _ ⟨m, n, h⟩, ⟨m, n, trivial, trivial, h⟩),
end
end module
section UMP
variables {M N P Q}
variables (f : M →ₗ[R] N →ₗ[R] P)
/-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift_aux : (M ⊗[R] N) →+ P :=
(add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $
add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add]
| _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $
by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end
lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n :=
zero_add _
variable {f}
@[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x :=
tensor_product.induction_on x (smul_zero _).symm
(λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul])
(λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add])
variable (f)
/-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that
its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift : M ⊗ N →ₗ[R] P :=
{ map_smul' := lift_aux.smul,
.. lift_aux f }
variable {f}
@[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y :=
zero_add _
@[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y :=
lift.tmul _ _
theorem ext' {g h : (M ⊗[R] N) →ₗ[R] P}
(H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h :=
linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $
λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy]
theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) :
g = lift f :=
ext' $ λ m n, by rw [H, lift.tmul]
theorem lift_mk : lift (mk R M N) = linear_map.id :=
eq.symm $ lift.unique $ λ x y, rfl
theorem lift_compr₂ (g : P →ₗ[R] Q) : lift (f.compr₂ g) = g.comp (lift f) :=
eq.symm $ lift.unique $ λ x y, by simp
theorem lift_mk_compr₂ (f : M ⊗ N →ₗ[R] P) : lift ((mk R M N).compr₂ f) = f :=
by rw [lift_compr₂ f, lift_mk, linear_map.comp_id]
/--
This used to be an `@[ext]` lemma, but it fails very slowly when the `ext` tactic tries to apply
it in some cases, notably when one wants to show equality of two linear maps. The `@[ext]`
attribute is now added locally where it is needed. Using this as the `@[ext]` lemma instead of
`tensor_product.ext'` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`.
See note [partially-applied ext lemmas]. -/
theorem ext {g h : M ⊗ N →ₗ[R] P}
(H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h :=
by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂]
local attribute [ext] ext
example : M → N → (M → N → P) → P :=
λ m, flip $ λ f, f m
variables (R M N P)
/-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P :=
linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id)
variables {R M N P}
@[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
uncurry R M N P f (m ⊗ₜ n) = f m n :=
by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl
variables (R M N P)
/-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P`
with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is
the given bilinear map `M → N → P`. -/
def lift.equiv : (M →ₗ[R] N →ₗ[R] P) ≃ₗ[R] (M ⊗ N →ₗ[R] P) :=
{ inv_fun := λ f, (mk R M N).compr₂ f,
left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _,
right_inv := λ f, ext' $ λ m n, lift.tmul _ _,
.. uncurry R M N P }
@[simp] lemma lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) :
lift.equiv R M N P f (m ⊗ₜ n) = f m n :=
uncurry_apply f m n
@[simp] lemma lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) :
(lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) :=
rfl
/-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to
form a bilinear map `M → N → P`. -/
def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P :=
(lift.equiv R M N P).symm
variables {R M N P}
@[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) :
lcurry R M N P f m n = f (m ⊗ₜ n) := rfl
/-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to
form a bilinear map `M → N → P`. -/
def curry (f : M ⊗ N →ₗ[R] P) : M →ₗ[R] N →ₗ[R] P := lcurry R M N P f
@[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) :
curry f m n = f (m ⊗ₜ n) := rfl
lemma curry_injective : function.injective (curry : (M ⊗[R] N →ₗ[R] P) → (M →ₗ[R] N →ₗ[R] P)) :=
λ g h H, ext H
theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q}
(H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
ext x y z,
exact H x y z
end
-- We'll need this one for checking the pentagon identity!
theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S}
(H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h :=
begin
ext w x y z,
exact H w x y z,
end
end UMP
variables {M N}
section
variables (R M)
/--
The base ring is a left identity for the tensor product of modules, up to linear equivalence.
-/
protected def lid : R ⊗ M ≃ₗ[R] M :=
linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1)
(linear_map.ext $ λ _, by simp)
(ext' $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one])
end
@[simp] theorem lid_tmul (m : M) (r : R) :
((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m :=
begin
dsimp [tensor_product.lid],
simp,
end
@[simp] lemma lid_symm_apply (m : M) :
(tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl
section
variables (R M N)
/--
The tensor product of modules is commutative, up to linear equivalence.
-/
protected def comm : M ⊗ N ≃ₗ[R] N ⊗ M :=
linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip)
(ext' $ λ m n, rfl)
(ext' $ λ m n, rfl)
@[simp] theorem comm_tmul (m : M) (n : N) :
(tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl
@[simp] theorem comm_symm_tmul (m : M) (n : N) :
(tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl
end
section
variables (R M)
/--
The base ring is a right identity for the tensor product of modules, up to linear equivalence.
-/
protected def rid : M ⊗[R] R ≃ₗ[R] M :=
linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M)
end
@[simp] theorem rid_tmul (m : M) (r : R) :
(tensor_product.rid R M) (m ⊗ₜ r) = r • m :=
begin
dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid],
simp,
end
@[simp] lemma rid_symm_apply (m : M) :
(tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl
open linear_map
section
variables (R M N P)
/-- The associator for tensor product of R-modules, as a linear equivalence. -/
protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) :=
begin
refine linear_equiv.of_linear
(lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _)
(lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _)
(ext $ linear_map.ext $ λ m, ext' $ λ n p, _)
(ext $ flip_inj $ linear_map.ext $ λ p, ext' $ λ m n, _);
repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|>
rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|>
rw uncurry_apply <|> rw curry_apply <|> rw id_apply }
end
end
@[simp] theorem assoc_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl
@[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) :
(tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl
/-- The tensor product of a pair of linear maps between modules. -/
def map (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : M ⊗ N →ₗ[R] P ⊗ Q :=
lift $ comp (compl₂ (mk _ _ _) g) f
@[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) :
map f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
lemma map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(map f g).range = submodule.span R { t | ∃ m n, (f m) ⊗ₜ (g n) = t } :=
begin
simp only [← submodule.map_top, ← span_tmul_eq_top, submodule.map_span, set.mem_image,
set.mem_set_of_eq],
congr, ext t,
split,
{ rintros ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩, use [m, n], simp only [map_tmul], },
{ rintros ⟨m, n, rfl⟩, use [m ⊗ₜ n, m, n], simp only [map_tmul], },
end
/-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/
@[simp] def map_incl (p : submodule R P) (q : submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q :=
map p.subtype q.subtype
section
variables {P' Q' : Type*}
variables [add_comm_monoid P'] [module R P']
variables [add_comm_monoid Q'] [module R Q']
lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) :
map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) :=
ext' $ λ _ _, by simp only [linear_map.comp_apply, map_tmul]
lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(lift i).comp (map f g) = lift ((i.comp f).compl₂ g) :=
ext' $ λ _ _, by simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply]
local attribute [ext] ext
@[simp] lemma map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = id :=
by { ext, simp only [mk_apply, id_coe, compr₂_apply, id.def, map_tmul], }
@[simp] lemma map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id
lemma map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) :
map (f₁ * f₂) (g₁ * g₂) = (map f₁ g₁) * (map f₂ g₂) :=
map_comp f₁ f₂ g₁ g₂
@[simp] protected lemma map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) :
(map f g)^n = map (f^n) (g^n) :=
begin
induction n with n ih,
{ simp only [pow_zero, map_one], },
{ simp only [pow_succ', ih, map_mul], },
end
lemma map_add_left (f₁ f₂ : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (f₁ + f₂) g = map f₁ g + map f₂ g :=
by {ext, simp only [add_tmul, compr₂_apply, mk_apply, map_tmul, add_apply]}
lemma map_add_right (f : M →ₗ[R] P) (g₁ g₂ : N →ₗ[R] Q) : map f (g₁ + g₂) = map f g₁ + map f g₂ :=
by {ext, simp only [tmul_add, compr₂_apply, mk_apply, map_tmul, add_apply]}
lemma map_smul_left (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map (r • f) g = r • map f g :=
by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]}
lemma map_smul_right (r : R) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : map f (r • g) = r • map f g :=
by {ext, simp only [smul_tmul, compr₂_apply, mk_apply, map_tmul, smul_apply, tmul_smul]}
variables (R M N P Q)
/-- The tensor product of a pair of linear maps between modules, bilinear in both maps. -/
def map_bilinear : (M →ₗ[R] P) →ₗ[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) :=
linear_map.mk₂ R map map_add_left map_smul_left map_add_right map_smul_right
/-- The canonical linear map from `P ⊗[R] (M →ₗ[R] Q)` to `(M →ₗ[R] P ⊗[R] Q)` -/
def ltensor_hom_to_hom_ltensor : P ⊗[R] (M →ₗ[R] Q) →ₗ[R] (M →ₗ[R] P ⊗[R] Q) :=
tensor_product.lift (llcomp R M Q _ ∘ₗ mk R P Q)
/-- The canonical linear map from `(M →ₗ[R] P) ⊗[R] Q` to `(M →ₗ[R] P ⊗[R] Q)` -/
def rtensor_hom_to_hom_rtensor : (M →ₗ[R] P) ⊗[R] Q →ₗ[R] (M →ₗ[R] P ⊗[R] Q) :=
tensor_product.lift (llcomp R M P _ ∘ₗ (mk R P Q).flip).flip
/-- The linear map from `(M →ₗ P) ⊗ (N →ₗ Q)` to `(M ⊗ N →ₗ P ⊗ Q)` sending `f ⊗ₜ g` to
the `tensor_product.map f g`, the tensor product of the two maps. -/
def hom_tensor_hom_map : (M →ₗ[R] P) ⊗[R] (N →ₗ[R] Q) →ₗ[R] (M ⊗[R] N →ₗ[R] P ⊗[R] Q) :=
lift (map_bilinear R M N P Q)
variables {R M N P Q}
@[simp]
lemma map_bilinear_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
map_bilinear R M N P Q f g = map f g := rfl
@[simp]
lemma ltensor_hom_to_hom_ltensor_apply (p : P) (f : M →ₗ[R] Q) (m : M) :
ltensor_hom_to_hom_ltensor R M P Q (p ⊗ₜ f) m = p ⊗ₜ f m := rfl
@[simp]
lemma rtensor_hom_to_hom_rtensor_apply (f : M →ₗ[R] P) (q : Q) (m : M) :
rtensor_hom_to_hom_rtensor R M P Q (f ⊗ₜ q) m = f m ⊗ₜ q := rfl
@[simp]
lemma hom_tensor_hom_map_apply (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
hom_tensor_hom_map R M N P Q (f ⊗ₜ g) = map f g :=
by simp only [hom_tensor_hom_map, lift.tmul, map_bilinear_apply]
end
/-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent
then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/
def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q :=
linear_equiv.of_linear (map f g) (map f.symm g.symm)
(ext' $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply])
(ext' $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply])
@[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) :
congr f g (m ⊗ₜ n) = f m ⊗ₜ g n :=
rfl
@[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) :
(congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q :=
rfl
variables (R M N P Q)
/-- A tensor product analogue of `mul_left_comm`. -/
def left_comm : M ⊗[R] (N ⊗[R] P) ≃ₗ[R] N ⊗[R] (M ⊗[R] P) :=
let e₁ := (tensor_product.assoc R M N P).symm,
e₂ := congr (tensor_product.comm R M N) (1 : P ≃ₗ[R] P),
e₃ := (tensor_product.assoc R N M P) in
e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃)
variables {M N P Q}
@[simp] lemma left_comm_tmul (m : M) (n : N) (p : P) :
left_comm R M N P (m ⊗ₜ (n ⊗ₜ p)) = n ⊗ₜ (m ⊗ₜ p) :=
rfl
@[simp] lemma left_comm_symm_tmul (m : M) (n : N) (p : P) :
(left_comm R M N P).symm (n ⊗ₜ (m ⊗ₜ p)) = m ⊗ₜ (n ⊗ₜ p) :=
rfl
variables (M N P Q)
/-- This special case is worth defining explicitly since it is useful for defining multiplication
on tensor products of modules carrying multiplications (e.g., associative rings, Lie rings, ...).
E.g., suppose `M = P` and `N = Q` and that `M` and `N` carry bilinear multiplications:
`M ⊗ M → M` and `N ⊗ N → N`. Using `map`, we can define `(M ⊗ M) ⊗ (N ⊗ N) → M ⊗ N` which, when
combined with this definition, yields a bilinear multiplication on `M ⊗ N`:
`(M ⊗ N) ⊗ (M ⊗ N) → M ⊗ N`. In particular we could use this to define the multiplication in
the `tensor_product.semiring` instance (currently defined "by hand" using `tensor_product.mul`).
See also `mul_mul_mul_comm`. -/
def tensor_tensor_tensor_comm : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] (M ⊗[R] P) ⊗[R] (N ⊗[R] Q) :=
let e₁ := tensor_product.assoc R M N (P ⊗[R] Q),
e₂ := congr (1 : M ≃ₗ[R] M) (left_comm R N P Q),
e₃ := (tensor_product.assoc R M P (N ⊗[R] Q)).symm in
e₁ ≪≫ₗ (e₂ ≪≫ₗ e₃)
variables {M N P Q}
@[simp] lemma tensor_tensor_tensor_comm_tmul (m : M) (n : N) (p : P) (q : Q) :
tensor_tensor_tensor_comm R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q) :=
rfl
@[simp] lemma tensor_tensor_tensor_comm_symm_tmul (m : M) (n : N) (p : P) (q : Q) :
(tensor_tensor_tensor_comm R M N P Q).symm ((m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q)) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) :=
rfl
variables (M N P Q)
/-- This special case is useful for describing the interplay between `dual_tensor_hom_equiv` and
composition of linear maps.
E.g., composition of linear maps gives a map `(M → N) ⊗ (N → P) → (M → P)`, and applying
`dual_tensor_hom_equiv.symm` to the three hom-modules gives a map
`(M.dual ⊗ N) ⊗ (N.dual ⊗ P) → (M.dual ⊗ P)`, which agrees with the application of `contract_right`
on `N ⊗ N.dual` after the suitable rebracketting.
-/
def tensor_tensor_tensor_assoc : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] M ⊗[R] (N ⊗[R] P) ⊗[R] Q :=
(tensor_product.assoc R (M ⊗[R] N) P Q).symm ≪≫ₗ
congr (tensor_product.assoc R M N P) (1 : Q ≃ₗ[R] Q)
variables {M N P Q}
@[simp] lemma tensor_tensor_tensor_assoc_tmul (m : M) (n : N) (p : P) (q : Q) :
tensor_tensor_tensor_assoc R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q := rfl
@[simp] lemma tensor_tensor_tensor_assoc_symm_tmul (m : M) (n : N) (p : P) (q : Q) :
(tensor_tensor_tensor_assoc R M N P Q).symm (m ⊗ₜ (n ⊗ₜ p) ⊗ₜ q) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) :=
rfl
end tensor_product
namespace linear_map
variables {R} (M) {N P Q}
/-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/
def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P :=
tensor_product.map id f
/-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/
def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M :=
tensor_product.map f id
variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P)
@[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl
@[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl
open tensor_product
local attribute [ext] tensor_product.ext
/-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/
def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) :=
{ to_fun := ltensor M,
map_add' := λ f g, by
{ ext x y, simp only [compr₂_apply, mk_apply, add_apply, ltensor_tmul, tmul_add] },
map_smul' := λ r f, by
{ dsimp, ext x y, simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, ltensor_tmul] } }
/-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/
def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) :=
{ to_fun := λ f, f.rtensor M,
map_add' := λ f g, by
{ ext x y, simp only [compr₂_apply, mk_apply, add_apply, rtensor_tmul, add_tmul] },
map_smul' := λ r f, by
{ dsimp, ext x y, simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply,
rtensor_tmul] } }
@[simp] lemma coe_ltensor_hom :
(ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl
@[simp] lemma coe_rtensor_hom :
(rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl
@[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M :=
(ltensor_hom M).map_add f g
@[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M :=
(rtensor_hom M).map_add f g
@[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 :=
(ltensor_hom M).map_zero
@[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 :=
(rtensor_hom M).map_zero
@[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) :=
(ltensor_hom M).map_smul r f
@[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) :=
(rtensor_hom M).map_smul r f
lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) :=
by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, ltensor_tmul] }
lemma ltensor_comp_apply (x : M ⊗[R] N) :
(g.comp f).ltensor M x = (g.ltensor M) ((f.ltensor M) x) :=
by { rw [ltensor_comp, coe_comp], }
lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) :=
by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, rtensor_tmul] }
lemma rtensor_comp_apply (x : N ⊗[R] M) :
(g.comp f).rtensor M x = (g.rtensor M) ((f.rtensor M) x) :=
by { rw [rtensor_comp, coe_comp], }
lemma ltensor_mul (f g : module.End R N) : (f * g).ltensor M = (f.ltensor M) * (g.ltensor M) :=
ltensor_comp M f g
lemma rtensor_mul (f g : module.End R N) : (f * g).rtensor M = (f.rtensor M) * (g.rtensor M) :=
rtensor_comp M f g
variables (N)
@[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id := map_id
-- `simp` can prove this.
lemma ltensor_id_apply (x : M ⊗[R] N) : (linear_map.id : N →ₗ[R] N).ltensor M x = x :=
by {rw [ltensor_id, id_coe, id.def], }
@[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id := map_id
-- `simp` can prove this.
lemma rtensor_id_apply (x : N ⊗[R] M) : (linear_map.id : N →ₗ[R] N).rtensor M x = x :=
by { rw [rtensor_id, id_coe, id.def], }
variables {N}
@[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(g.ltensor P).comp (f.rtensor N) = map f g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(f.rtensor Q).comp (g.ltensor M) = map f g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) :
(map f g).comp (f'.rtensor _) = map (f.comp f') g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) :
(map f g).comp (g'.ltensor _) = map f (g.comp g') :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(f'.rtensor _).comp (map f g) = map (f'.comp f) g :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
@[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) :
(g'.ltensor _).comp (map f g) = map f (g'.comp g) :=
by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id]
variables {M}
@[simp] lemma rtensor_pow (f : M →ₗ[R] M) (n : ℕ) : (f.rtensor N)^n = (f^n).rtensor N :=
by { have h := tensor_product.map_pow f (id : N →ₗ[R] N) n, rwa id_pow at h, }
@[simp] lemma ltensor_pow (f : N →ₗ[R] N) (n : ℕ) : (f.ltensor M)^n = (f^n).ltensor M :=
by { have h := tensor_product.map_pow (id : M →ₗ[R] M) f n, rwa id_pow at h, }
end linear_map
end semiring
section ring
variables {R : Type*} [comm_semiring R]
variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*}
variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q]
[add_comm_group S]
variables [module R M] [module R N] [module R P] [module R Q] [module R S]
namespace tensor_product
open_locale tensor_product
open linear_map
variables (R)
/-- Auxiliary function to defining negation multiplication on tensor product. -/
def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N :=
free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2
variables {R}
theorem neg.aux_of (m : M) (n : N) :
neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n :=
rfl
instance : has_neg (M ⊗[R] N) :=
{ neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $
λ x y hxy, match x, y, hxy with
| _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul]
| _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero]
| _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul]
| _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add]
| _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $
by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg]
| _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $
by simp_rw [add_monoid_hom.map_add, add_comm]
end }
protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 :=
tensor_product.induction_on x
(by { rw [add_zero], apply (neg.aux R).map_zero, })
(λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], })
(λ x y hx hy, by
{ unfold has_neg.neg sub_neg_monoid.neg,
rw add_monoid_hom.map_add,
ac_change (-x + x) + (-y + y) = 0,
rw [hx, hy, add_zero], })
instance : add_comm_group (M ⊗[R] N) :=
{ neg := has_neg.neg,
sub := _,
sub_eq_add_neg := λ _ _, rfl,
add_left_neg := λ x, by exact tensor_product.add_left_neg x,
zsmul := λ n v, n • v,
zsmul_zero' := by simp [tensor_product.zero_smul],
zsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul],
zsmul_neg' := λ n x, begin
change (- n.succ : ℤ) • x = - (((n : ℤ) + 1) • x),
rw [← zero_add (-↑(n.succ) • x), ← tensor_product.add_left_neg (↑(n.succ) • x), add_assoc,
← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero],
refl,
end,
.. tensor_product.add_comm_monoid }
lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl
lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _
lemma tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = (m ⊗ₜ[R] n₁) - (m ⊗ₜ[R] n₂) :=
(mk R M N _).map_sub _ _
lemma sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = (m₁ ⊗ₜ[R] n) - (m₂ ⊗ₜ[R] n) :=
(mk R M N).map_sub₂ _ _ _
/--
While the tensor product will automatically inherit a ℤ-module structure from
`add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless
we use a `ℤ-module` instance provided by `tensor_product.left_module`.
When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through
`is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch.
The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`.
-/
instance compatible_smul.int : compatible_smul R ℤ M N :=
⟨λ r m n, int.induction_on r
(by simp)
(λ r ih, by simpa [add_smul, tmul_add, add_tmul] using ih)
(λ r ih, by simpa [sub_smul, tmul_sub, sub_tmul] using ih)⟩
instance compatible_smul.unit {S} [monoid S] [distrib_mul_action S M] [distrib_mul_action S N]
[compatible_smul R S M N] :
compatible_smul R Sˣ M N :=
⟨λ s m n, (compatible_smul.smul_tmul (s : S) m n : _)⟩
end tensor_product
namespace linear_map
@[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M :=
by simp only [← coe_ltensor_hom, map_sub]
@[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M :=
by simp only [← coe_rtensor_hom, map_sub]
@[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) :=
by simp only [← coe_ltensor_hom, map_neg]
@[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) :=
by simp only [← coe_rtensor_hom, map_neg]
end linear_map
end ring
|
35e7c62850b0f367b0ee81b6783bff3e72b48295 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/match_anonymous_constructor.lean | f66adfc7494f852ac30f89c01e76ff4fa7204210 | [
"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 | 172 | lean | definition p1 := (10, 20, 30)
definition v2 : nat :=
match p1 with
⟨a, b⟩ := a
end
example : v2 = 10 := rfl
definition v3 : nat :=
match p1 with
⟨a, b⟩ := a
end
|
702a6b71674fbb798bf7bdab34e7c9525da1b9dc | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/sesquilinear_form.lean | 90ed4b404fe954dbf4591bfb838761ea1b9e959b | [
"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 | 27,293 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andreas Swerdlow
-/
import algebra.module.linear_map
import linear_algebra.bilinear_map
import linear_algebra.matrix.basis
import linear_algebra.linear_pmap
/-!
# Sesquilinear form
This files provides properties about sesquilinear forms. The maps considered are of the form
`M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R`, where `I₁ : R₁ →+* R` and `I₂ : R₂ →+* R` are ring homomorphisms and
`M₁` is a module over `R₁` and `M₂` is a module over `R₂`.
Sesquilinear forms are the special case that `M₁ = M₂`, `R₁ = R₂ = R`, and `I₁ = ring_hom.id R`.
Taking additionally `I₂ = ring_hom.id R`, then one obtains bilinear forms.
These forms are a special case of the bilinear maps defined in `bilinear_map.lean` and all basic
lemmas about construction and elementary calculations are found there.
## Main declarations
* `is_ortho`: states that two vectors are orthogonal with respect to a sesquilinear form
* `is_symm`, `is_alt`: states that a sesquilinear form is symmetric and alternating, respectively
* `orthogonal_bilin`: provides the orthogonal complement with respect to sesquilinear form
## References
* <https://en.wikipedia.org/wiki/Sesquilinear_form#Over_arbitrary_rings>
## Tags
Sesquilinear form,
-/
open_locale big_operators
variables {R R₁ R₂ R₃ M M₁ M₂ K K₁ K₂ V V₁ V₂ n: Type*}
namespace linear_map
/-! ### Orthogonal vectors -/
section comm_ring
-- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps
variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁]
[comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
{I₁ : R₁ →+* R} {I₂ : R₂ →+* R} {I₁' : R₁ →+* R}
/-- The proposition that two elements of a sesquilinear form space are orthogonal -/
def is_ortho (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x y) : Prop := B x y = 0
lemma is_ortho_def {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} {x y} : B.is_ortho x y ↔ B x y = 0 := iff.rfl
lemma is_ortho_zero_left (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x) : is_ortho B (0 : M₁) x :=
by { dunfold is_ortho, rw [ map_zero B, zero_apply] }
lemma is_ortho_zero_right (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) (x) : is_ortho B x (0 : M₂) :=
map_zero (B x)
lemma is_ortho_flip {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R} {x y} :
B.is_ortho x y ↔ B.flip.is_ortho y x :=
by simp_rw [is_ortho_def, flip_apply]
/-- A set of vectors `v` is orthogonal with respect to some bilinear form `B` if and only
if for all `i ≠ j`, `B (v i) (v j) = 0`. For orthogonality between two elements, use
`bilin_form.is_ortho` -/
def is_Ortho (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R) (v : n → M₁) : Prop :=
pairwise (B.is_ortho on v)
lemma is_Ortho_def {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R} {v : n → M₁} :
B.is_Ortho v ↔ ∀ i j : n, i ≠ j → B (v i) (v j) = 0 := iff.rfl
lemma is_Ortho_flip (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₁'] R) {v : n → M₁} :
B.is_Ortho v ↔ B.flip.is_Ortho v :=
begin
simp_rw is_Ortho_def,
split; intros h i j hij,
{ rw flip_apply,
exact h j i (ne.symm hij) },
simp_rw flip_apply at h,
exact h j i (ne.symm hij),
end
end comm_ring
section field
variables [field K] [field K₁] [add_comm_group V₁] [module K₁ V₁]
[field K₂] [add_comm_group V₂] [module K₂ V₂]
{I₁ : K₁ →+* K} {I₂ : K₂ →+* K} {I₁' : K₁ →+* K}
{J₁ : K →+* K} {J₂ : K →+* K}
-- todo: this also holds for [comm_ring R] [is_domain R] when J₁ is invertible
lemma ortho_smul_left {B : V₁ →ₛₗ[I₁] V₂ →ₛₗ[I₂] K} {x y} {a : K₁} (ha : a ≠ 0) :
(is_ortho B x y) ↔ (is_ortho B (a • x) y) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [map_smulₛₗ₂, H, smul_zero]},
{ rw [map_smulₛₗ₂, smul_eq_zero] at H,
cases H,
{ rw map_eq_zero I₁ at H, trivial },
{ exact H }}
end
-- todo: this also holds for [comm_ring R] [is_domain R] when J₂ is invertible
lemma ortho_smul_right {B : V₁ →ₛₗ[I₁] V₂ →ₛₗ[I₂] K} {x y} {a : K₂} {ha : a ≠ 0} :
(is_ortho B x y) ↔ (is_ortho B x (a • y)) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [map_smulₛₗ, H, smul_zero] },
{ rw [map_smulₛₗ, smul_eq_zero] at H,
cases H,
{ simp at H,
exfalso,
exact ha H },
{ exact H }}
end
/-- A set of orthogonal vectors `v` with respect to some sesquilinear form `B` is linearly
independent if for all `i`, `B (v i) (v i) ≠ 0`. -/
lemma linear_independent_of_is_Ortho {B : V₁ →ₛₗ[I₁] V₁ →ₛₗ[I₁'] K} {v : n → V₁}
(hv₁ : B.is_Ortho v) (hv₂ : ∀ i, ¬ B.is_ortho (v i) (v i)) : linear_independent K₁ v :=
begin
classical,
rw linear_independent_iff',
intros s w hs i hi,
have : B (s.sum $ λ (i : n), w i • v i) (v i) = 0,
{ rw [hs, map_zero, zero_apply] },
have hsum : s.sum (λ (j : n), I₁(w j) * B (v j) (v i)) = I₁(w i) * B (v i) (v i),
{ apply finset.sum_eq_single_of_mem i hi,
intros j hj hij,
rw [is_Ortho_def.1 hv₁ _ _ hij, mul_zero], },
simp_rw [B.map_sum₂, map_smulₛₗ₂, smul_eq_mul, hsum] at this,
apply (map_eq_zero I₁).mp,
exact eq_zero_of_ne_zero_of_mul_right_eq_zero (hv₂ i) this,
end
end field
/-! ### Reflexive bilinear forms -/
section reflexive
variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁]
{I₁ : R₁ →+* R} {I₂ : R₁ →+* R}
{B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R}
/-- The proposition that a sesquilinear form is reflexive -/
def is_refl (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : Prop :=
∀ (x y), B x y = 0 → B y x = 0
namespace is_refl
variable (H : B.is_refl)
lemma eq_zero : ∀ {x y}, B x y = 0 → B y x = 0 := λ x y, H x y
lemma ortho_comm {x y} : is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩
lemma dom_restrict_refl (H : B.is_refl) (p : submodule R₁ M₁) : (B.dom_restrict₁₂ p p).is_refl :=
λ _ _, by { simp_rw dom_restrict₁₂_apply, exact H _ _}
@[simp] lemma flip_is_refl_iff : B.flip.is_refl ↔ B.is_refl :=
⟨λ h x y H, h y x ((B.flip_apply _ _).trans H), λ h x y, h y x⟩
lemma ker_flip_eq_bot (H : B.is_refl) (h : B.ker = ⊥) : B.flip.ker = ⊥ :=
begin
refine ker_eq_bot'.mpr (λ _ hx, ker_eq_bot'.mp h _ _),
ext,
exact H _ _ (linear_map.congr_fun hx _),
end
lemma ker_eq_bot_iff_ker_flip_eq_bot (H : B.is_refl) : B.ker = ⊥ ↔ B.flip.ker = ⊥ :=
begin
refine ⟨ker_flip_eq_bot H, λ h, _⟩,
exact (congr_arg _ B.flip_flip.symm).trans (ker_flip_eq_bot (flip_is_refl_iff.mpr H) h),
end
end is_refl
end reflexive
/-! ### Symmetric bilinear forms -/
section symmetric
variables [comm_semiring R] [add_comm_monoid M] [module R M]
{I : R →+* R} {B : M →ₛₗ[I] M →ₗ[R] R}
/-- The proposition that a sesquilinear form is symmetric -/
def is_symm (B : M →ₛₗ[I] M →ₗ[R] R) : Prop :=
∀ (x y), I (B x y) = B y x
namespace is_symm
protected lemma eq (H : B.is_symm) (x y) : I (B x y) = B y x := H x y
lemma is_refl (H : B.is_symm) : B.is_refl := λ x y H1, by { rw ←H.eq, simp [H1] }
lemma ortho_comm (H : B.is_symm) {x y} : is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm
lemma dom_restrict_symm (H : B.is_symm) (p : submodule R M) : (B.dom_restrict₁₂ p p).is_symm :=
λ _ _, by { simp_rw dom_restrict₁₂_apply, exact H _ _}
end is_symm
lemma is_symm_iff_eq_flip {B : M →ₗ[R] M →ₗ[R] R} : B.is_symm ↔ B = B.flip :=
begin
split; intro h,
{ ext,
rw [←h, flip_apply, ring_hom.id_apply] },
intros x y,
conv_lhs { rw h },
rw [flip_apply, ring_hom.id_apply],
end
end symmetric
/-! ### Alternating bilinear forms -/
section alternating
variables [comm_ring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁]
{I₁ : R₁ →+* R} {I₂ : R₁ →+* R} {I : R₁ →+* R} {B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R}
/-- The proposition that a sesquilinear form is alternating -/
def is_alt (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : Prop := ∀ x, B x x = 0
namespace is_alt
variable (H : B.is_alt)
include H
lemma self_eq_zero (x) : B x x = 0 := H x
lemma neg (x y) : - B x y = B y x :=
begin
have H1 : B (y + x) (y + x) = 0,
{ exact self_eq_zero H (y + x) },
simp [map_add, self_eq_zero H] at H1,
rw [add_eq_zero_iff_neg_eq] at H1,
exact H1,
end
lemma is_refl : B.is_refl :=
begin
intros x y h,
rw [←neg H, h, neg_zero],
end
lemma ortho_comm {x y} : is_ortho B x y ↔ is_ortho B y x := H.is_refl.ortho_comm
end is_alt
lemma is_alt_iff_eq_neg_flip [no_zero_divisors R] [char_zero R] {B : M₁ →ₛₗ[I] M₁ →ₛₗ[I] R} :
B.is_alt ↔ B = -B.flip :=
begin
split; intro h,
{ ext,
simp_rw [neg_apply, flip_apply],
exact (h.neg _ _).symm },
intros x,
let h' := congr_fun₂ h x x,
simp only [neg_apply, flip_apply, ←add_eq_zero_iff_eq_neg] at h',
exact add_self_eq_zero.mp h',
end
end alternating
end linear_map
namespace submodule
/-! ### The orthogonal complement -/
variables [comm_ring R] [comm_ring R₁] [add_comm_group M₁] [module R₁ M₁]
{I₁ : R₁ →+* R} {I₂ : R₁ →+* R}
{B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R}
/-- The orthogonal complement of a submodule `N` with respect to some bilinear form is the set of
elements `x` which are orthogonal to all elements of `N`; i.e., for all `y` in `N`, `B x y = 0`.
Note that for general (neither symmetric nor antisymmetric) bilinear forms this definition has a
chirality; in addition to this "left" orthogonal complement one could define a "right" orthogonal
complement for which, for all `y` in `N`, `B y x = 0`. This variant definition is not currently
provided in mathlib. -/
def orthogonal_bilin (N : submodule R₁ M₁) (B : M₁ →ₛₗ[I₁] M₁ →ₛₗ[I₂] R) : submodule R₁ M₁ :=
{ carrier := { m | ∀ n ∈ N, B.is_ortho n m },
zero_mem' := λ x _, B.is_ortho_zero_right x,
add_mem' := λ x y hx hy n hn,
by rw [linear_map.is_ortho, map_add, show B n x = 0, by exact hx n hn,
show B n y = 0, by exact hy n hn, zero_add],
smul_mem' := λ c x hx n hn,
by rw [linear_map.is_ortho, linear_map.map_smulₛₗ, show B n x = 0, by exact hx n hn,
smul_zero] }
variables {N L : submodule R₁ M₁}
@[simp] lemma mem_orthogonal_bilin_iff {m : M₁} :
m ∈ N.orthogonal_bilin B ↔ ∀ n ∈ N, B.is_ortho n m := iff.rfl
lemma orthogonal_bilin_le (h : N ≤ L) : L.orthogonal_bilin B ≤ N.orthogonal_bilin B :=
λ _ hn l hl, hn l (h hl)
lemma le_orthogonal_bilin_orthogonal_bilin (b : B.is_refl) :
N ≤ (N.orthogonal_bilin B).orthogonal_bilin B :=
λ n hn m hm, b _ _ (hm n hn)
end submodule
namespace linear_map
section orthogonal
variables [field K] [add_comm_group V] [module K V]
[field K₁] [add_comm_group V₁] [module K₁ V₁]
{J : K →+* K} {J₁ : K₁ →+* K} {J₁' : K₁ →+* K}
-- ↓ This lemma only applies in fields as we require `a * b = 0 → a = 0 ∨ b = 0`
lemma span_singleton_inf_orthogonal_eq_bot
(B : V₁ →ₛₗ[J₁] V₁ →ₛₗ[J₁'] K) (x : V₁) (hx : ¬ B.is_ortho x x) :
(K₁ ∙ x) ⊓ submodule.orthogonal_bilin (K₁ ∙ x) B = ⊥ :=
begin
rw ← finset.coe_singleton,
refine eq_bot_iff.2 (λ y h, _),
rcases mem_span_finset.1 h.1 with ⟨μ, rfl⟩,
have := h.2 x _,
{ rw finset.sum_singleton at this ⊢,
suffices hμzero : μ x = 0,
{ rw [hμzero, zero_smul, submodule.mem_bot] },
change B x (μ x • x) = 0 at this, rw [map_smulₛₗ, smul_eq_mul] at this,
exact or.elim (zero_eq_mul.mp this.symm)
(λ y, by { simp at y, exact y })
(λ hfalse, false.elim $ hx hfalse) },
{ rw submodule.mem_span; exact λ _ hp, hp $ finset.mem_singleton_self _ }
end
-- ↓ This lemma only applies in fields since we use the `mul_eq_zero`
lemma orthogonal_span_singleton_eq_to_lin_ker {B : V →ₗ[K] V →ₛₗ[J] K} (x : V) :
submodule.orthogonal_bilin (K ∙ x) B = (B x).ker :=
begin
ext y,
simp_rw [submodule.mem_orthogonal_bilin_iff, linear_map.mem_ker,
submodule.mem_span_singleton ],
split,
{ exact λ h, h x ⟨1, one_smul _ _⟩ },
{ rintro h _ ⟨z, rfl⟩,
rw [is_ortho, map_smulₛₗ₂, smul_eq_zero],
exact or.intro_right _ h }
end
-- todo: Generalize this to sesquilinear maps
lemma span_singleton_sup_orthogonal_eq_top {B : V →ₗ[K] V →ₗ[K] K}
{x : V} (hx : ¬ B.is_ortho x x) :
(K ∙ x) ⊔ submodule.orthogonal_bilin (K ∙ x) B = ⊤ :=
begin
rw orthogonal_span_singleton_eq_to_lin_ker,
exact (B x).span_singleton_sup_ker_eq_top hx,
end
-- todo: Generalize this to sesquilinear maps
/-- Given a bilinear form `B` and some `x` such that `B x x ≠ 0`, the span of the singleton of `x`
is complement to its orthogonal complement. -/
lemma is_compl_span_singleton_orthogonal {B : V →ₗ[K] V →ₗ[K] K}
{x : V} (hx : ¬ B.is_ortho x x) : is_compl (K ∙ x) (submodule.orthogonal_bilin (K ∙ x) B) :=
{ disjoint := eq_bot_iff.1 $ span_singleton_inf_orthogonal_eq_bot B x hx,
codisjoint := eq_top_iff.1 $ span_singleton_sup_orthogonal_eq_top hx }
end orthogonal
/-! ### Adjoint pairs -/
section adjoint_pair
section add_comm_monoid
variables [comm_semiring R]
variables [add_comm_monoid M] [module R M]
variables [add_comm_monoid M₁] [module R M₁]
variables [add_comm_monoid M₂] [module R M₂]
variables {B F : M →ₗ[R] M →ₗ[R] R} {B' : M₁ →ₗ[R] M₁ →ₗ[R] R} {B'' : M₂ →ₗ[R] M₂ →ₗ[R] R}
variables {f f' : M →ₗ[R] M₁} {g g' : M₁ →ₗ[R] M}
variables (B B' f g)
/-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of
maps between them to be mutually adjoint. -/
def is_adjoint_pair := ∀ x y, B' (f x) y = B x (g y)
variables {B B' f g}
lemma is_adjoint_pair_iff_comp_eq_compl₂ :
is_adjoint_pair B B' f g ↔ B'.comp f = B.compl₂ g :=
begin
split; intros h,
{ ext x y, rw [comp_apply, compl₂_apply], exact h x y },
{ intros _ _, rw [←compl₂_apply, ←comp_apply, h] },
end
lemma is_adjoint_pair_zero : is_adjoint_pair B B' 0 0 :=
λ _ _, by simp only [zero_apply, map_zero]
lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl
lemma is_adjoint_pair.add (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') :
is_adjoint_pair B B' (f + f') (g + g') :=
λ x _, by rw [f.add_apply, g.add_apply, B'.map_add₂, (B x).map_add, h, h']
lemma is_adjoint_pair.comp {f' : M₁ →ₗ[R] M₂} {g' : M₂ →ₗ[R] M₁}
(h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B' B'' f' g') :
is_adjoint_pair B B'' (f'.comp f) (g.comp g') :=
λ _ _, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h]
lemma is_adjoint_pair.mul
{f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') :
is_adjoint_pair B B (f * f') (g' * g) :=
h'.comp h
end add_comm_monoid
section add_comm_group
variables [comm_ring R]
variables [add_comm_group M] [module R M]
variables [add_comm_group M₁] [module R M₁]
variables {B F : M →ₗ[R] M →ₗ[R] R} {B' : M₁ →ₗ[R] M₁ →ₗ[R] R}
variables {f f' : M →ₗ[R] M₁} {g g' : M₁ →ₗ[R] M}
lemma is_adjoint_pair.sub (h : is_adjoint_pair B B' f g) (h' : is_adjoint_pair B B' f' g') :
is_adjoint_pair B B' (f - f') (g - g') :=
λ x _, by rw [f.sub_apply, g.sub_apply, B'.map_sub₂, (B x).map_sub, h, h']
lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B' f g) :
is_adjoint_pair B B' (c • f) (c • g) :=
λ _ _, by simp only [smul_apply, map_smul, smul_eq_mul, h _ _]
end add_comm_group
end adjoint_pair
/-! ### Self-adjoint pairs-/
section selfadjoint_pair
section add_comm_monoid
variables [comm_semiring R]
variables [add_comm_monoid M] [module R M]
variables (B F : M →ₗ[R] M →ₗ[R] R)
/-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms
on the underlying module. In the case that these two forms are identical, this is the usual concept
of self adjointness. In the case that one of the forms is the negation of the other, this is the
usual concept of skew adjointness. -/
def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B F f f
/-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an
adjoint for itself. -/
protected def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f
end add_comm_monoid
section add_comm_group
variables [comm_ring R]
variables [add_comm_group M] [module R M]
variables [add_comm_group M₁] [module R M₁]
(B F : M →ₗ[R] M →ₗ[R] R)
/-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/
def is_pair_self_adjoint_submodule : submodule R (module.End R M) :=
{ carrier := { f | is_pair_self_adjoint B F f },
zero_mem' := is_adjoint_pair_zero,
add_mem' := λ f g hf hg, hf.add hg,
smul_mem' := λ c f h, h.smul c, }
/-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation
serves as an adjoint. -/
def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f)
/-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Jordan subalgebra.) -/
def self_adjoint_submodule := is_pair_self_adjoint_submodule B B
/-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Lie subalgebra.) -/
def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B
variables {B F}
@[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R M) :
f ∈ is_pair_self_adjoint_submodule B F ↔ is_pair_self_adjoint B F f :=
iff.rfl
lemma is_pair_self_adjoint_equiv (e : M₁ ≃ₗ[R] M) (f : module.End R M) :
is_pair_self_adjoint B F f ↔
is_pair_self_adjoint (B.compl₁₂ ↑e ↑e) (F.compl₁₂ ↑e ↑e) (e.symm.conj f) :=
begin
have hₗ : (F.compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M)).comp (e.symm.conj f) =
(F.comp f).compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M) :=
by { ext, simp only [linear_equiv.symm_conj_apply, coe_comp, linear_equiv.coe_coe, compl₁₂_apply,
linear_equiv.apply_symm_apply], },
have hᵣ : (B.compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M)).compl₂ (e.symm.conj f) =
(B.compl₂ f).compl₁₂ (↑e : M₁ →ₗ[R] M) (↑e : M₁ →ₗ[R] M) :=
by { ext, simp only [linear_equiv.symm_conj_apply, compl₂_apply, coe_comp, linear_equiv.coe_coe,
compl₁₂_apply, linear_equiv.apply_symm_apply] },
have he : function.surjective (⇑(↑e : M₁ →ₗ[R] M) : M₁ → M) := e.surjective,
simp_rw [is_pair_self_adjoint, is_adjoint_pair_iff_comp_eq_compl₂, hₗ, hᵣ,
compl₁₂_inj he he],
end
lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) :
B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f :=
show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y),
by simp
@[simp] lemma mem_self_adjoint_submodule (f : module.End R M) :
f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl
@[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) :
f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f :=
by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl }
end add_comm_group
end selfadjoint_pair
/-! ### Nondegenerate bilinear forms -/
section nondegenerate
section comm_semiring
variables [comm_semiring R] [comm_semiring R₁] [add_comm_monoid M₁] [module R₁ M₁]
[comm_semiring R₂] [add_comm_monoid M₂] [module R₂ M₂]
{I₁ : R₁ →+* R} {I₂ : R₂ →+* R} {I₁' : R₁ →+* R}
/-- A bilinear form is called left-separating if
the only element that is left-orthogonal to every other element is `0`; i.e.,
for every nonzero `x` in `M₁`, there exists `y` in `M₂` with `B x y ≠ 0`.-/
def separating_left (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop :=
∀ x : M₁, (∀ y : M₂, B x y = 0) → x = 0
/-- A bilinear form is called right-separating if
the only element that is right-orthogonal to every other element is `0`; i.e.,
for every nonzero `y` in `M₂`, there exists `x` in `M₁` with `B x y ≠ 0`.-/
def separating_right (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop :=
∀ y : M₂, (∀ x : M₁, B x y = 0) → y = 0
/-- A bilinear form is called non-degenerate if it is left-separating and right-separating. -/
def nondegenerate (B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R) : Prop := separating_left B ∧ separating_right B
@[simp] lemma flip_separating_right {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.flip.separating_right ↔ B.separating_left := ⟨λ hB x hy, hB x hy, λ hB x hy, hB x hy⟩
@[simp] lemma flip_separating_left {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.flip.separating_left ↔ separating_right B := by rw [←flip_separating_right, flip_flip]
@[simp] lemma flip_nondegenerate {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.flip.nondegenerate ↔ B.nondegenerate :=
iff.trans and.comm (and_congr flip_separating_right flip_separating_left)
lemma separating_left_iff_linear_nontrivial {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.separating_left ↔ ∀ x : M₁, B x = 0 → x = 0 :=
begin
split; intros h x hB,
{ let h' := h x,
simp only [hB, zero_apply, eq_self_iff_true, forall_const] at h',
exact h' },
have h' : B x = 0 := by { ext, rw [zero_apply], exact hB _ },
exact h x h',
end
lemma separating_right_iff_linear_flip_nontrivial {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.separating_right ↔ ∀ y : M₂, B.flip y = 0 → y = 0 :=
by rw [←flip_separating_left, separating_left_iff_linear_nontrivial]
/-- A bilinear form is left-separating if and only if it has a trivial kernel. -/
theorem separating_left_iff_ker_eq_bot {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.separating_left ↔ B.ker = ⊥ :=
iff.trans separating_left_iff_linear_nontrivial linear_map.ker_eq_bot'.symm
/-- A bilinear form is right-separating if and only if its flip has a trivial kernel. -/
theorem separating_right_iff_flip_ker_eq_bot {B : M₁ →ₛₗ[I₁] M₂ →ₛₗ[I₂] R} :
B.separating_right ↔ B.flip.ker = ⊥ :=
by rw [←flip_separating_left, separating_left_iff_ker_eq_bot]
end comm_semiring
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M]
{I I' : R →+* R}
lemma is_refl.nondegenerate_of_separating_left {B : M →ₗ[R] M →ₗ[R] R}
(hB : B.is_refl) (hB' : B.separating_left) : B.nondegenerate :=
begin
refine ⟨hB', _⟩,
rw [separating_right_iff_flip_ker_eq_bot, hB.ker_eq_bot_iff_ker_flip_eq_bot.mp],
rwa ←separating_left_iff_ker_eq_bot,
end
lemma is_refl.nondegenerate_of_separating_right {B : M →ₗ[R] M →ₗ[R] R}
(hB : B.is_refl) (hB' : B.separating_right) : B.nondegenerate :=
begin
refine ⟨_, hB'⟩,
rw [separating_left_iff_ker_eq_bot, hB.ker_eq_bot_iff_ker_flip_eq_bot.mpr],
rwa ←separating_right_iff_flip_ker_eq_bot,
end
/-- The restriction of a reflexive bilinear form `B` onto a submodule `W` is
nondegenerate if `W` has trivial intersection with its orthogonal complement,
that is `disjoint W (W.orthogonal_bilin B)`. -/
lemma nondegenerate_restrict_of_disjoint_orthogonal
{B : M →ₗ[R] M →ₗ[R] R} (hB : B.is_refl)
{W : submodule R M} (hW : disjoint W (W.orthogonal_bilin B)) :
(B.dom_restrict₁₂ W W).nondegenerate :=
begin
refine (hB.dom_restrict_refl W).nondegenerate_of_separating_left _,
rintro ⟨x, hx⟩ b₁,
rw [submodule.mk_eq_zero, ← submodule.mem_bot R],
refine hW ⟨hx, λ y hy, _⟩,
specialize b₁ ⟨y, hy⟩,
simp_rw [dom_restrict₁₂_apply, submodule.coe_mk] at b₁,
rw hB.ortho_comm,
exact b₁,
end
/-- An orthogonal basis with respect to a left-separating bilinear form has no self-orthogonal
elements. -/
lemma is_Ortho.not_is_ortho_basis_self_of_separating_left [nontrivial R]
{B : M →ₛₗ[I] M →ₛₗ[I'] R} {v : basis n R M} (h : B.is_Ortho v) (hB : B.separating_left)
(i : n) : ¬B.is_ortho (v i) (v i) :=
begin
intro ho,
refine v.ne_zero i (hB (v i) $ λ m, _),
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, map_sum],
apply finset.sum_eq_zero,
rintros j -,
rw map_smulₛₗ,
convert mul_zero _ using 2,
obtain rfl | hij := eq_or_ne i j,
{ exact ho },
{ exact h i j hij },
end
/-- An orthogonal basis with respect to a right-separating bilinear form has no self-orthogonal
elements. -/
lemma is_Ortho.not_is_ortho_basis_self_of_separating_right [nontrivial R]
{B : M →ₛₗ[I] M →ₛₗ[I'] R} {v : basis n R M} (h : B.is_Ortho v) (hB : B.separating_right)
(i : n) : ¬B.is_ortho (v i) (v i) :=
begin
rw is_Ortho_flip at h,
rw is_ortho_flip,
exact h.not_is_ortho_basis_self_of_separating_left (flip_separating_left.mpr hB) i,
end
/-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is left-separating
if the basis has no elements which are self-orthogonal. -/
lemma is_Ortho.separating_left_of_not_is_ortho_basis_self [no_zero_divisors R]
{B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) :
B.separating_left :=
begin
intros m hB,
obtain ⟨vi, rfl⟩ := v.repr.symm.surjective m,
rw linear_equiv.map_eq_zero_iff,
ext i,
rw [finsupp.zero_apply],
specialize hB (v i),
simp_rw [basis.repr_symm_apply, finsupp.total_apply, finsupp.sum, map_sum₂, map_smulₛₗ₂,
smul_eq_mul] at hB,
rw finset.sum_eq_single i at hB,
{ exact eq_zero_of_ne_zero_of_mul_right_eq_zero (h i) hB, },
{ intros j hj hij, convert mul_zero _ using 2, exact hO j i hij, },
{ intros hi, convert zero_mul _ using 2, exact finsupp.not_mem_support_iff.mp hi }
end
/-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is right-separating
if the basis has no elements which are self-orthogonal. -/
lemma is_Ortho.separating_right_iff_not_is_ortho_basis_self [no_zero_divisors R]
{B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) :
B.separating_right :=
begin
rw is_Ortho_flip at hO,
rw [←flip_separating_left],
refine is_Ortho.separating_left_of_not_is_ortho_basis_self v hO (λ i, _),
rw is_ortho_flip,
exact h i,
end
/-- Given an orthogonal basis with respect to a bilinear form, the bilinear form is nondegenerate
if the basis has no elements which are self-orthogonal. -/
lemma is_Ortho.nondegenerate_of_not_is_ortho_basis_self [no_zero_divisors R]
{B : M →ₗ[R] M →ₗ[R] R} (v : basis n R M) (hO : B.is_Ortho v) (h : ∀ i, ¬B.is_ortho (v i) (v i)) :
B.nondegenerate :=
⟨is_Ortho.separating_left_of_not_is_ortho_basis_self v hO h,
is_Ortho.separating_right_iff_not_is_ortho_basis_self v hO h⟩
end comm_ring
end nondegenerate
end linear_map
|
dc8d94f561f52a21916e90d3ccef34805a8e0f45 | a523fc1740c8cb84cd0fa0f4b52a760da4e32a5c | /src/missing_mathlib/set_theory/cardinal.lean | 7f93a2bad83648b0384504c8507a2243b789e7c9 | [] | no_license | abentkamp/spectral | a1aff51e85d30b296a81d256ced1d382345d3396 | 751645679ef1cb6266316349de9e492eff85484c | refs/heads/master | 1,669,994,798,064 | 1,597,591,646,000 | 1,597,591,646,000 | 287,544,072 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 956 | lean | import set_theory.cardinal
open function lattice set
local attribute [instance] classical.prop_decidable
universes u v w x
variables {α β : Type u}
namespace cardinal
lemma mk_zero_iff_empty_set (s : set α) : cardinal.mk s = 0 ↔ s = ∅ :=
begin
rw [←set.not_nonempty_iff_eq_empty, iff_not_comm, set.nonempty,
←nonempty_subtype, ←ne_zero_iff_nonempty],
refl,
end
lemma nat_add (m n : ℕ) : ((m + n : ℕ) : cardinal) = (m + n : cardinal) := nat.cast_add _ _
lemma exists_nat_of_add_eq_nat {a b : cardinal} {n : ℕ} (h : a + b = n) :
∃ k l : ℕ, a = k ∧ b = l :=
begin
rcases (@cardinal.lt_omega a).1 _ with ⟨k, hk⟩,
rcases (@cardinal.lt_omega b).1 _ with ⟨l, hl⟩,
{ use k,
use l,
cc },
{ refine ((@cardinal.add_lt_omega_iff a b).1 _).2,
rw h,
apply cardinal.nat_lt_omega },
{ refine ((@cardinal.add_lt_omega_iff a b).1 _).1,
rw h,
apply cardinal.nat_lt_omega },
end
end cardinal
|
a7506e2277c85d5716d1fb633210b0e3049a1c9d | 86d328c7fd9114507f3e8380e2b3d2f83ef6c647 | /lambda/parsing.lean | 37b5c45d2c96eb0baec03671b3de009318e19cd1 | [] | no_license | forked-from-1kasper/lambda | 05ada15e7abdaa5f453bfe3792c086f04f363f76 | 696363514f3730951a90e86474940135a2339c0b | refs/heads/master | 1,623,388,766,920 | 1,607,249,080,000 | 1,607,249,080,000 | 128,524,636 | 2 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 2,320 | lean | import data.buffer.parser
import lambda.types
open parser types
namespace parsing
def whitespaces := " \t\n\x0d".to_list
def reserved_chars :=
[' ', ',', 'λ', '(', ')', ':', '-']
def WordChar : parser char :=
sat (λ c, list.all (reserved_chars ++ whitespaces) (≠ c))
def LF := ch $ char.of_nat 10
def CR := ch $ char.of_nat 13
def Nl := CR >> LF <|> LF <|> CR
def Ws : parser unit :=
decorate_error "<whitespace>" $
many' $ one_of' whitespaces
def Word : parser string := many_char1 WordChar
def tok (s : string) := str s >> Ws
def Var : parser term := do
name ← Word,
pure $ term.var name
def Lam (Term_recur : parser term) : parser term := do
ch 'λ', many Ws,
names ← sep_by1 Ws (many_char1 WordChar),
ch ',', many Ws,
body ← Term_recur,
pure $ multi_lam names body
def App (Term : parser term) : parser term := do
head ← Term, many1 Ws,
body ← sep_by Ws Term,
pure $ multi_app head body
def parens (term : parser term) :=
term <|> (ch '(' >> term <* ch ')')
def Term_core : parser term → parser term
| Term_recur :=
parens $
Lam (parens Term_recur) <|>
App (parens Term_recur) <|>
Var
def Term := fix Term_core
def Let : parser (string × term) := do
tok "let",
name ← Word, many1 Ws,
tok ":=", body ← Term,
pure (name, body)
def Numeral : parser char :=
sat $ λ c, list.any "0123456789".to_list (= c)
def Number := many_char1 Numeral
def Command_line : parser repl_command :=
str ":quit" >> pure repl_command.quit <|>
str ":help" >> pure repl_command.help <|>
str ":env" >> pure repl_command.env <|>
str ":depth" >> Ws >> Number >>=
(pure ∘ repl_command.depth ∘ string.to_nat) <|>
str ":import_depth" >> Ws >> Number >>=
(pure ∘ repl_command.import_depth ∘ string.to_nat) <|>
str ":show_depth" >> pure repl_command.show_depth <|>
str ":show_import_depth" >> pure repl_command.show_import_depth <|>
str ":clear_env" >> pure repl_command.clear_env <|>
str ":load" >> Ws >> Word >>= (pure ∘ repl_command.load) <|>
Let >>= (pure ∘ function.uncurry repl_command.bind) <|>
Term >>= (pure ∘ repl_command.term) <|>
many Ws >> pure repl_command.nothing
def Command : parser repl_command := do
cmd ← Command_line,
optional (str "--" >> optional Ws >> many (sat (λ _, tt))),
optional $ many Ws,
pure cmd
end parsing
|
010590f4e3440430c31ad1d0bc295a73b94dc8ee | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/group_with_zero/units/lemmas.lean | 2f0ecc5d24a700a3cf563704abe079761c940ac0 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 7,558 | lean | /-
Copyright (c) 2020 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import algebra.group_with_zero.commute
import algebra.hom.units
import group_theory.group_action.units
/-!
# Further lemmas about units in a `monoid_with_zero` or a `group_with_zero`.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
variables {α M₀ G₀ M₀' G₀' F F' : Type*}
variables [monoid_with_zero M₀]
section group_with_zero
variables [group_with_zero G₀] {a b c : G₀}
@[simp] lemma div_self (h : a ≠ 0) : a / a = 1 := h.is_unit.div_self
lemma eq_mul_inv_iff_mul_eq₀ (hc : c ≠ 0) : a = b * c⁻¹ ↔ a * c = b :=
hc.is_unit.eq_mul_inv_iff_mul_eq
lemma eq_inv_mul_iff_mul_eq₀ (hb : b ≠ 0) : a = b⁻¹ * c ↔ b * a = c :=
hb.is_unit.eq_inv_mul_iff_mul_eq
lemma inv_mul_eq_iff_eq_mul₀ (ha : a ≠ 0) : a⁻¹ * b = c ↔ b = a * c :=
ha.is_unit.inv_mul_eq_iff_eq_mul
lemma mul_inv_eq_iff_eq_mul₀ (hb : b ≠ 0) : a * b⁻¹ = c ↔ a = c * b :=
hb.is_unit.mul_inv_eq_iff_eq_mul
lemma mul_inv_eq_one₀ (hb : b ≠ 0) : a * b⁻¹ = 1 ↔ a = b := hb.is_unit.mul_inv_eq_one
lemma inv_mul_eq_one₀ (ha : a ≠ 0) : a⁻¹ * b = 1 ↔ a = b := ha.is_unit.inv_mul_eq_one
lemma mul_eq_one_iff_eq_inv₀ (hb : b ≠ 0) : a * b = 1 ↔ a = b⁻¹ := hb.is_unit.mul_eq_one_iff_eq_inv
lemma mul_eq_one_iff_inv_eq₀ (ha : a ≠ 0) : a * b = 1 ↔ a⁻¹ = b := ha.is_unit.mul_eq_one_iff_inv_eq
@[simp] lemma div_mul_cancel (a : G₀) (h : b ≠ 0) : a / b * b = a := h.is_unit.div_mul_cancel _
@[simp] lemma mul_div_cancel (a : G₀) (h : b ≠ 0) : a * b / b = a := h.is_unit.mul_div_cancel _
lemma mul_one_div_cancel (h : a ≠ 0) : a * (1 / a) = 1 := h.is_unit.mul_one_div_cancel
lemma one_div_mul_cancel (h : a ≠ 0) : (1 / a) * a = 1 := h.is_unit.one_div_mul_cancel
lemma div_left_inj' (hc : c ≠ 0) : a / c = b / c ↔ a = b := hc.is_unit.div_left_inj
@[field_simps] lemma div_eq_iff (hb : b ≠ 0) : a / b = c ↔ a = c * b := hb.is_unit.div_eq_iff
@[field_simps] lemma eq_div_iff (hb : b ≠ 0) : c = a / b ↔ c * b = a := hb.is_unit.eq_div_iff
lemma div_eq_iff_mul_eq (hb : b ≠ 0) : a / b = c ↔ c * b = a := hb.is_unit.div_eq_iff.trans eq_comm
lemma eq_div_iff_mul_eq (hc : c ≠ 0) : a = b / c ↔ a * c = b := hc.is_unit.eq_div_iff
lemma div_eq_of_eq_mul (hb : b ≠ 0) : a = c * b → a / b = c := hb.is_unit.div_eq_of_eq_mul
lemma eq_div_of_mul_eq (hc : c ≠ 0) : a * c = b → a = b / c := hc.is_unit.eq_div_of_mul_eq
lemma div_eq_one_iff_eq (hb : b ≠ 0) : a / b = 1 ↔ a = b := hb.is_unit.div_eq_one_iff_eq
lemma div_mul_left (hb : b ≠ 0) : b / (a * b) = 1 / a := hb.is_unit.div_mul_left
lemma mul_div_mul_right (a b : G₀) (hc : c ≠ 0) : (a * c) / (b * c) = a / b :=
hc.is_unit.mul_div_mul_right _ _
lemma mul_mul_div (a : G₀) (hb : b ≠ 0) : a = a * b * (1 / b) := (hb.is_unit.mul_mul_div _).symm
lemma div_div_div_cancel_right (a : G₀) (hc : c ≠ 0) : (a / c) / (b / c) = a / b :=
by rw [div_div_eq_mul_div, div_mul_cancel _ hc]
lemma div_mul_div_cancel (a : G₀) (hc : c ≠ 0) : (a / c) * (c / b) = a / b :=
by rw [← mul_div_assoc, div_mul_cancel _ hc]
lemma div_mul_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a / b * b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (div_mul_cancel a)
lemma mul_div_cancel_of_imp {a b : G₀} (h : b = 0 → a = 0) : a * b / b = a :=
classical.by_cases (λ hb : b = 0, by simp [*]) (mul_div_cancel a)
@[simp] theorem divp_mk0 (a : G₀) {b : G₀} (hb : b ≠ 0) :
a /ₚ units.mk0 b hb = a / b :=
divp_eq_div _ _
end group_with_zero
section comm_group_with_zero -- comm
variables [comm_group_with_zero G₀] {a b c d : G₀}
lemma div_mul_right (b : G₀) (ha : a ≠ 0) : a / (a * b) = 1 / b := ha.is_unit.div_mul_right _
lemma mul_div_cancel_left_of_imp {a b : G₀} (h : a = 0 → b = 0) : a * b / a = b :=
by rw [mul_comm, mul_div_cancel_of_imp h]
lemma mul_div_cancel_left (b : G₀) (ha : a ≠ 0) : a * b / a = b := ha.is_unit.mul_div_cancel_left _
lemma mul_div_cancel_of_imp' {a b : G₀} (h : b = 0 → a = 0) : b * (a / b) = a :=
by rw [mul_comm, div_mul_cancel_of_imp h]
lemma mul_div_cancel' (a : G₀) (hb : b ≠ 0) : b * (a / b) = a := hb.is_unit.mul_div_cancel' _
lemma mul_div_mul_left (a b : G₀) (hc : c ≠ 0) : (c * a) / (c * b) = a / b :=
hc.is_unit.mul_div_mul_left _ _
lemma mul_eq_mul_of_div_eq_div (a : G₀) {b : G₀} (c : G₀) {d : G₀} (hb : b ≠ 0) (hd : d ≠ 0)
(h : a / b = c / d) : a * d = c * b :=
by rw [←mul_one a, ←div_self hb, ←mul_comm_div, h, div_mul_eq_mul_div, div_mul_cancel _ hd]
@[field_simps] lemma div_eq_div_iff (hb : b ≠ 0) (hd : d ≠ 0) : a / b = c / d ↔ a * d = c * b :=
hb.is_unit.div_eq_div_iff hd.is_unit
lemma div_div_cancel' (ha : a ≠ 0) : a / (a / b) = b := ha.is_unit.div_div_cancel
lemma div_div_cancel_left' (ha : a ≠ 0) : a / b / a = b⁻¹ := ha.is_unit.div_div_cancel_left
lemma div_helper (b : G₀) (h : a ≠ 0) : 1 / (a * b) * a = 1 / b :=
by rw [div_mul_eq_mul_div, one_mul, div_mul_right _ h]
end comm_group_with_zero
section monoid_with_zero
variables [group_with_zero G₀] [nontrivial M₀]
[monoid_with_zero M₀'] [monoid_with_zero_hom_class F G₀ M₀]
[monoid_with_zero_hom_class F' G₀ M₀'] (f : F) {a : G₀}
include M₀
lemma map_ne_zero : f a ≠ 0 ↔ a ≠ 0 :=
⟨λ hfa ha, hfa $ ha.symm ▸ map_zero f, λ ha, ((is_unit.mk0 a ha).map f).ne_zero⟩
@[simp] lemma map_eq_zero : f a = 0 ↔ a = 0 := not_iff_not.1 (map_ne_zero f)
omit M₀
include M₀'
lemma eq_on_inv₀ (f g : F') (h : f a = g a) : f a⁻¹ = g a⁻¹ :=
begin
rcases eq_or_ne a 0 with rfl|ha,
{ rw [inv_zero, map_zero, map_zero] },
{ exact (is_unit.mk0 a ha).eq_on_inv f g h }
end
end monoid_with_zero
section group_with_zero
variables [group_with_zero G₀] [group_with_zero G₀'] [monoid_with_zero_hom_class F G₀ G₀']
(f : F) (a b : G₀)
include G₀'
/-- A monoid homomorphism between groups with zeros sending `0` to `0` sends `a⁻¹` to `(f a)⁻¹`. -/
@[simp] lemma map_inv₀ : f a⁻¹ = (f a)⁻¹ :=
begin
by_cases h : a = 0, by simp [h],
apply eq_inv_of_mul_eq_one_left,
rw [← map_mul, inv_mul_cancel h, map_one]
end
@[simp] lemma map_div₀ : f (a / b) = f a / f b := map_div' f (map_inv₀ f) a b
end group_with_zero
/-- We define the inverse as a `monoid_with_zero_hom` by extending the inverse map by zero
on non-units. -/
noncomputable
def monoid_with_zero.inverse {M : Type*} [comm_monoid_with_zero M] :
M →*₀ M :=
{ to_fun := ring.inverse,
map_zero' := ring.inverse_zero _,
map_one' := ring.inverse_one _,
map_mul' := λ x y, (ring.mul_inverse_rev x y).trans (mul_comm _ _) }
@[simp]
lemma monoid_with_zero.coe_inverse {M : Type*} [comm_monoid_with_zero M] :
(monoid_with_zero.inverse : M → M) = ring.inverse := rfl
@[simp]
lemma monoid_with_zero.inverse_apply {M : Type*} [comm_monoid_with_zero M] (a : M) :
monoid_with_zero.inverse a = ring.inverse a := rfl
/-- Inversion on a commutative group with zero, considered as a monoid with zero homomorphism. -/
def inv_monoid_with_zero_hom {G₀ : Type*} [comm_group_with_zero G₀] : G₀ →*₀ G₀ :=
{ map_zero' := inv_zero,
..inv_monoid_hom }
namespace units
variables [group_with_zero G₀]
variables {a b : G₀}
@[simp] lemma smul_mk0 {α : Type*} [has_smul G₀ α] {g : G₀} (hg : g ≠ 0) (a : α) :
(mk0 g hg) • a = g • a :=
rfl
end units
|
a2d9d127a3c9873095c03bbed46119215c67eb1c | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /test/linarith.lean | 365273aecad63b8038966ce022d7348a2f12e3cf | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 11,319 | lean | import tactic.linarith
example : ∀ (y : ℕ), y ≤ 37 → y < 40 :=
begin
refine λ y hy, _,
-- The type of `hy` is a (solved but not instantiated) metavariable
do { tactic.get_local `hy >>= tactic.infer_type >>= guardb ∘ expr.is_mvar },
-- But linarith should still work
linarith
end
example {α : Type} (_inst : Π (a : Prop), decidable a)
[linear_ordered_field α]
{a b c : α}
(ha : a < 0)
(hb : ¬b = 0)
(hc' : c = 0)
(h : (1 - a) * (b * b) ≤ 0)
(hc : 0 ≤ 0)
(this : -(a * -b * -b + b * -b + 0) = (1 - a) * (b * b))
(h : (1 - a) * (b * b) ≤ 0) :
0 < 1 - a :=
begin
linarith
end
example (e b c a v0 v1 : ℚ) (h1 : v0 = 5*a) (h2 : v1 = 3*b) (h3 : v0 + v1 + c = 10) :
v0 + 5 + (v1 - 3) + (c - 2) = 10 :=
by linarith
example (u v r s t : ℚ) (h : 0 < u*(t*v + t*r + s)) : 0 < (t*(r + v) + s)*3*u :=
by linarith
example (A B : ℚ) (h : 0 < A * B) : 0 < 8*A*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*8*B :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A*B/8 :=
begin
linarith
end
example (A B : ℚ) (h : 0 < A * B) : 0 < A/8*B :=
begin
linarith
end
example (ε : ℚ) (h1 : ε > 0) : ε / 2 + ε / 3 + ε / 7 < ε :=
by linarith
example (x y z : ℚ) (h1 : 2*x < 3*y) (h2 : -4*x + z/2 < 0)
(h3 : 12*y - z < 0) : false :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 2 < ε :=
by linarith
example (ε : ℚ) (h1 : ε > 0) : ε / 3 + ε / 3 + ε / 3 = ε :=
by linarith
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith {discharger := `[ring]}
example (a b c : ℚ) (h2 : b + 2 > 3 + b) : false :=
by linarith
example (a b c : ℚ) (x y : ℤ) (h1 : x ≤ 3*y) (h2 : b + 2 > 3 + b) : false :=
by linarith {restrict_type := ℚ}
example (g v V c h : ℚ) (h1 : h = 0) (h2 : v = V) (h3 : V > 0) (h4 : g > 0)
(h5 : 0 ≤ c) (h6 : c < 1) :
v ≤ V :=
by linarith
constant nat.prime : ℕ → Prop
example (x y z : ℚ) (h1 : 2*x + ((-3)*y) < 0) (h2 : (-4)*x + 2*z < 0)
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℚ) (h1 : 2*1*x + (3)*(y*(-1)) < 0) (h2 : (-2)*x*2 < -(z + z))
(h3 : 12*y + (-4)* z < 0) (h4 : nat.prime 7) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5)
(h3 : 12*y - 4* z < 0) : false :=
by linarith
example (x y z : ℤ) (h1 : 2*x < 3*y) (h2 : -4*x + 2*z < 0) (h3 : x*y < 5) :
¬ 12*y - 4* z < 0 :=
by linarith
example (w x y z : ℤ) (h1 : 4*x + (-3)*y + 6*w ≤ 0) (h2 : (-1)*x < 0)
(h3 : y < 0) (h4 : w ≥ 0) (h5 : nat.prime x.nat_abs) : false :=
by linarith
example (a b c : ℚ) (h1 : a > 0) (h2 : b > 5) (h3 : c < -10)
(h4 : a + b - c < 3) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : ¬ b ≥ 0) : false :=
by linarith
example (a b c : ℚ) (h2 : (2 : ℚ) > 3) : a + b - c ≥ 3 :=
by linarith {exfalso := ff}
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith [rat.num_pos_iff_pos.mpr hx, h]
example (x : ℚ) (hx : x > 0) (h : x.num < 0) : false :=
by linarith only [rat.num_pos_iff_pos.mpr hx, h]
example (x y z : ℚ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℕ) (hx : x ≤ 3*y) (h2 : y ≤ 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (x y z : ℚ) (hx : ¬ x > 3*y) (h2 : ¬ y > 2*z) (h3 : x ≥ 6*z) : x = 3*y :=
by linarith
example (h1 : (1 : ℕ) < 1) : false :=
by linarith
example (a b c : ℚ) (h2 : b > 0) (h3 : b < 0) : nat.prime 10 :=
by linarith
example (a b c : ℕ) : a + b ≥ a :=
by linarith
example (a b c : ℕ) : ¬ a + b < a :=
by linarith
example (x y : ℚ) (h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3) (h' : (x + 4) * x ≥ 0)
(h'' : (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (x y : ℚ)
(h : 6 + ((x + 4) * x + (6 + 3 * y) * y) = 3 ∧ (x + 4) * x ≥ 0 ∧ (6 + 3 * y) * y ≥ 0) : false :=
by linarith
example (a b i : ℕ) (h1 : ¬ a < i) (h2 : b < i) (h3 : a ≤ b) : false :=
by linarith
example (n : ℕ) (h1 : n ≤ 3) (h2 : n > 2) : n = 3 := by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) (h2 : ¬ z + 1 ≤ 2) : false :=
by linarith
example (z : ℕ) (hz : ¬ z ≥ 2) : z + 1 ≤ 2 :=
by linarith
example (a b c : ℚ) (h1 : 1 / a < b) (h2 : b < c) : 1 / a < c :=
by linarith
example
(N : ℕ) (n : ℕ) (Hirrelevant : n > N)
(A : ℚ) (l : ℚ) (h : A - l ≤ -(A - l)) (h_1 : ¬A ≤ -A) (h_2 : ¬l ≤ -l)
(h_3 : -(A - l) < 1) : A < l + 1 := by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
d ≤ ((q : ℚ) - 1)*n :=
by linarith
example (d : ℚ) (q n : ℕ) (h1 : ((q : ℚ) - 1)*n ≥ 0) (h2 : d = 2/3*(((q : ℚ) - 1)*n)) :
((q : ℚ) - 1)*n - d = 1/3 * (((q : ℚ) - 1)*n) :=
by linarith
example (a : ℚ) (ha : 0 ≤ a) : 0 * 0 ≤ 2 * a :=
by linarith
example (x : ℚ) : id x ≥ x :=
by success_if_fail {linarith}; linarith!
example (x y z : ℚ) (hx : x < 5) (hx2 : x > 5) (hy : y < 5000000000) (hz : z > 34*y) : false :=
by linarith only [hx, hx2]
example (x y z : ℚ) (hx : x < 5) (hy : y < 5000000000) (hz : z > 34*y) : x ≤ 5 :=
by linarith only [hx]
example (x y : ℚ) (h : x < y) : x ≠ y := by linarith
example (x y : ℚ) (h : x < y) : ¬ x = y := by linarith
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
u * y + v * x + u * v < 3 * A * B :=
by nlinarith
example (u v x y A B : ℚ) : (0 < A) → (A ≤ 1) → (1 ≤ B)
→ (x ≤ B) → ( y ≤ B)
→ (0 ≤ u ) → (0 ≤ v )
→ (u < A) → ( v < A)
→ (u * y + v * x + u * v < 3 * A * B) :=
begin
intros,
nlinarith
end
example (a b c z : ℚ) (_ : a ≤ z) (E0 : b ≤ c) (E1 : c ≤ a) (E2 : 0 ≤ c) : b ≤ a + c := by linarith
example (u v x y A B : ℚ)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 ≤ A * (1 - A))
→ (0 ≤ A * (B - 1))
→ (0 < A * (A - u))
→ (0 ≤ (B - 1) * (A - u))
→ (0 ≤ (B - 1) * (A - v))
→ (0 ≤ (B - x) * v)
→ (0 ≤ (B - y) * u)
→ (0 ≤ u * (A - v))
→ u * y + v * x + u * v < 3 * A * B :=
begin
intros,
linarith
end
example (u v x y A B : ℚ)
(a : 0 < A)
(a_1 : 0 <= 1 - A)
(a_2 : 0 <= B - 1)
(a_3 : 0 <= B - x)
(a_4 : 0 <= B - y)
(a_5 : 0 <= u)
(a_6 : 0 <= v)
(a_7 : 0 < A - u)
(a_8 : 0 < A - v) :
(0 < A * A)
-> (0 <= A * (1 - A))
-> (0 <= A * (B - 1))
-> (0 <= A * (B - x))
-> (0 <= A * (B - y))
-> (0 <= A * u)
-> (0 <= A * v)
-> (0 < A * (A - u))
-> (0 < A * (A - v))
-> (0 <= (1 - A) * A)
-> (0 <= (1 - A) * (1 - A))
-> (0 <= (1 - A) * (B - 1))
-> (0 <= (1 - A) * (B - x))
-> (0 <= (1 - A) * (B - y))
-> (0 <= (1 - A) * u)
-> (0 <= (1 - A) * v)
-> (0 <= (1 - A) * (A - u))
-> (0 <= (1 - A) * (A - v))
-> (0 <= (B - 1) * A)
-> (0 <= (B - 1) * (1 - A))
-> (0 <= (B - 1) * (B - 1))
-> (0 <= (B - 1) * (B - x))
-> (0 <= (B - 1) * (B - y))
-> (0 <= (B - 1) * u)
-> (0 <= (B - 1) * v)
-> (0 <= (B - 1) * (A - u))
-> (0 <= (B - 1) * (A - v))
-> (0 <= (B - x) * A)
-> (0 <= (B - x) * (1 - A))
-> (0 <= (B - x) * (B - 1))
-> (0 <= (B - x) * (B - x))
-> (0 <= (B - x) * (B - y))
-> (0 <= (B - x) * u)
-> (0 <= (B - x) * v)
-> (0 <= (B - x) * (A - u))
-> (0 <= (B - x) * (A - v))
-> (0 <= (B - y) * A)
-> (0 <= (B - y) * (1 - A))
-> (0 <= (B - y) * (B - 1))
-> (0 <= (B - y) * (B - x))
-> (0 <= (B - y) * (B - y))
-> (0 <= (B - y) * u)
-> (0 <= (B - y) * v)
-> (0 <= (B - y) * (A - u))
-> (0 <= (B - y) * (A - v))
-> (0 <= u * A)
-> (0 <= u * (1 - A))
-> (0 <= u * (B - 1))
-> (0 <= u * (B - x))
-> (0 <= u * (B - y))
-> (0 <= u * u)
-> (0 <= u * v)
-> (0 <= u * (A - u))
-> (0 <= u * (A - v))
-> (0 <= v * A)
-> (0 <= v * (1 - A))
-> (0 <= v * (B - 1))
-> (0 <= v * (B - x))
-> (0 <= v * (B - y))
-> (0 <= v * u)
-> (0 <= v * v)
-> (0 <= v * (A - u))
-> (0 <= v * (A - v))
-> (0 < (A - u) * A)
-> (0 <= (A - u) * (1 - A))
-> (0 <= (A - u) * (B - 1))
-> (0 <= (A - u) * (B - x))
-> (0 <= (A - u) * (B - y))
-> (0 <= (A - u) * u)
-> (0 <= (A - u) * v)
-> (0 < (A - u) * (A - u))
-> (0 < (A - u) * (A - v))
-> (0 < (A - v) * A)
-> (0 <= (A - v) * (1 - A))
-> (0 <= (A - v) * (B - 1))
-> (0 <= (A - v) * (B - x))
-> (0 <= (A - v) * (B - y))
-> (0 <= (A - v) * u)
-> (0 <= (A - v) * v)
-> (0 < (A - v) * (A - u))
-> (0 < (A - v) * (A - v))
->
u * y + v * x + u * v < 3 * A * B :=
begin
intros,
linarith
end
example (A B : ℚ) : (0 < A) → (1 ≤ B) → (0 < A / 8 * B) :=
begin
intros, nlinarith
end
example (x y : ℚ) : 0 ≤ x ^2 + y ^2 :=
by nlinarith
example (x y : ℚ) : 0 ≤ x*x + y*y :=
by nlinarith
example (x y : ℚ) : x = 0 → y = 0 → x*x + y*y = 0 :=
by intros; nlinarith
lemma norm_eq_zero_iff {x y : ℚ} : x * x + y * y = 0 ↔ x = 0 ∧ y = 0 :=
begin
split,
{ intro, split; nlinarith },
{ intro, nlinarith }
end
lemma norm_nonpos_right {x y : ℚ} (h1 : x * x + y * y ≤ 0) : y = 0 :=
by nlinarith
lemma norm_nonpos_left (x y : ℚ) (h1 : x * x + y * y ≤ 0) : x = 0 :=
by nlinarith
variables {E : Type*} [add_group E]
example (f : ℤ → E) (h : 0 = f 0) : 1 ≤ 2 := by nlinarith
example (a : E) (h : a = a) : 1 ≤ 2 := by nlinarith
-- test that the apply bug doesn't affect linarith preprocessing
constant α : Type
variable [fact false] -- we work in an inconsistent context below
def leα : α → α → Prop := λ a b, ∀ c : α, true
noncomputable instance : linear_ordered_field α :=
by refine_struct { le := leα }; exact (fact.out false).elim
example (a : α) (ha : a < 2) : a ≤ a :=
by linarith
example (p q r s t u v w : ℕ) (h1 : p + u = q + t) (h2 : r + w = s + v) :
p * r + q * s + (t * w + u * v) = p * s + q * r + (t * v + u * w) :=
by nlinarith
-- Tests involving a norm, including that squares in a type where `sq_nonneg` does not apply
-- do not cause an exception
variables {R : Type*} [ring R] (abs : R → ℚ)
lemma abs_nonneg' : ∀ r, 0 ≤ abs r := (fact.out false).elim
example (t : R) (a b : ℚ) (h : a ≤ b) : abs (t^2) * a ≤ abs (t^2) * b :=
by nlinarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : a ≤ abs (t^2) + b :=
by linarith [abs_nonneg' abs (t^2)]
example (t : R) (a b : ℚ) (h : a ≤ b) : abs t * a ≤ abs t * b :=
by nlinarith [abs_nonneg' abs t]
constant T : Type
attribute [instance]
constant T_zero : ordered_ring T
namespace T
lemma zero_lt_one : (0 : T) < 1 := (fact.out false).elim
lemma works {a b : ℕ} (hab : a ≤ b) (h : b < a) : false :=
begin
linarith,
end
end T
example (a b c : ℚ) (h : a ≠ b) (h3 : b ≠ c) (h2 : a ≥ b) : b ≠ c :=
by linarith {split_ne := tt}
example (a b c : ℚ) (h : a ≠ b) (h2 : a ≥ b) (h3 : b ≠ c) : a > b :=
by linarith {split_ne := tt}
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x * x := by nlinarith
example (x y : ℚ) (h₁ : 0 ≤ y) (h₂ : y ≤ x) : y * x ≤ x ^ 2 := by nlinarith
axiom foo {x : int} : 1 ≤ x → 1 ≤ x*x
lemma bar (x y: int)(h : 0 ≤ y ∧ 1 ≤ x) : 1 ≤ y + x*x := by linarith [foo h.2]
-- issue #9822
lemma mytest (j : ℕ) (h : 0 < j) : j-1 < j:=
begin
linarith,
end
|
061086cc81e781a13115b0af6db37ab8ce38594f | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/noetherian_space.lean | 18d85a615a0f175e603a8a86b43ba18c6fa8cda7 | [
"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 | 9,233 | lean | /-
Copyright (c) 2022 Andrew Yang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Andrew Yang
-/
import order.compactly_generated
import topology.sets.closeds
/-!
# Noetherian space
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
A Noetherian space is a topological space that satisfies any of the following equivalent conditions:
- `well_founded ((>) : opens α → opens α → Prop)`
- `well_founded ((<) : closeds α → closeds α → Prop)`
- `∀ s : set α, is_compact s`
- `∀ s : opens α, is_compact s`
The first is chosen as the definition, and the equivalence is shown in
`topological_space.noetherian_space_tfae`.
Many examples of noetherian spaces come from algebraic topology. For example, the underlying space
of a noetherian scheme (e.g., the spectrum of a noetherian ring) is noetherian.
## Main Results
- `noetherian_space.set`: Every subspace of a noetherian space is noetherian.
- `noetherian_space.is_compact`: Every subspace of a noetherian space is compact.
- `noetherian_space_tfae`: Describes the equivalent definitions of noetherian spaces.
- `noetherian_space.range`: The image of a noetherian space under a continuous map is noetherian.
- `noetherian_space.Union`: The finite union of noetherian spaces is noetherian.
- `noetherian_space.discrete`: A noetherian and hausdorff space is discrete.
- `noetherian_space.exists_finset_irreducible` : Every closed subset of a noetherian space is a
finite union of irreducible closed subsets.
- `noetherian_space.finite_irreducible_components `: The number of irreducible components of a
noetherian space is finite.
-/
variables (α β : Type*) [topological_space α] [topological_space β]
namespace topological_space
/-- Type class for noetherian spaces. It is defined to be spaces whose open sets satisfies ACC. -/
@[mk_iff]
class noetherian_space : Prop :=
(well_founded : well_founded ((>) : opens α → opens α → Prop))
lemma noetherian_space_iff_opens :
noetherian_space α ↔ ∀ s : opens α, is_compact (s : set α) :=
begin
rw [noetherian_space_iff, complete_lattice.well_founded_iff_is_Sup_finite_compact,
complete_lattice.is_Sup_finite_compact_iff_all_elements_compact],
exact forall_congr opens.is_compact_element_iff,
end
@[priority 100]
instance noetherian_space.compact_space [h : noetherian_space α] : compact_space α :=
⟨(noetherian_space_iff_opens α).mp h ⊤⟩
variables {α β}
protected lemma noetherian_space.is_compact [noetherian_space α] (s : set α) : is_compact s :=
begin
refine is_compact_iff_finite_subcover.2 (λ ι U hUo hs, _),
rcases ((noetherian_space_iff_opens α).mp ‹_›
⟨⋃ i, U i, is_open_Union hUo⟩).elim_finite_subcover U hUo set.subset.rfl with ⟨t, ht⟩,
exact ⟨t, hs.trans ht⟩
end
protected lemma inducing.noetherian_space [noetherian_space α] {i : β → α} (hi : inducing i) :
noetherian_space β :=
(noetherian_space_iff_opens _).2 $ λ s, hi.is_compact_iff.1 (noetherian_space.is_compact _)
instance noetherian_space.set [h : noetherian_space α] (s : set α) : noetherian_space s :=
inducing_coe.noetherian_space
variable (α)
example (α : Type*) : set α ≃o (set α)ᵒᵈ := by refine order_iso.compl (set α)
lemma noetherian_space_tfae :
tfae [noetherian_space α,
well_founded (λ s t : closeds α, s < t),
∀ s : set α, is_compact s,
∀ s : opens α, is_compact (s : set α)] :=
begin
tfae_have : 1 ↔ 2,
{ refine (noetherian_space_iff _).trans (surjective.well_founded_iff opens.compl_bijective.2 _),
exact λ s t, (order_iso.compl (set α)).lt_iff_lt.symm },
tfae_have : 1 ↔ 4,
{ exact noetherian_space_iff_opens α },
tfae_have : 1 → 3,
{ exact @noetherian_space.is_compact _ _ },
tfae_have : 3 → 4,
{ exact λ H s, H s },
tfae_finish
end
variables {α β}
instance {α} : noetherian_space (cofinite_topology α) :=
begin
simp only [noetherian_space_iff_opens, is_compact_iff_ultrafilter_le_nhds,
cofinite_topology.nhds_eq, ultrafilter.le_sup_iff],
intros s f hs,
rcases f.le_cofinite_or_eq_pure with hf|⟨a, rfl⟩,
{ rcases filter.nonempty_of_mem (filter.le_principal_iff.1 hs) with ⟨a, ha⟩,
exact ⟨a, ha, or.inr hf⟩ },
{ exact ⟨a, filter.le_principal_iff.mp hs, or.inl le_rfl⟩ }
end
lemma noetherian_space_of_surjective [noetherian_space α] (f : α → β)
(hf : continuous f) (hf' : function.surjective f) : noetherian_space β :=
begin
rw noetherian_space_iff_opens,
intro s,
obtain ⟨t, e⟩ := set.image_surjective.mpr hf' s,
exact e ▸ (noetherian_space.is_compact t).image hf,
end
lemma noetherian_space_iff_of_homeomorph (f : α ≃ₜ β) :
noetherian_space α ↔ noetherian_space β :=
⟨λ h, @@noetherian_space_of_surjective _ _ h f f.continuous f.surjective,
λ h, @@noetherian_space_of_surjective _ _ h f.symm f.symm.continuous f.symm.surjective⟩
lemma noetherian_space.range [noetherian_space α] (f : α → β) (hf : continuous f) :
noetherian_space (set.range f) :=
noetherian_space_of_surjective (set.cod_restrict f _ set.mem_range_self) (by continuity)
(λ ⟨a, b, h⟩, ⟨b, subtype.ext h⟩)
lemma noetherian_space_set_iff (s : set α) :
noetherian_space s ↔ ∀ t ⊆ s, is_compact t :=
begin
rw (noetherian_space_tfae s).out 0 2,
split,
{ intros H t ht,
have := embedding_subtype_coe.is_compact_iff_is_compact_image.mp (H (coe ⁻¹' t)),
simpa [set.inter_eq_left_iff_subset.mpr ht] using this },
{ intros H t,
refine embedding_subtype_coe.is_compact_iff_is_compact_image.mpr (H (coe '' t) _),
simp }
end
@[simp] lemma noetherian_univ_iff :
noetherian_space (set.univ : set α) ↔ noetherian_space α :=
noetherian_space_iff_of_homeomorph (homeomorph.set.univ α)
lemma noetherian_space.Union {ι : Type*} (f : ι → set α) [finite ι]
[hf : ∀ i, noetherian_space (f i)] :
noetherian_space (⋃ i, f i) :=
begin
casesI nonempty_fintype ι,
simp_rw noetherian_space_set_iff at hf ⊢,
intros t ht,
rw [← set.inter_eq_left_iff_subset.mpr ht, set.inter_Union],
exact is_compact_Union (λ i, hf i _ (set.inter_subset_right _ _))
end
-- This is not an instance since it makes a loop with `t2_space_discrete`.
lemma noetherian_space.discrete [noetherian_space α] [t2_space α] : discrete_topology α :=
⟨eq_bot_iff.mpr (λ U _, is_closed_compl_iff.mp (noetherian_space.is_compact _).is_closed)⟩
local attribute [instance] noetherian_space.discrete
/-- Spaces that are both Noetherian and Hausdorff is finite. -/
lemma noetherian_space.finite [noetherian_space α] [t2_space α] : finite α :=
begin
letI : fintype α :=
set.fintype_of_finite_univ (noetherian_space.is_compact set.univ).finite_of_discrete,
apply_instance
end
@[priority 100]
instance finite.to_noetherian_space [finite α] : noetherian_space α :=
⟨finite.well_founded_of_trans_of_irrefl _⟩
lemma noetherian_space.exists_finset_irreducible [noetherian_space α] (s : closeds α) :
∃ S : finset (closeds α), (∀ k : S, is_irreducible (k : set α)) ∧ s = S.sup id :=
begin
classical,
have := ((noetherian_space_tfae α).out 0 1).mp infer_instance,
apply well_founded.induction this s, clear s,
intros s H,
by_cases h₁ : is_preirreducible s.1,
cases h₂ : s.1.eq_empty_or_nonempty,
{ use ∅, refine ⟨λ k, k.2.elim, _⟩, rw finset.sup_empty, ext1, exact h },
{ use {s},
simp only [coe_coe, finset.sup_singleton, id.def, eq_self_iff_true, and_true],
rintro ⟨k, hk⟩,
cases finset.mem_singleton.mp hk,
exact ⟨h, h₁⟩ },
{ rw is_preirreducible_iff_closed_union_closed at h₁,
push_neg at h₁,
obtain ⟨z₁, z₂, hz₁, hz₂, h, hz₁', hz₂'⟩ := h₁,
obtain ⟨S₁, hS₁, hS₁'⟩ := H (s ⊓ ⟨z₁, hz₁⟩) (inf_lt_left.2 hz₁'),
obtain ⟨S₂, hS₂, hS₂'⟩ := H (s ⊓ ⟨z₂, hz₂⟩) (inf_lt_left.2 hz₂'),
refine ⟨S₁ ∪ S₂, λ k, _, _⟩,
{ cases finset.mem_union.mp k.2 with h' h', exacts [hS₁ ⟨k, h'⟩, hS₂ ⟨k, h'⟩] },
{ rwa [finset.sup_union, ← hS₁', ← hS₂', ← inf_sup_left, left_eq_inf] } }
end
lemma noetherian_space.finite_irreducible_components [noetherian_space α] :
(irreducible_components α).finite :=
begin
classical,
obtain ⟨S, hS₁, hS₂⟩ := noetherian_space.exists_finset_irreducible (⊤ : closeds α),
suffices : irreducible_components α ⊆ coe '' (S : set $ closeds α),
{ exact set.finite.subset ((set.finite.intro infer_instance).image _) this },
intros K hK,
obtain ⟨z, hz, hz'⟩ : ∃ (z : set α) (H : z ∈ finset.image coe S), K ⊆ z,
{ convert is_irreducible_iff_sUnion_closed.mp
hK.1 (S.image coe) _ _,
{ simp only [finset.mem_image, exists_prop, forall_exists_index, and_imp],
rintro _ z hz rfl,
exact z.2 },
{ exact (set.subset_univ _).trans ((congr_arg coe hS₂).trans $ by simp).subset } },
obtain ⟨s, hs, e⟩ := finset.mem_image.mp hz,
rw ← e at hz',
refine ⟨s, hs, _⟩,
symmetry,
suffices : K ≤ s, { exact this.antisymm (hK.2 (hS₁ ⟨s, hs⟩) this) },
simpa,
end
end topological_space
|
d367dde49680c1a7b0fde9333ab4017882ed4467 | 33340b3a23ca62ef3c8a7f6a2d4e14c07c6d3354 | /nat.lean | 3244ecc0a54c6cce6e8d5b0879749b0095c64fbc | [] | no_license | lclem/cooper | 79554e72ced343c64fed24b2d892d24bf9447dfe | 812afc6b158821f2e7dac9c91d3b6123c7a19faf | refs/heads/master | 1,607,554,257,488 | 1,578,694,133,000 | 1,578,694,133,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 964 | lean | import data.nat.gcd data.int.basic
namespace nat
lemma gt_zero_of_ne_zero (n) : n ≠ 0 → n > 0 :=
begin
intro h, cases n, exfalso, apply h, refl,
apply nat.zero_lt_succ
end
lemma mul_nonzero {m n : nat} : m ≠ 0 → n ≠ 0 → m * n ≠ 0 :=
begin
intros hm hn hc, apply hm,
apply eq.trans, apply eq.symm,
apply nat.mul_div_cancel,
apply gt_zero_of_ne_zero, apply hn,
rewrite hc, apply nat.zero_div
end
lemma lcm_nonzero (m n : nat) : m ≠ 0 → n ≠ 0 → (nat.lcm m n) ≠ 0 :=
begin
intros hm hn hc,
have h := nat.gcd_mul_lcm m n,
rewrite hc at h, rewrite mul_zero at h,
apply nat.mul_nonzero hm hn,
apply eq.symm h
end
def to_int (n : nat) : int := n
lemma le_to_int' {m n : ℕ} : m.to_int ≤ n.to_int ↔ m ≤ n :=
by simp [to_int]
lemma add_to_int' {m n : ℕ} : (m + n).to_int = m.to_int + n.to_int :=
begin simp [to_int] end
lemma to_int_to_nat {n : nat} : n.to_int.to_nat = n :=
begin simp [to_int] end
end nat
|
a3315be334c5334f0633a68908d2e978b5b9df39 | 137c667471a40116a7afd7261f030b30180468c2 | /src/topology/subset_properties.lean | cfb35e682c41704496664394bdd1b354fc34c21c | [
"Apache-2.0"
] | permissive | bragadeesh153/mathlib | 46bf814cfb1eecb34b5d1549b9117dc60f657792 | b577bb2cd1f96eb47031878256856020b76f73cd | refs/heads/master | 1,687,435,188,334 | 1,626,384,207,000 | 1,626,384,207,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 65,655 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov
-/
import topology.bases
import data.finset.order
import data.set.accumulate
/-!
# Properties of subsets of topological spaces
In this file we define various properties of subsets of a topological space, and some classes on
topological spaces.
## Main definitions
We define the following properties for sets in a topological space:
* `is_compact`: each open cover has a finite subcover. This is defined in mathlib using filters.
The main property of a compact set is `is_compact.elim_finite_subcover`.
* `is_clopen`: a set that is both open and closed.
* `is_irreducible`: a nonempty set that has contains no non-trivial pair of disjoint opens.
See also the section below in the module doc.
For each of these definitions (except for `is_clopen`), we also have a class stating that the whole
space satisfies that property:
`compact_space`, `irreducible_space`
Furthermore, we have two more classes:
* `locally_compact_space`: for every point `x`, every open neighborhood of `x` contains a compact
neighborhood of `x`. The definition is formulated in terms of the neighborhood filter.
* `sigma_compact_space`: a space that is the union of a countably many compact subspaces.
## On the definition of irreducible and connected sets/spaces
In informal mathematics, irreducible spaces are assumed to be nonempty.
We formalise the predicate without that assumption as `is_preirreducible`.
In other words, the only difference is whether the empty space counts as irreducible.
There are good reasons to consider the empty space to be “too simple to be simple”
See also https://ncatlab.org/nlab/show/too+simple+to+be+simple,
and in particular
https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions.
-/
open set filter classical topological_space
open_locale classical topological_space filter
universes u v
variables {α : Type u} {β : Type v} [topological_space α] {s t : set α}
/- compact sets -/
section compact
/-- A set `s` is compact if for every nontrivial filter `f` that contains `s`,
there exists `a ∈ s` such that every set of `f` meets every neighborhood of `a`. -/
def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f
/-- The complement to a compact set belongs to a filter `f` if it belongs to each filter
`𝓝 a ⊓ f`, `a ∈ s`. -/
lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) :
sᶜ ∈ f :=
begin
contrapose! hf,
simp only [not_mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢,
exact @hs _ hf inf_le_right
end
/-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t`
within `s` such that `tᶜ` belongs to `f`. -/
lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α}
(hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) :
sᶜ ∈ f :=
begin
refine hs.compl_mem_sets (λ a ha, _),
rcases hf a ha with ⟨t, ht, hst⟩,
replace ht := mem_inf_principal.1 ht,
refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩,
rintros x ⟨h₁, h₂⟩ hs,
exact h₂ (h₁ hs)
end
/-- If `p : set α → Prop` is stable under restriction and union, and each point `x`
of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/
@[elab_as_eliminator]
lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅)
(hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t))
(hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) :
p s :=
let f : filter α :=
{ sets := {t | p tᶜ},
univ_sets := by simpa,
sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁,
inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in
have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds),
by simpa
/-- The intersection of a compact set and a closed set is a compact set. -/
lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) :
is_compact (s ∩ t) :=
begin
introsI f hnf hstf,
obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f :=
hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))),
have : a ∈ t :=
(ht.mem_of_nhds_within_ne_bot $ ha.mono $
le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))),
exact ⟨a, ⟨hsa, this⟩, ha⟩
end
/-- The intersection of a closed set and a compact set is a compact set. -/
lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) :=
inter_comm t s ▸ ht.inter_right hs
/-- The set difference of a compact set and an open set is a compact set. -/
lemma is_compact.diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) :=
hs.inter_right (is_closed_compl_iff.mpr ht)
/-- A closed subset of a compact set is a compact set. -/
lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) :
is_compact t :=
inter_eq_self_of_subset_right h ▸ hs.inter_right ht
lemma is_compact.adherence_nhdset {f : filter α}
(hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) :
t ∈ f :=
classical.by_cases mem_sets_of_eq_bot $
assume : f ⊓ 𝓟 tᶜ ≠ ⊥,
let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs ⟨this⟩ $ inf_le_of_left_le hf₂ in
have a ∈ t,
from ht₂ a ha (hfa.of_inf_left),
have tᶜ ∩ t ∈ 𝓝[tᶜ] a,
from inter_mem_nhds_within _ (is_open.mem_nhds ht₁ this),
have A : 𝓝[tᶜ] a = ⊥,
from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this,
have 𝓝[tᶜ] a ≠ ⊥,
from hfa.of_inf_right.ne,
absurd A this
lemma is_compact_iff_ultrafilter_le_nhds :
is_compact s ↔ (∀f : ultrafilter α, ↑f ≤ 𝓟 s → ∃a∈s, ↑f ≤ 𝓝 a) :=
begin
refine (forall_ne_bot_le_iff _).trans _,
{ rintro f g hle ⟨a, has, haf⟩,
exact ⟨a, has, haf.mono hle⟩ },
{ simp only [ultrafilter.cluster_pt_iff] }
end
alias is_compact_iff_ultrafilter_le_nhds ↔ is_compact.ultrafilter_le_nhds _
/-- For every open directed cover of a compact set, there exists a single element of the
cover which itself includes the set. -/
lemma is_compact.elim_directed_cover {ι : Type v} [hι : nonempty ι] (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) (hdU : directed (⊆) U) :
∃ i, s ⊆ U i :=
hι.elim $ λ i₀, is_compact.induction_on hs ⟨i₀, empty_subset _⟩
(λ s₁ s₂ hs ⟨i, hi⟩, ⟨i, subset.trans hs hi⟩)
(λ s₁ s₂ ⟨i, hi⟩ ⟨j, hj⟩, let ⟨k, hki, hkj⟩ := hdU i j in
⟨k, union_subset (subset.trans hi hki) (subset.trans hj hkj)⟩)
(λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in
⟨U i, mem_nhds_within_of_mem_nhds (is_open.mem_nhds (hUo i) hi), i, subset.refl _⟩)
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s)
(U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) :
∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i :=
hs.elim_directed_cover _ (λ t, is_open_bUnion $ λ i _, hUo i) (Union_eq_Union_finset U ▸ hsU)
(directed_of_sup $ λ t₁ t₂ h, bUnion_subset_bUnion_left h)
lemma is_compact.elim_nhds_subcover' (hs : is_compact s) (U : Π x ∈ s, set α)
(hU : ∀ x ∈ s, U x ‹x ∈ s› ∈ 𝓝 x) :
∃ t : finset s, s ⊆ ⋃ x ∈ t, U (x : s) x.2 :=
(hs.elim_finite_subcover (λ x : s, interior (U x x.2)) (λ x, is_open_interior)
(λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 $ hU _ _⟩)).imp $ λ t ht,
subset.trans ht $ bUnion_subset_bUnion_right $ λ _ _, interior_subset
lemma is_compact.elim_nhds_subcover (hs : is_compact s) (U : α → set α) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) :
∃ t : finset α, (∀ x ∈ t, x ∈ s) ∧ s ⊆ ⋃ x ∈ t, U x :=
let ⟨t, ht⟩ := hs.elim_nhds_subcover' (λ x _, U x) hU
in ⟨t.image coe, λ x hx, let ⟨y, hyt, hyx⟩ := finset.mem_image.1 hx in hyx ▸ y.2,
by rwa finset.set_bUnion_finset_image⟩
/-- For every family of closed sets whose intersection avoids a compact set,
there exists a finite subfamily whose intersection avoids this compact set. -/
lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) :
∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ :=
let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) (λ i, (hZc i).is_open_compl)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- If `s` is a compact set in a topological space `α` and `f : ι → set α` is a locally finite
family of sets, then `f i ∩ s` is nonempty only for a finitely many `i`. -/
lemma locally_finite.finite_nonempty_inter_compact {ι : Type*} {f : ι → set α}
(hf : locally_finite f) {s : set α} (hs : is_compact s) :
finite {i | (f i ∩ s).nonempty} :=
begin
choose U hxU hUf using hf,
rcases hs.elim_nhds_subcover U (λ x _, hxU x) with ⟨t, -, hsU⟩,
refine (t.finite_to_set.bUnion (λ x _, hUf x)).subset _,
rintro i ⟨x, hx⟩,
rcases mem_bUnion_iff.1 (hsU hx.2) with ⟨c, hct, hcx⟩,
exact mem_bUnion hct ⟨x, hx.1, hcx⟩
end
/-- To show that a compact set intersects the intersection of a family of closed sets,
it is sufficient to show that it intersects every finite subfamily. -/
lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s)
(Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) :
(s ∩ ⋂ i, Z i).nonempty :=
begin
simp only [← ne_empty_iff_nonempty] at hsZ ⊢,
apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ
end
/-- Cantor's intersection theorem:
the intersection of a directed family of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
{ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z)
(hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
begin
apply hι.elim,
intro i₀,
let Z' := λ i, Z i ∩ Z i₀,
suffices : (⋂ i, Z' i).nonempty,
{ exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this },
rw ← ne_empty_iff_nonempty,
intro H,
obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅,
from (hZc i₀).elim_finite_subfamily_closed Z'
(assume i, is_closed.inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]),
obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i,
{ rcases directed.finset_le hZd t with ⟨i, hi⟩,
rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩,
use [i₁, hi₁₀],
intros j hj,
exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ },
suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty,
{ rw ← ne_empty_iff_nonempty at this, contradiction },
refine nonempty.mono _ (hZn i₁),
exact subset_inter hi₁.left (subset_bInter hi₁.right)
end
/-- Cantor's intersection theorem for sequences indexed by `ℕ`:
the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/
lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed
(Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i)
(hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) :
(⋂ i, Z i).nonempty :=
have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd,
have hZd : directed (⊇) Z, from directed_of_sup Zmono,
have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i,
have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i),
is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl
/-- For every open cover of a compact set, there exists a finite subcover. -/
lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α}
(hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) :
∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i :=
begin
rcases hs.elim_finite_subcover (λ i, c i : b → set α) _ _ with ⟨d, hd⟩;
[skip, simpa using hc₁, simpa using hc₂],
refine ⟨↑(d.image coe), _, finset.finite_to_set _, _⟩; simp *
end
/-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_of_finite_subfamily_closed
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :
is_compact s :=
assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f),
have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥,
by simpa only [cluster_pt, not_exists, not_not, ne_bot_iff],
have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t,
from assume ⟨x, hxs, hx⟩,
have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs],
let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in
have ∅ ∈ 𝓝[t₂] x,
from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht,
have 𝓝[t₂] x = ⊥,
by rwa [empty_in_sets_eq_bot] at this,
by simp only [closure_eq_cluster_pts] at hx; exact (hx t₂ ht₂).ne this,
let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure)
(by simpa [eq_empty_iff_forall_not_mem, not_exists]) in
have (⋂i∈t, subtype.val i) ∈ f,
from t.Inter_mem_sets.2 $ assume i hi, i.2,
have s ∩ (⋂i∈t, subtype.val i) ∈ f,
from inter_mem_sets (le_principal_iff.1 hfs) this,
have ∅ ∈ f,
from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩,
let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i),
by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in
have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit),
show false, from hxi this,
hfn.ne $ by rwa [empty_in_sets_eq_bot] at this
/-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_of_finite_subcover
(h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :
is_compact s :=
is_compact_of_finite_subfamily_closed $
assume ι Z hZc hsZ,
let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i)
(by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using hsZ)
in
⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, mem_Union,
exists_prop, mem_inter_eq, not_and, iff_self, mem_Inter, mem_compl_eq] using ht⟩
/-- A set `s` is compact if and only if
for every open cover of `s`, there exists a finite subcover. -/
lemma is_compact_iff_finite_subcover :
is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) →
s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) :=
⟨assume hs ι, hs.elim_finite_subcover, is_compact_of_finite_subcover⟩
/-- A set `s` is compact if and only if
for every family of closed sets whose intersection avoids `s`,
there exists a finite subfamily whose intersection avoids `s`. -/
theorem is_compact_iff_finite_subfamily_closed :
is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) :=
⟨assume hs ι, hs.elim_finite_subfamily_closed, is_compact_of_finite_subfamily_closed⟩
@[simp]
lemma is_compact_empty : is_compact (∅ : set α) :=
assume f hnf hsf, not.elim hnf.ne $
empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf
@[simp]
lemma is_compact_singleton {a : α} : is_compact ({a} : set α) :=
λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds'
(hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩
lemma set.subsingleton.is_compact {s : set α} (hs : s.subsingleton) : is_compact s :=
subsingleton.induction_on hs is_compact_empty $ λ x, is_compact_singleton
lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s)
(hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
is_compact_of_finite_subcover $ assume ι U hUo hsU,
have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from
assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo
(calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi
... ⊆ ⋃j, U j : hsU),
let ⟨finite_subcovers, h⟩ := axiom_of_choice this in
by haveI : fintype (subtype s) := hs.fintype; exact
let t := finset.bUnion finset.univ finite_subcovers in
have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $
assume i hi, calc
f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩)
... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $
assume j hj, finset.mem_bUnion.mpr ⟨_, finset.mem_univ _, hj⟩,
⟨t, this⟩
lemma finset.compact_bUnion (s : finset β) {f : β → set α} (hf : ∀i ∈ s, is_compact (f i)) :
is_compact (⋃i ∈ s, f i) :=
s.finite_to_set.compact_bUnion hf
lemma compact_accumulate {K : ℕ → set α} (hK : ∀ n, is_compact (K n)) (n : ℕ) :
is_compact (accumulate K n) :=
(finite_le_nat n).compact_bUnion $ λ k _, hK k
lemma compact_Union {f : β → set α} [fintype β]
(h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) :=
by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i)
lemma set.finite.is_compact (hs : finite s) : is_compact s :=
bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, is_compact_singleton)
lemma finite_of_is_compact_of_discrete [discrete_topology α] (s : set α) (hs : is_compact s) :
s.finite :=
begin
have := hs.elim_finite_subcover (λ x : α, ({x} : set α))
(λ x, is_open_discrete _),
simp only [set.subset_univ, forall_prop_of_true, set.Union_of_singleton] at this,
rcases this with ⟨t, ht⟩,
suffices : (⋃ (i : α) (H : i ∈ t), {i} : set α) = (t : set α),
{ rw this at ht, exact t.finite_to_set.subset ht },
ext x,
simp only [exists_prop, set.mem_Union, set.mem_singleton_iff, exists_eq_right', finset.mem_coe]
end
lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) :=
by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption)
lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) :=
is_compact_singleton.union hs
/-- If `V : ι → set α` is a decreasing family of closed compact sets then any neighborhood of
`⋂ i, V i` contains some `V i`. We assume each `V i` is compact *and* closed because `α` is
not assumed to be Hausdorff. See `exists_subset_nhd_of_compact` for version assuming this. -/
lemma exists_subset_nhd_of_compact' {ι : Type*} [nonempty ι] {V : ι → set α} (hV : directed (⊇) V)
(hV_cpct : ∀ i, is_compact (V i)) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
begin
set Y := ⋂ i, V i,
obtain ⟨W, hsubW, W_op, hWU⟩ : ∃ W, Y ⊆ W ∧ is_open W ∧ W ⊆ U,
from exists_open_set_nhds hU,
suffices : ∃ i, V i ⊆ W,
{ rcases this with ⟨i, hi⟩,
refine ⟨i, set.subset.trans hi hWU⟩ },
by_contradiction H,
push_neg at H,
replace H : ∀ i, (V i ∩ Wᶜ).nonempty := λ i, set.inter_compl_nonempty_iff.mpr (H i),
have : (⋂ i, V i ∩ Wᶜ).nonempty,
{ apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed _ _ H,
{ intro i,
exact (hV_cpct i).inter_right W_op.is_closed_compl },
{ intro i,
apply (hV_closed i).inter W_op.is_closed_compl },
{ intros i j,
rcases hV i j with ⟨k, hki, hkj⟩,
use k,
split ; intro x ; simp only [and_imp, mem_inter_eq, mem_compl_eq] ; tauto } },
have : ¬ (⋂ (i : ι), V i) ⊆ W,
by simpa [← Inter_inter, inter_compl_nonempty_iff],
contradiction
end
/-- `filter.cocompact` is the filter generated by complements to compact sets. -/
def filter.cocompact (α : Type*) [topological_space α] : filter α :=
⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ)
lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl :=
has_basis_binfi_principal'
(λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t),
compl_subset_compl.2 (subset_union_right s t)⟩)
⟨∅, is_compact_empty⟩
lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s :=
filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop
lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t :=
filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm
lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α :=
filter.has_basis_cocompact.mem_of_mem hs
section tube_lemma
variables [topological_space β]
/-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes
a product of an open neighborhood of `s` by an open neighborhood of `t`. -/
def nhds_contain_boxes (s : set α) (t : set β) : Prop :=
∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n),
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n
lemma nhds_contain_boxes.symm {s : set α} {t : set β} :
nhds_contain_boxes s t → nhds_contain_boxes t s :=
assume H n hn hp,
let ⟨u, v, uo, vo, su, tv, p⟩ :=
H (prod.swap ⁻¹' n)
(hn.preimage continuous_swap)
(by rwa [←image_subset_iff, image_swap_prod]) in
⟨v, u, vo, uo, tv, su,
by rwa [←image_subset_iff, image_swap_prod] at p⟩
lemma nhds_contain_boxes.comm {s : set α} {t : set β} :
nhds_contain_boxes s t ↔ nhds_contain_boxes t s :=
iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm
lemma nhds_contain_boxes_of_singleton {x : α} {y : β} :
nhds_contain_boxes ({x} : set α) ({y} : set β) :=
assume n hn hp,
let ⟨u, v, uo, vo, xu, yv, hp'⟩ :=
is_open_prod_iff.mp hn x y (hp $ by simp) in
⟨u, v, uo, vo, by simpa, by simpa, hp'⟩
lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β)
(H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t :=
assume n hn hp,
have ∀x : subtype s, ∃uv : set α × set β,
is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n,
from assume ⟨x, hx⟩,
have set.prod {x} t ⊆ n, from
subset.trans (prod_mono (by simpa) (subset.refl _)) hp,
let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩,
let ⟨uvs, h⟩ := classical.axiom_of_choice this in
have us_cover : s ⊆ ⋃i, (uvs i).1, from
assume x hx, subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1),
let ⟨s0, s0_cover⟩ :=
hs.elim_finite_subcover _ (λi, (h i).1) us_cover in
let u := ⋃(i ∈ s0), (uvs i).1 in
let v := ⋂(i ∈ s0), (uvs i).2 in
have is_open u, from is_open_bUnion (λi _, (h i).1),
have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1),
have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1),
have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩,
have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx',
let ⟨i,is0,hi⟩ := this in
(h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩,
⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩
/-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist
open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/
lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t)
{n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) :
∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n :=
have _, from
nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $
nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton,
this n hn hp
end tube_lemma
/-- Type class for compact spaces. Separation is sometimes included in the definition, especially
in the French literature, but we do not include it here. -/
class compact_space (α : Type*) [topological_space α] : Prop :=
(compact_univ : is_compact (univ : set α))
@[priority 10] -- see Note [lower instance priority]
instance subsingleton.compact_space [subsingleton α] : compact_space α :=
⟨subsingleton_univ.is_compact⟩
lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ
lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] :
∃ x, cluster_pt x f :=
by simpa using compact_univ (show f ≤ 𝓟 univ, by simp)
lemma compact_space.elim_nhds_subcover {α : Type*} [topological_space α] [compact_space α]
(U : α → set α) (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = ⊤ :=
begin
obtain ⟨t, -, s⟩ := is_compact.elim_nhds_subcover compact_univ U (λ x m, hU x),
exact ⟨t, by { rw eq_top_iff, exact s }⟩,
end
theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α]
(h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) →
(⋂ i, Z i) = ∅ → ∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅) :
compact_space α :=
{ compact_univ :=
begin
apply is_compact_of_finite_subfamily_closed,
intros ι Z, specialize h Z,
simpa using h
end }
lemma is_closed.is_compact [compact_space α] {s : set α} (h : is_closed s) :
is_compact s :=
compact_of_is_closed_subset compact_univ h (subset_univ _)
/-- A compact discrete space is finite. -/
noncomputable
def fintype_of_compact_of_discrete [compact_space α] [discrete_topology α] :
fintype α :=
fintype_of_univ_finite $ finite_of_is_compact_of_discrete _ compact_univ
lemma finite_cover_nhds_interior [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, interior (U x)) = univ :=
let ⟨t, ht⟩ := compact_univ.elim_finite_subcover (λ x, interior (U x)) (λ x, is_open_interior)
(λ x _, mem_Union.2 ⟨x, mem_interior_iff_mem_nhds.2 (hU x)⟩)
in ⟨t, univ_subset_iff.1 ht⟩
lemma finite_cover_nhds [compact_space α] {U : α → set α} (hU : ∀ x, U x ∈ 𝓝 x) :
∃ t : finset α, (⋃ x ∈ t, U x) = univ :=
let ⟨t, ht⟩ := finite_cover_nhds_interior hU in ⟨t, univ_subset_iff.1 $
ht ▸ bUnion_subset_bUnion_right (λ x hx, interior_subset)⟩
/-- If `α` is a compact space, then a locally finite family of sets of `α` can have only finitely
many nonempty elements. -/
lemma locally_finite.finite_nonempty_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) :
finite {i | (f i).nonempty} :=
by simpa only [inter_univ] using hf.finite_nonempty_inter_compact compact_univ
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `set.finite` version. -/
lemma locally_finite.finite_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
finite (univ : set ι) :=
by simpa only [hne] using hf.finite_nonempty_of_compact
/-- If `α` is a compact space, then a locally finite family of nonempty sets of `α` can have only
finitely many elements, `fintype` version. -/
noncomputable def locally_finite.fintype_of_compact {ι : Type*} [compact_space α] {f : ι → set α}
(hf : locally_finite f) (hne : ∀ i, (f i).nonempty) :
fintype ι :=
fintype_of_univ_finite (hf.finite_of_compact hne)
variables [topological_space β]
lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) :
is_compact (f '' s) :=
begin
intros l lne ls,
have : ne_bot (l.comap f ⊓ 𝓟 s) :=
comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls),
obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right,
use [f a, mem_image_of_mem f has],
have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l),
{ convert (hf a has).inf (@tendsto_comap _ _ f l) using 1,
rw nhds_within,
ac_refl },
exact @@tendsto.ne_bot _ this ha,
end
lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) :
is_compact (f '' s) :=
hs.image_of_continuous_on hf.continuous_on
lemma is_compact_range [compact_space α] {f : α → β} (hf : continuous f) :
is_compact (range f) :=
by rw ← image_univ; exact compact_univ.image hf
/-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/
theorem is_closed_proj_of_is_compact
{X : Type*} [topological_space X] [compact_space X]
{Y : Type*} [topological_space Y] :
is_closed_map (prod.snd : X × Y → Y) :=
begin
set πX := (prod.fst : X × Y → X),
set πY := (prod.snd : X × Y → Y),
assume C (hC : is_closed C),
rw is_closed_iff_cluster_pt at hC ⊢,
assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)),
have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
{ suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)),
by simpa only [map_ne_bot_iff],
convert y_closure,
calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) =
𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _
... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal },
resetI,
obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)),
from cluster_point_of_compact _,
refine ⟨⟨x, y⟩, _, by simp [πY]⟩,
apply hC,
rw [cluster_pt, ← filter.map_ne_bot_iff πX],
convert hx,
calc map πX (𝓝 (x, y) ⊓ 𝓟 C)
= map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod]
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl
... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull
... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm
end
lemma exists_subset_nhd_of_compact_space [compact_space α] {ι : Type*} [nonempty ι]
{V : ι → set α} (hV : directed (⊇) V) (hV_closed : ∀ i, is_closed (V i))
{U : set α} (hU : ∀ x ∈ ⋂ i, V i, U ∈ 𝓝 x) : ∃ i, V i ⊆ U :=
exists_subset_nhd_of_compact' hV (λ i, (hV_closed i).is_compact) hV_closed hU
lemma embedding.is_compact_iff_is_compact_image {f : α → β} (hf : embedding f) :
is_compact s ↔ is_compact (f '' s) :=
iff.intro (assume h, h.image hf.continuous) $ assume h, begin
rw is_compact_iff_ultrafilter_le_nhds at ⊢ h,
intros u us',
have : ↑(u.map f) ≤ 𝓟 (f '' s), begin
rw [ultrafilter.coe_map, map_le_iff_le_comap, comap_principal], convert us',
exact preimage_image_eq _ hf.inj
end,
rcases h (u.map f) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩,
refine ⟨a, ha, _⟩,
rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap]
end
/-- A closed embedding is proper, ie, inverse images of compact sets are contained in compacts. -/
lemma closed_embedding.tendsto_cocompact
{f : α → β} (hf : closed_embedding f) : tendsto f (filter.cocompact α) (filter.cocompact β) :=
begin
rw filter.has_basis_cocompact.tendsto_iff filter.has_basis_cocompact,
intros K hK,
refine ⟨f ⁻¹' (K ∩ (set.range f)), _, λ x hx, by simpa using hx⟩,
apply hf.to_embedding.is_compact_iff_is_compact_image.mpr,
rw set.image_preimage_eq_of_subset (set.inter_subset_right _ _),
exact hK.inter_right hf.closed_range,
end
lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} :
is_compact s ↔ is_compact ((coe : _ → α) '' s) :=
embedding_subtype_coe.is_compact_iff_is_compact_image
lemma is_compact_iff_is_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) :=
by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl
lemma is_compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s :=
is_compact_iff_is_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩
lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) :
is_compact (set.prod s t) :=
begin
rw is_compact_iff_ultrafilter_le_nhds at hs ht ⊢,
intros f hfs,
rw le_principal_iff at hfs,
obtain ⟨a : α, sa : a ∈ s, ha : map prod.fst ↑f ≤ 𝓝 a⟩ :=
hs (f.map prod.fst) (le_principal_iff.2 $ mem_map.2 $ mem_sets_of_superset hfs (λ x, and.left)),
obtain ⟨b : β, tb : b ∈ t, hb : map prod.snd ↑f ≤ 𝓝 b⟩ :=
ht (f.map prod.snd) (le_principal_iff.2 $ mem_map.2 $
mem_sets_of_superset hfs (λ x, and.right)),
rw map_le_iff_le_comap at ha hb,
refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩,
rw nhds_prod_eq, exact le_inf ha hb
end
lemma inducing.is_compact_iff {f : α → β} (hf : inducing f) {s : set α} :
is_compact (f '' s) ↔ is_compact s :=
begin
split,
{ introsI hs F F_ne_bot F_le,
obtain ⟨_, ⟨x, x_in : x ∈ s, rfl⟩, hx : cluster_pt (f x) (map f F)⟩ :=
hs (calc map f F ≤ map f (𝓟 s) : map_mono F_le
... = 𝓟 (f '' s) : map_principal),
use [x, x_in],
suffices : (map f (𝓝 x ⊓ F)).ne_bot, by simpa [filter.map_ne_bot_iff],
rwa calc map f (𝓝 x ⊓ F) = map f ((comap f $ 𝓝 $ f x) ⊓ F) : by rw hf.nhds_eq_comap
... = 𝓝 (f x) ⊓ map f F : filter.push_pull' _ _ _ },
{ intro hs,
exact hs.image hf.continuous }
end
/-- Finite topological spaces are compact. -/
@[priority 100] instance fintype.compact_space [fintype α] : compact_space α :=
{ compact_univ := finite_univ.is_compact }
/-- The product of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α × β) :=
⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩
/-- The disjoint union of two compact spaces is compact. -/
instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) :=
⟨begin
rw ← range_inl_union_range_inr,
exact (is_compact_range continuous_inl).union (is_compact_range continuous_inr)
end⟩
/-- The coproduct of the cocompact filters on two topological spaces is the cocompact filter on
their product. -/
lemma filter.coprod_cocompact {β : Type*} [topological_space β]:
(filter.cocompact α).coprod (filter.cocompact β) = filter.cocompact (α × β) :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap_sets, filter.mem_cocompact],
split,
{ rintro ⟨⟨A, ⟨t, ht, hAt⟩, hAS⟩, B, ⟨t', ht', hBt'⟩, hBS⟩,
refine ⟨t.prod t', ht.prod ht', _⟩,
refine subset.trans _ (union_subset hAS hBS),
rw compl_subset_comm at ⊢ hAt hBt',
refine subset.trans _ (set.prod_mono hAt hBt'),
intros x,
simp only [compl_union, mem_inter_eq, mem_prod, mem_preimage, mem_compl_eq],
tauto },
{ rintros ⟨t, ht, htS⟩,
refine ⟨⟨(prod.fst '' t)ᶜ, _, _⟩, ⟨(prod.snd '' t)ᶜ, _, _⟩⟩,
{ exact ⟨prod.fst '' t, ht.image continuous_fst, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.fst _) },
{ exact ⟨prod.snd '' t, ht.image continuous_snd, subset.rfl⟩ },
{ rw preimage_compl,
rw compl_subset_comm at ⊢ htS,
exact subset.trans htS (subset_preimage_image prod.snd _) } }
end
section tychonoff
variables {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)]
/-- **Tychonoff's theorem** -/
lemma is_compact_pi_infinite {s : Π i, set (π i)} :
(∀ i, is_compact (s i)) → is_compact {x : Π i, π i | ∀ i, x i ∈ s i} :=
begin
simp only [is_compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff,
le_principal_iff],
intros h f hfs,
have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a),
{ refine λ i, h i (f.map _) (mem_map.2 _),
exact mem_sets_of_superset hfs (λ x hx, hx i) },
choose a ha,
exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩
end
/-- A version of Tychonoff's theorem that uses `set.pi`. -/
lemma is_compact_univ_pi {s : Π i, set (π i)} (h : ∀ i, is_compact (s i)) :
is_compact (pi univ s) :=
by { convert is_compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] }
instance pi.compact_space [∀ i, compact_space (π i)] : compact_space (Πi, π i) :=
⟨by { rw [← pi_univ univ], exact is_compact_univ_pi (λ i, compact_univ) }⟩
/-- Product of compact sets is compact -/
lemma filter.Coprod_cocompact {δ : Type*} {κ : δ → Type*} [Π d, topological_space (κ d)] :
filter.Coprod (λ d, filter.cocompact (κ d)) = filter.cocompact (Π d, κ d) :=
begin
ext S,
simp only [mem_coprod_iff, exists_prop, mem_comap_sets, filter.mem_cocompact],
split,
{ intros h,
rw filter.mem_Coprod_iff at h,
choose t ht1 ht2 using h,
choose t1 ht11 ht12 using λ d, filter.mem_cocompact.mp (ht1 d),
refine ⟨set.pi set.univ t1, _, _⟩,
{ convert is_compact_pi_infinite ht11,
ext,
simp },
{ refine subset.trans _ (set.Union_subset ht2),
intros x,
simp only [mem_Union, mem_univ_pi, exists_imp_distrib, mem_compl_eq, not_forall],
intros d h,
exact ⟨d, ht12 d h⟩ } },
{ rintros ⟨t, h1, h2⟩,
rw filter.mem_Coprod_iff,
intros d,
refine ⟨((λ (k : Π (d : δ), κ d), k d) '' t)ᶜ, _, _⟩,
{ rw filter.mem_cocompact,
refine ⟨(λ (k : Π (d : δ), κ d), k d) '' t, _, set.subset.refl _⟩,
exact is_compact.image h1 (continuous_pi_iff.mp (continuous_id) d) },
refine subset.trans _ h2,
intros x hx,
simp only [not_exists, mem_image, mem_preimage, mem_compl_eq] at hx,
simpa using mt (hx x) },
end
end tychonoff
instance quot.compact_space {r : α → α → Prop} [compact_space α] :
compact_space (quot r) :=
⟨by { rw ← range_quot_mk, exact is_compact_range continuous_quot_mk }⟩
instance quotient.compact_space {s : setoid α} [compact_space α] :
compact_space (quotient s) :=
quot.compact_space
/-- There are various definitions of "locally compact space" in the literature, which agree for
Hausdorff spaces but not in general. This one is the precise condition on X needed for the
evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the
compact-open topology. -/
class locally_compact_space (α : Type*) [topological_space α] : Prop :=
(local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s)
lemma compact_basis_nhds [locally_compact_space α] (x : α) :
(𝓝 x).has_basis (λ s, s ∈ 𝓝 x ∧ is_compact s) (λ s, s) :=
has_basis_self.2 $ by simpa only [and_comm] using locally_compact_space.local_compact_nhds x
lemma locally_compact_space_of_has_basis {ι : α → Type*} {p : Π x, ι x → Prop}
{s : Π x, ι x → set α} (h : ∀ x, (𝓝 x).has_basis (p x) (s x))
(hc : ∀ x i, p x i → is_compact (s x i)) :
locally_compact_space α :=
⟨λ x t ht, let ⟨i, hp, ht⟩ := (h x).mem_iff.1 ht in ⟨s x i, (h x).mem_of_mem hp, ht, hc x i hp⟩⟩
instance locally_compact_space.prod (α : Type*) (β : Type*) [topological_space α]
[topological_space β] [locally_compact_space α] [locally_compact_space β] :
locally_compact_space (α × β) :=
have _ := λ x : α × β, (compact_basis_nhds x.1).prod_nhds' (compact_basis_nhds x.2),
locally_compact_space_of_has_basis this $ λ x s ⟨⟨_, h₁⟩, _, h₂⟩, h₁.prod h₂
/-- A reformulation of the definition of locally compact space: In a locally compact space,
every open set containing `x` has a compact subset containing `x` in its interior. -/
lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α}
(hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U :=
begin
rcases locally_compact_space.local_compact_nhds x U (hU.mem_nhds hx) with ⟨K, h1K, h2K, h3K⟩,
exact ⟨K, h3K, mem_interior_iff_mem_nhds.2 h1K, h2K⟩,
end
/-- In a locally compact space every point has a compact neighborhood. -/
lemma exists_compact_mem_nhds [locally_compact_space α] (x : α) :
∃ K, is_compact K ∧ K ∈ 𝓝 x :=
let ⟨K, hKc, hx, H⟩ := exists_compact_subset is_open_univ (mem_univ x)
in ⟨K, hKc, mem_interior_iff_mem_nhds.1 hx⟩
/-- In a locally compact space, every compact set is contained in the interior of a compact set. -/
lemma exists_compact_superset [locally_compact_space α] {K : set α} (hK : is_compact K) :
∃ K', is_compact K' ∧ K ⊆ interior K' :=
begin
choose U hUc hxU using λ x : K, exists_compact_mem_nhds (x : α),
have : K ⊆ ⋃ x, interior (U x),
from λ x hx, mem_Union.2 ⟨⟨x, hx⟩, mem_interior_iff_mem_nhds.2 (hxU _)⟩,
rcases hK.elim_finite_subcover _ _ this with ⟨t, ht⟩,
{ refine ⟨_, t.compact_bUnion (λ x _, hUc x), λ x hx, _⟩,
rcases mem_bUnion_iff.1 (ht hx) with ⟨y, hyt, hy⟩,
exact interior_mono (subset_bUnion_of_mem hyt) hy },
{ exact λ _, is_open_interior }
end
lemma ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) :
↑F ≤ 𝓝 (@Lim _ _ (F : filter α).nonempty_of_ne_bot F) :=
begin
rcases compact_univ.ultrafilter_le_nhds F (by simp) with ⟨x, -, h⟩,
exact le_nhds_Lim ⟨x,h⟩,
end
theorem is_closed.exists_minimal_nonempty_closed_subset [compact_space α]
{S : set α} (hS : is_closed S) (hne : S.nonempty) :
∃ (V : set α),
V ⊆ S ∧ V.nonempty ∧ is_closed V ∧
(∀ (V' : set α), V' ⊆ V → V'.nonempty → is_closed V' → V' = V) :=
begin
let opens := {U : set α | Sᶜ ⊆ U ∧ is_open U ∧ Uᶜ.nonempty},
obtain ⟨U, ⟨Uc, Uo, Ucne⟩, h⟩ := zorn.zorn_subset opens (λ c hc hz, begin
by_cases hcne : c.nonempty,
{ obtain ⟨U₀, hU₀⟩ := hcne,
haveI : nonempty {U // U ∈ c} := ⟨⟨U₀, hU₀⟩⟩,
obtain ⟨U₀compl, U₀opn, U₀ne⟩ := hc hU₀,
use ⋃₀ c,
refine ⟨⟨_, _, _⟩, λ U hU a ha, ⟨U, hU, ha⟩⟩,
{ exact λ a ha, ⟨U₀, hU₀, U₀compl ha⟩ },
{ exact is_open_sUnion (λ _ h, (hc h).2.1) },
{ convert_to (⋂(U : {U // U ∈ c}), U.1ᶜ).nonempty,
{ ext,
simp only [not_exists, exists_prop, not_and, set.mem_Inter, subtype.forall,
set.mem_set_of_eq, set.mem_compl_eq, subtype.val_eq_coe],
refl, },
apply is_compact.nonempty_Inter_of_directed_nonempty_compact_closed,
{ rintros ⟨U, hU⟩ ⟨U', hU'⟩,
obtain ⟨V, hVc, hVU, hVU'⟩ := zorn.chain.directed_on hz U hU U' hU',
exact ⟨⟨V, hVc⟩, set.compl_subset_compl.mpr hVU, set.compl_subset_compl.mpr hVU'⟩, },
{ exact λ U, (hc U.2).2.2, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1).is_compact, },
{ exact λ U, (is_closed_compl_iff.mpr (hc U.2).2.1), } } },
{ use Sᶜ,
refine ⟨⟨set.subset.refl _, is_open_compl_iff.mpr hS, _⟩, λ U Uc, (hcne ⟨U, Uc⟩).elim⟩,
rw compl_compl,
exact hne, }
end),
refine ⟨Uᶜ, set.compl_subset_comm.mp Uc, Ucne, is_closed_compl_iff.mpr Uo, _⟩,
intros V' V'sub V'ne V'cls,
have : V'ᶜ = U,
{ refine h V'ᶜ ⟨_, is_open_compl_iff.mpr V'cls, _⟩ (set.subset_compl_comm.mp V'sub),
exact set.subset.trans Uc (set.subset_compl_comm.mp V'sub),
simp only [compl_compl, V'ne], },
rw [←this, compl_compl],
end
/-- A σ-compact space is a space that is the union of a countable collection of compact subspaces.
Note that a locally compact separable T₂ space need not be σ-compact.
The sequence can be extracted using `topological_space.compact_covering`. -/
class sigma_compact_space (α : Type*) [topological_space α] : Prop :=
(exists_compact_covering : ∃ K : ℕ → set α, (∀ n, is_compact (K n)) ∧ (⋃ n, K n) = univ)
@[priority 200] -- see Note [lower instance priority]
instance compact_space.sigma_compact [compact_space α] : sigma_compact_space α :=
⟨⟨λ _, univ, λ _, compact_univ, Union_const _⟩⟩
lemma sigma_compact_space.of_countable (S : set (set α)) (Hc : countable S)
(Hcomp : ∀ s ∈ S, is_compact s) (HU : ⋃₀ S = univ) : sigma_compact_space α :=
⟨(exists_seq_cover_iff_countable ⟨_, is_compact_empty⟩).2 ⟨S, Hc, Hcomp, HU⟩⟩
@[priority 100] -- see Note [lower instance priority]
instance sigma_compact_space_of_locally_compact_second_countable [locally_compact_space α]
[second_countable_topology α] : sigma_compact_space α :=
begin
choose K hKc hxK using λ x : α, exists_compact_mem_nhds x,
rcases countable_cover_nhds hxK with ⟨s, hsc, hsU⟩,
refine sigma_compact_space.of_countable _ (hsc.image K) (ball_image_iff.2 $ λ x _, hKc x) _,
rwa sUnion_image
end
variables (α) [sigma_compact_space α]
open sigma_compact_space
/-- A choice of compact covering for a `σ`-compact space, chosen to be monotone. -/
def compact_covering : ℕ → set α :=
accumulate exists_compact_covering.some
lemma is_compact_compact_covering (n : ℕ) : is_compact (compact_covering α n) :=
compact_accumulate (classical.some_spec sigma_compact_space.exists_compact_covering).1 n
lemma Union_compact_covering : (⋃ n, compact_covering α n) = univ :=
begin
rw [compact_covering, Union_accumulate],
exact (classical.some_spec sigma_compact_space.exists_compact_covering).2
end
@[mono] lemma compact_covering_subset ⦃m n : ℕ⦄ (h : m ≤ n) :
compact_covering α m ⊆ compact_covering α n :=
monotone_accumulate h
variable {α}
/-- If `α` is a `σ`-compact space, then a locally finite family of nonempty sets of `α` can have
only countably many elements, `set.countable` version. -/
lemma locally_finite.countable_of_sigma_compact {ι : Type*} {f : ι → set α} (hf : locally_finite f)
(hne : ∀ i, (f i).nonempty) :
countable (univ : set ι) :=
begin
have := λ n, hf.finite_nonempty_inter_compact (is_compact_compact_covering α n),
refine (countable_Union (λ n, (this n).countable)).mono (λ i hi, _),
rcases hne i with ⟨x, hx⟩,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
exact mem_Union.2 ⟨n, x, hx, hn⟩
end
/-- In a topological space with sigma compact topology, if `f` is a function that sends each
point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`,
`x ∈ s`, cover the whole space. -/
lemma countable_cover_nhds_of_sigma_compact {f : α → set α}
(hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ :=
begin
choose t ht hsub using λ n, (is_compact_compact_covering α n).elim_nhds_subcover f (λ x _, hf x),
refine ⟨⋃ n, (t n : set α), countable_Union $ λ n, (t n).countable_to_set, _⟩,
simp only [eq_univ_iff_forall, mem_Union, exists_prop],
intro x,
rcases Union_eq_univ_iff.1 (Union_compact_covering α) x with ⟨n, hn⟩,
rcases mem_bUnion_iff.1 (hsub n hn) with ⟨c, hct, hfx⟩,
exact ⟨c, ⟨n, hct⟩, hfx⟩
end
end compact
/-- An [exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets) of a
topological space is a sequence of compact sets `K n` such that `K n ⊆ interior (K (n + 1))` and
`(⋃ n, K n) = univ`.
If `X` is a locally compact sigma compact space, then `compact_exhaustion.choice X` provides
a choice of an exhaustion by compact sets. This choice is also available as
`(default : compact_exhaustion X)`. -/
structure compact_exhaustion (X : Type*) [topological_space X] :=
(to_fun : ℕ → set X)
(is_compact' : ∀ n, is_compact (to_fun n))
(subset_interior_succ' : ∀ n, to_fun n ⊆ interior (to_fun (n + 1)))
(Union_eq' : (⋃ n, to_fun n) = univ)
namespace compact_exhaustion
instance : has_coe_to_fun (compact_exhaustion α) := ⟨_, to_fun⟩
variables {α} (K : compact_exhaustion α)
protected lemma is_compact (n : ℕ) : is_compact (K n) := K.is_compact' n
lemma subset_interior_succ (n : ℕ) : K n ⊆ interior (K (n + 1)) :=
K.subset_interior_succ' n
lemma subset_succ (n : ℕ) : K n ⊆ K (n + 1) :=
subset.trans (K.subset_interior_succ n) interior_subset
@[mono] protected lemma subset ⦃m n : ℕ⦄ (h : m ≤ n) : K m ⊆ K n :=
show K m ≤ K n, from monotone_of_monotone_nat K.subset_succ h
lemma subset_interior ⦃m n : ℕ⦄ (h : m < n) : K m ⊆ interior (K n) :=
subset.trans (K.subset_interior_succ m) $ interior_mono $ K.subset h
lemma Union_eq : (⋃ n, K n) = univ := K.Union_eq'
lemma exists_mem (x : α) : ∃ n, x ∈ K n := Union_eq_univ_iff.1 K.Union_eq x
/-- The minimal `n` such that `x ∈ K n`. -/
protected noncomputable def find (x : α) : ℕ := nat.find (K.exists_mem x)
lemma mem_find (x : α) : x ∈ K (K.find x) := nat.find_spec (K.exists_mem x)
lemma mem_iff_find_le {x : α} {n : ℕ} : x ∈ K n ↔ K.find x ≤ n :=
⟨λ h, nat.find_min' (K.exists_mem x) h, λ h, K.subset h $ K.mem_find x⟩
/-- Prepend the empty set to a compact exhaustion `K n`. -/
def shiftr : compact_exhaustion α :=
{ to_fun := λ n, nat.cases_on n ∅ K,
is_compact' := λ n, nat.cases_on n is_compact_empty K.is_compact,
subset_interior_succ' := λ n, nat.cases_on n (empty_subset _) K.subset_interior_succ,
Union_eq' := Union_eq_univ_iff.2 $ λ x, ⟨K.find x + 1, K.mem_find x⟩ }
@[simp] lemma find_shiftr (x : α) : K.shiftr.find x = K.find x + 1 :=
nat.find_comp_succ _ _ (not_mem_empty _)
lemma mem_diff_shiftr_find (x : α) : x ∈ K.shiftr (K.find x + 1) \ K.shiftr (K.find x) :=
⟨K.mem_find _, mt K.shiftr.mem_iff_find_le.1 $
by simp only [find_shiftr, not_le, nat.lt_succ_self]⟩
/-- A choice of an
[exhaustion by compact sets](https://en.wikipedia.org/wiki/Exhaustion_by_compact_sets)
of a locally compact sigma compact space. -/
noncomputable def choice (X : Type*) [topological_space X] [locally_compact_space X]
[sigma_compact_space X] : compact_exhaustion X :=
begin
apply classical.choice,
let K : ℕ → {s : set X // is_compact s} :=
λ n, nat.rec_on n ⟨∅, is_compact_empty⟩
(λ n s, ⟨(exists_compact_superset s.2).some ∪ compact_covering X n,
(exists_compact_superset s.2).some_spec.1.union (is_compact_compact_covering _ _)⟩),
refine ⟨⟨λ n, K n, λ n, (K n).2, λ n, _, _⟩⟩,
{ exact subset.trans (exists_compact_superset (K n).2).some_spec.2
(interior_mono $ subset_union_left _ _) },
{ refine univ_subset_iff.1 (Union_compact_covering X ▸ _),
exact Union_subset_Union2 (λ n, ⟨n + 1, subset_union_right _ _⟩) }
end
noncomputable instance [locally_compact_space α] [sigma_compact_space α] :
inhabited (compact_exhaustion α) :=
⟨compact_exhaustion.choice α⟩
end compact_exhaustion
section clopen
/-- A set is clopen if it is both open and closed. -/
def is_clopen (s : set α) : Prop :=
is_open s ∧ is_closed s
theorem is_clopen.union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) :=
⟨is_open.union hs.1 ht.1, is_closed.union hs.2 ht.2⟩
theorem is_clopen.inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) :=
⟨is_open.inter hs.1 ht.1, is_closed.inter hs.2 ht.2⟩
@[simp] theorem is_clopen_empty : is_clopen (∅ : set α) :=
⟨is_open_empty, is_closed_empty⟩
@[simp] theorem is_clopen_univ : is_clopen (univ : set α) :=
⟨is_open_univ, is_closed_univ⟩
theorem is_clopen.compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ :=
⟨hs.2.is_open_compl, is_closed_compl_iff.2 hs.1⟩
@[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s :=
⟨λ h, compl_compl s ▸ is_clopen.compl h, is_clopen.compl⟩
theorem is_clopen.diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) :=
hs.inter ht.compl
lemma is_clopen_Union {β : Type*} [fintype β] {s : β → set α}
(h : ∀ i, is_clopen (s i)) : is_clopen (⋃ i, s i) :=
⟨is_open_Union (forall_and_distrib.1 h).1, is_closed_Union (forall_and_distrib.1 h).2⟩
lemma is_clopen_bUnion {β : Type*} {s : finset β} {f : β → set α} (h : ∀i ∈ s, is_clopen $ f i) :
is_clopen (⋃ i ∈ s, f i) :=
begin
refine ⟨is_open_bUnion (λ i hi, (h i hi).1), _⟩,
show is_closed (⋃ (i : β) (H : i ∈ (s : set β)), f i),
rw bUnion_eq_Union,
exact is_closed_Union (λ ⟨i, hi⟩,(h i hi).2)
end
lemma is_clopen_Inter {β : Type*} [fintype β] {s : β → set α}
(h : ∀ i, is_clopen (s i)) : is_clopen (⋂ i, s i) :=
⟨(is_open_Inter (forall_and_distrib.1 h).1), (is_closed_Inter (forall_and_distrib.1 h).2)⟩
lemma is_clopen_bInter {β : Type*} {s : finset β} {f : β → set α} (h : ∀i∈s, is_clopen (f i)) :
is_clopen (⋂i∈s, f i) :=
⟨ is_open_bInter ⟨finset_coe.fintype s⟩ (λ i hi, (h i hi).1),
by {show is_closed (⋂ (i : β) (H : i ∈ (↑s : set β)), f i), rw bInter_eq_Inter,
apply is_closed_Inter, rintro ⟨i, hi⟩, exact (h i hi).2}⟩
lemma continuous_on.preimage_clopen_of_clopen {β: Type*} [topological_space β]
{f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_clopen s)
(ht : is_clopen t) : is_clopen (s ∩ f⁻¹' t) :=
⟨continuous_on.preimage_open_of_open hf hs.1 ht.1,
continuous_on.preimage_closed_of_closed hf hs.2 ht.2⟩
/-- The intersection of a disjoint covering by two open sets of a clopen set will be clopen. -/
theorem is_clopen_inter_of_disjoint_cover_clopen {Z a b : set α} (h : is_clopen Z)
(cover : Z ⊆ a ∪ b) (ha : is_open a) (hb : is_open b) (hab : a ∩ b = ∅) : is_clopen (Z ∩ a) :=
begin
refine ⟨is_open.inter h.1 ha, _⟩,
have : is_closed (Z ∩ bᶜ) := is_closed.inter h.2 (is_closed_compl_iff.2 hb),
convert this using 1,
apply subset.antisymm,
{ exact inter_subset_inter_right Z (subset_compl_iff_disjoint.2 hab) },
{ rintros x ⟨hx₁, hx₂⟩,
exact ⟨hx₁, by simpa [not_mem_of_mem_compl hx₂] using cover hx₁⟩ }
end
end clopen
section preirreducible
/-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/
def is_preirreducible (s : set α) : Prop :=
∀ (u v : set α), is_open u → is_open v →
(s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty
/-- An irreducible set `s` is one that is nonempty and
where there is no non-trivial pair of disjoint opens on `s`. -/
def is_irreducible (s : set α) : Prop :=
s.nonempty ∧ is_preirreducible s
lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) :
s.nonempty := h.1
lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) :
is_preirreducible s := h.2
theorem is_preirreducible_empty : is_preirreducible (∅ : set α) :=
λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim
theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) :=
⟨singleton_nonempty x,
λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3;
substs y z; exact ⟨x, rfl, h2, h4⟩⟩
theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) :
is_preirreducible (closure s) :=
λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩,
let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in
let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in
let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in
⟨r, subset_closure hrs, hruv⟩
lemma is_irreducible.closure {s : set α} (h : is_irreducible s) :
is_irreducible (closure s) :=
⟨h.nonempty.closure, h.is_preirreducible.closure⟩
theorem exists_preirreducible (s : set α) (H : is_preirreducible s) :
∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t :=
let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset_nonempty {t : set α | is_preirreducible t}
(λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in
⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩,
let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy,
⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in
or.cases_on (zorn.chain.total hcc hpc hqc)
(assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv
⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩)
(assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv
⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in
⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩),
λ x hxc, subset_sUnion_of_mem hxc⟩) s H in
⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩
/-- A maximal irreducible set that contains a given point. -/
def irreducible_component (x : α) : set α :=
classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
lemma irreducible_component_property (x : α) :
is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧
∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) :=
classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible)
theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x :=
singleton_subset_iff.1 (irreducible_component_property x).2.1
theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) :=
⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩
theorem eq_irreducible_component {x : α} :
∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x :=
(irreducible_component_property x).2.2
theorem is_closed_irreducible_component {x : α} :
is_closed (irreducible_component x) :=
closure_eq_iff_is_closed.1 $ eq_irreducible_component
is_irreducible_irreducible_component.is_preirreducible.closure
subset_closure
/-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/
class preirreducible_space (α : Type u) [topological_space α] : Prop :=
(is_preirreducible_univ [] : is_preirreducible (univ : set α))
/-- An irreducible space is one that is nonempty
and where there is no non-trivial pair of disjoint opens. -/
class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop :=
(to_nonempty [] : nonempty α)
-- see Note [lower instance priority]
attribute [instance, priority 50] irreducible_space.to_nonempty
theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} :
is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty :=
by simpa only [univ_inter, univ_subset_iff] using
@preirreducible_space.is_preirreducible_univ α _ _ s t
theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s)
(f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) :=
begin
rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩,
rw ← mem_preimage at hxu hyv,
rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩,
rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩,
have := H u' v' hu' hv',
rw [inter_comm s u', ← u'_eq] at this,
rw [inter_comm s v', ← v'_eq] at this,
rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩,
refine ⟨f z, mem_image_of_mem f hzs, _, _⟩,
all_goals
{ rw ← mem_preimage,
apply mem_of_mem_inter_left,
show z ∈ _ ∩ s,
simp [*] }
end
theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s)
(f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) :=
⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩
lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) :
preirreducible_space s :=
{ is_preirreducible_univ :=
begin
intros u v hu hv hsu hsv,
rw is_open_induced_iff at hu hv,
rcases hu with ⟨u, hu, rfl⟩,
rcases hv with ⟨v, hv, rfl⟩,
rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩,
rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩,
rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩,
exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩
end }
lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) :
irreducible_space s :=
{ is_preirreducible_univ :=
(subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ,
to_nonempty := h.nonempty.to_subtype }
/-- A set `s` is irreducible if and only if
for every finite collection of open sets all of whose members intersect `s`,
`s` also intersects the intersection of the entire collection
(i.e., there is an element of `s` contained in every member of the collection). -/
lemma is_irreducible_iff_sInter {s : set α} :
is_irreducible s ↔
∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty),
(s ∩ ⋂₀ ↑U).nonempty :=
begin
split; intro h,
{ intro U, apply finset.induction_on U,
{ intros, simpa using h.nonempty },
{ intros u U hu IH hU H,
rw [finset.coe_insert, sInter_insert],
apply h.2,
{ solve_by_elim [finset.mem_insert_self] },
{ apply is_open_sInter (finset.finite_to_set U),
intros, solve_by_elim [finset.mem_insert_of_mem] },
{ solve_by_elim [finset.mem_insert_self] },
{ apply IH,
all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } },
{ split,
{ simpa using h ∅ _ _; intro u; simp },
intros u v hu hv hu' hv',
simpa using h {u,v} _ _,
all_goals
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption } }
end
/-- A set is preirreducible if and only if
for every cover by two closed sets, it is contained in one of the two covering sets. -/
lemma is_preirreducible_iff_closed_union_closed {s : set α} :
is_preirreducible s ↔
∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ :=
begin
split,
all_goals
{ intros h t₁ t₂ ht₁ ht₂,
specialize h t₁ᶜ t₂ᶜ,
simp only [is_open_compl_iff, is_closed_compl_iff] at h,
specialize h ht₁ ht₂ },
{ contrapose!, simp only [not_subset],
rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩,
rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩,
rw ← compl_union at hz',
exact ⟨z, hz, hz'⟩ },
{ rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩,
rw ← compl_inter at h,
delta set.nonempty,
rw imp_iff_not_or at h,
contrapose! h,
split,
{ intros z hz hz', exact h z ⟨hz, hz'⟩ },
{ split; intro H; refine H _ ‹_›; assumption } }
end
/-- A set is irreducible if and only if
for every cover by a finite collection of closed sets,
it is contained in one of the members of the collection. -/
lemma is_irreducible_iff_sUnion_closed {s : set α} :
is_irreducible s ↔
∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z),
∃ z ∈ Z, s ⊆ z :=
begin
rw [is_irreducible, is_preirreducible_iff_closed_union_closed],
split; intro h,
{ intro Z, apply finset.induction_on Z,
{ intros, rw [finset.coe_empty, sUnion_empty] at H,
rcases h.1 with ⟨x, hx⟩,
exfalso, tauto },
{ intros z Z hz IH hZ H,
cases h.2 z (⋃₀ ↑Z) _ _ _
with h' h',
{ exact ⟨z, finset.mem_insert_self _ _, h'⟩ },
{ rcases IH _ h' with ⟨z', hz', hsz'⟩,
{ exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ },
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ solve_by_elim [finset.mem_insert_self] },
{ rw sUnion_eq_bUnion,
apply is_closed_bUnion (finset.finite_to_set Z),
{ intros, solve_by_elim [finset.mem_insert_of_mem] } },
{ simpa using H } } },
{ split,
{ by_contradiction hs,
simpa using h ∅ _ _,
{ intro z, simp },
{ simpa [set.nonempty] using hs } },
intros z₁ z₂ hz₁ hz₂ H,
have := h {z₁, z₂} _ _,
simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this,
{ rcases this with ⟨z, rfl|rfl, hz⟩; tauto },
{ intro t,
rw [finset.mem_insert, finset.mem_singleton],
rintro (rfl|rfl); assumption },
{ simpa using H } }
end
end preirreducible
|
8e01bb439defe601104459f4b537475a42c6bbcf | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/group_theory/free_group.lean | 8c477a913ba274453e2bcc48e6bd10e1172b1006 | [
"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 | 42,439 | 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.fintype.basic
import group_theory.subgroup.basic
/-!
# Free groups
This file defines free groups over a type. Furthermore, it is shown that the free group construction
is an instance of a monad. For the result that `free_group` is the left adjoint to the forgetful
functor from groups to types, see `algebra/category/Group/adjunctions`.
## Main definitions
* `free_group`/`free_add_group`: the free group (resp. free additive group) associated to a type
`α` defined as the words over `a : α × bool` modulo the relation `a * x * x⁻¹ * b = a * b`.
* `free_group.mk`/`free_add_group.mk`: the canonical quotient map `list (α × bool) → free_group α`.
* `free_group.of`/`free_add_group.of`: the canonical injection `α → free_group α`.
* `free_group.lift f`/`free_add_group.lift`: the canonical group homomorphism `free_group α →* G`
given a group `G` and a function `f : α → G`.
## Main statements
* `free_group.church_rosser`/`free_add_group.church_rosser`: The Church-Rosser theorem for word
reduction (also known as Newman's diamond lemma).
* `free_group.free_group_unit_equiv_int`: The free group over the one-point type
is isomorphic to the integers.
* The free group construction is an instance of a monad.
## Implementation details
First we introduce the one step reduction relation `free_group.red.step`:
`w * x * x⁻¹ * v ~> w * v`, its reflexive transitive closure `free_group.red.trans`
and prove that its join is an equivalence relation. Then we introduce `free_group α` as a quotient
over `free_group.red.step`.
For the additive version we introduce the same relation under a different name so that we can
distinguish the quotient types more easily.
## Tags
free group, Newman's diamond lemma, Church-Rosser theorem
-/
open relation
universes u v w
variables {α : Type u}
local attribute [simp] list.append_eq_has_append
run_cmd to_additive.map_namespace `free_group `free_add_group
/-- Reduction step for the additive free group relation: `w + x + (-x) + v ~> w + v` -/
inductive free_add_group.red.step : list (α × bool) → list (α × bool) → Prop
| bnot {L₁ L₂ x b} : free_add_group.red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂)
attribute [simp] free_add_group.red.step.bnot
/-- Reduction step for the multiplicative free group relation: `w * x * x⁻¹ * v ~> w * v` -/
@[to_additive]
inductive free_group.red.step : list (α × bool) → list (α × bool) → Prop
| bnot {L₁ L₂ x b} : free_group.red.step (L₁ ++ (x, b) :: (x, bnot b) :: L₂) (L₁ ++ L₂)
attribute [simp] free_group.red.step.bnot
namespace free_group
variables {L L₁ L₂ L₃ L₄ : list (α × bool)}
/-- Reflexive-transitive closure of red.step -/
@[to_additive "Reflexive-transitive closure of red.step"]
def red : list (α × bool) → list (α × bool) → Prop := refl_trans_gen red.step
@[refl, to_additive] lemma red.refl : red L L := refl_trans_gen.refl
@[trans, to_additive] lemma red.trans : red L₁ L₂ → red L₂ L₃ → red L₁ L₃ := refl_trans_gen.trans
namespace red
/-- Predicate asserting that the word `w₁` can be reduced to `w₂` in one step, i.e. there are words
`w₃ w₄` and letter `x` such that `w₁ = w₃xx⁻¹w₄` and `w₂ = w₃w₄` -/
@[to_additive
"Predicate asserting that the word `w₁` can be reduced to `w₂` in one step, i.e. there are words
`w₃ w₄` and letter `x` such that `w₁ = w₃ + x + (-x) + w₄` and `w₂ = w₃w₄`"]
theorem step.length : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.length + 2 = L₁.length
| _ _ (@red.step.bnot _ L1 L2 x b) := by rw [list.length_append, list.length_append]; refl
@[simp, to_additive]
lemma step.bnot_rev {x b} : step (L₁ ++ (x, bnot b) :: (x, b) :: L₂) (L₁ ++ L₂) :=
by cases b; from step.bnot
@[simp, to_additive] lemma step.cons_bnot {x b} : red.step ((x, b) :: (x, bnot b) :: L) L :=
@step.bnot _ [] _ _ _
@[simp, to_additive] lemma step.cons_bnot_rev {x b} : red.step ((x, bnot b) :: (x, b) :: L) L :=
@red.step.bnot_rev _ [] _ _ _
@[to_additive]
theorem step.append_left : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₂ L₃ → step (L₁ ++ L₂) (L₁ ++ L₃)
| _ _ _ red.step.bnot := by rw [← list.append_assoc, ← list.append_assoc]; constructor
@[to_additive]
theorem step.cons {x} (H : red.step L₁ L₂) : red.step (x :: L₁) (x :: L₂) :=
@step.append_left _ [x] _ _ H
@[to_additive]
theorem step.append_right : ∀ {L₁ L₂ L₃ : list (α × bool)}, step L₁ L₂ → step (L₁ ++ L₃) (L₂ ++ L₃)
| _ _ _ red.step.bnot := by simp
@[to_additive]
lemma not_step_nil : ¬ step [] L :=
begin
generalize h' : [] = L',
assume h,
cases h with L₁ L₂,
simp [list.nil_eq_append_iff] at h',
contradiction
end
@[to_additive]
lemma step.cons_left_iff {a : α} {b : bool} :
step ((a, b) :: L₁) L₂ ↔ (∃L, step L₁ L ∧ L₂ = (a, b) :: L) ∨ (L₁ = (a, bnot b)::L₂) :=
begin
split,
{ generalize hL : ((a, b) :: L₁ : list _) = L,
rintro @⟨_ | ⟨p, s'⟩, e, a', b'⟩,
{ simp at hL, simp [*] },
{ simp at hL,
rcases hL with ⟨rfl, rfl⟩,
refine or.inl ⟨s' ++ e, step.bnot, _⟩,
simp } },
{ rintro (⟨L, h, rfl⟩ | rfl),
{ exact step.cons h },
{ exact step.cons_bnot } }
end
@[to_additive]
lemma not_step_singleton : ∀ {p : α × bool}, ¬ step [p] L
| (a, b) := by simp [step.cons_left_iff, not_step_nil]
@[to_additive]
lemma step.cons_cons_iff : ∀{p : α × bool}, step (p :: L₁) (p :: L₂) ↔ step L₁ L₂ :=
by simp [step.cons_left_iff, iff_def, or_imp_distrib] {contextual := tt}
@[to_additive]
lemma step.append_left_iff : ∀L, step (L ++ L₁) (L ++ L₂) ↔ step L₁ L₂
| [] := by simp
| (p :: l) := by simp [step.append_left_iff l, step.cons_cons_iff]
@[to_additive]
theorem step.diamond_aux : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)} {x1 b1 x2 b2},
L₁ ++ (x1, b1) :: (x1, bnot b1) :: L₂ = L₃ ++ (x2, b2) :: (x2, bnot b2) :: L₄ →
L₁ ++ L₂ = L₃ ++ L₄ ∨ ∃ L₅, red.step (L₁ ++ L₂) L₅ ∧ red.step (L₃ ++ L₄) L₅
| [] _ [] _ _ _ _ _ H := by injections; subst_vars; simp
| [] _ [(x3,b3)] _ _ _ _ _ H := by injections; subst_vars; simp
| [(x3,b3)] _ [] _ _ _ _ _ H := by injections; subst_vars; simp
| [] _ ((x3,b3)::(x4,b4)::tl) _ _ _ _ _ H :=
by injections; subst_vars; simp; right; exact ⟨_, red.step.bnot, red.step.cons_bnot⟩
| ((x3,b3)::(x4,b4)::tl) _ [] _ _ _ _ _ H :=
by injections; subst_vars; simp; right; exact ⟨_, red.step.cons_bnot, red.step.bnot⟩
| ((x3,b3)::tl) _ ((x4,b4)::tl2) _ _ _ _ _ H :=
let ⟨H1, H2⟩ := list.cons.inj H in
match step.diamond_aux H2 with
| or.inl H3 := or.inl $ by simp [H1, H3]
| or.inr ⟨L₅, H3, H4⟩ := or.inr
⟨_, step.cons H3, by simpa [H1] using step.cons H4⟩
end
@[to_additive]
theorem step.diamond : ∀ {L₁ L₂ L₃ L₄ : list (α × bool)},
red.step L₁ L₃ → red.step L₂ L₄ → L₁ = L₂ →
L₃ = L₄ ∨ ∃ L₅, red.step L₃ L₅ ∧ red.step L₄ L₅
| _ _ _ _ red.step.bnot red.step.bnot H := step.diamond_aux H
@[to_additive]
lemma step.to_red : step L₁ L₂ → red L₁ L₂ :=
refl_trans_gen.single
/-- **Church-Rosser theorem** for word reduction: If `w1 w2 w3` are words such that `w1` reduces
to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4`
respectively. This is also known as Newman's diamond lemma. -/
@[to_additive
"**Church-Rosser theorem** for word reduction: If `w1 w2 w3` are words such that `w1` reduces
to `w2` and `w3` respectively, then there is a word `w4` such that `w2` and `w3` reduce to `w4`
respectively. This is also known as Newman's diamond lemma."]
theorem church_rosser : red L₁ L₂ → red L₁ L₃ → join red L₂ L₃ :=
relation.church_rosser (assume a b c hab hac,
match b, c, red.step.diamond hab hac rfl with
| b, _, or.inl rfl := ⟨b, by refl, by refl⟩
| b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, hcd.to_red⟩
end)
@[to_additive]
lemma cons_cons {p} : red L₁ L₂ → red (p :: L₁) (p :: L₂) :=
refl_trans_gen.lift (list.cons p) (assume a b, step.cons)
@[to_additive]
lemma cons_cons_iff (p) : red (p :: L₁) (p :: L₂) ↔ red L₁ L₂ :=
iff.intro
begin
generalize eq₁ : (p :: L₁ : list _) = LL₁,
generalize eq₂ : (p :: L₂ : list _) = LL₂,
assume h,
induction h using relation.refl_trans_gen.head_induction_on
with L₁ L₂ h₁₂ h ih
generalizing L₁ L₂,
{ subst_vars, cases eq₂, constructor },
{ subst_vars,
cases p with a b,
rw [step.cons_left_iff] at h₁₂,
rcases h₁₂ with ⟨L, h₁₂, rfl⟩ | rfl,
{ exact (ih rfl rfl).head h₁₂ },
{ exact (cons_cons h).tail step.cons_bnot_rev } }
end
cons_cons
@[to_additive]
lemma append_append_left_iff : ∀L, red (L ++ L₁) (L ++ L₂) ↔ red L₁ L₂
| [] := iff.rfl
| (p :: L) := by simp [append_append_left_iff L, cons_cons_iff]
@[to_additive]
lemma append_append (h₁ : red L₁ L₃) (h₂ : red L₂ L₄) : red (L₁ ++ L₂) (L₃ ++ L₄) :=
(h₁.lift (λL, L ++ L₂) (assume a b, step.append_right)).trans ((append_append_left_iff _).2 h₂)
@[to_additive]
lemma to_append_iff : red L (L₁ ++ L₂) ↔ (∃L₃ L₄, L = L₃ ++ L₄ ∧ red L₃ L₁ ∧ red L₄ L₂) :=
iff.intro
begin
generalize eq : L₁ ++ L₂ = L₁₂,
assume h,
induction h with L' L₁₂ hLL' h ih generalizing L₁ L₂,
{ exact ⟨_, _, eq.symm, by refl, by refl⟩ },
{ cases h with s e a b,
rcases list.append_eq_append_iff.1 eq with ⟨s', rfl, rfl⟩ | ⟨e', rfl, rfl⟩,
{ have : L₁ ++ (s' ++ ((a, b) :: (a, bnot b) :: e)) =
(L₁ ++ s') ++ ((a, b) :: (a, bnot b) :: e),
{ simp },
rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩,
exact ⟨w₁, w₂, rfl, h₁, h₂.tail step.bnot⟩ },
{ have : (s ++ ((a, b) :: (a, bnot b) :: e')) ++ L₂ =
s ++ ((a, b) :: (a, bnot b) :: (e' ++ L₂)),
{ simp },
rcases ih this with ⟨w₁, w₂, rfl, h₁, h₂⟩,
exact ⟨w₁, w₂, rfl, h₁.tail step.bnot, h₂⟩ }, }
end
(assume ⟨L₃, L₄, eq, h₃, h₄⟩, eq.symm ▸ append_append h₃ h₄)
/-- The empty word `[]` only reduces to itself. -/
@[to_additive "The empty word `[]` only reduces to itself."]
theorem nil_iff : red [] L ↔ L = [] :=
refl_trans_gen_iff_eq (assume l, red.not_step_nil)
/-- A letter only reduces to itself. -/
@[to_additive "A letter only reduces to itself."]
theorem singleton_iff {x} : red [x] L₁ ↔ L₁ = [x] :=
refl_trans_gen_iff_eq (assume l, not_step_singleton)
/-- If `x` is a letter and `w` is a word such that `xw` reduces to the empty word, then `w` reduces
to `x⁻¹` -/
@[to_additive "If `x` is a letter and `w` is a word such that `x + w` reduces to the empty word,
then `w` reduces to `-x`."]
theorem cons_nil_iff_singleton {x b} : red ((x, b) :: L) [] ↔ red L [(x, bnot b)] :=
iff.intro
(assume h,
have h₁ : red ((x, bnot b) :: (x, b) :: L) [(x, bnot b)], from cons_cons h,
have h₂ : red ((x, bnot b) :: (x, b) :: L) L, from refl_trans_gen.single step.cons_bnot_rev,
let ⟨L', h₁, h₂⟩ := church_rosser h₁ h₂ in
by rw [singleton_iff] at h₁; subst L'; assumption)
(assume h, (cons_cons h).tail step.cons_bnot)
@[to_additive]
theorem red_iff_irreducible {x1 b1 x2 b2} (h : (x1, b1) ≠ (x2, b2)) :
red [(x1, bnot b1), (x2, b2)] L ↔ L = [(x1, bnot b1), (x2, b2)] :=
begin
apply refl_trans_gen_iff_eq,
generalize eq : [(x1, bnot b1), (x2, b2)] = L',
assume L h',
cases h',
simp [list.cons_eq_append_iff, list.nil_eq_append_iff] at eq,
rcases eq with ⟨rfl, ⟨rfl, rfl⟩, ⟨rfl, rfl⟩, rfl⟩, subst_vars,
simp at h,
contradiction
end
/-- If `x` and `y` are distinct letters and `w₁ w₂` are words such that `xw₁` reduces to `yw₂`, then
`w₁` reduces to `x⁻¹yw₂`. -/
@[to_additive
"If `x` and `y` are distinct letters and `w₁ w₂` are words such that `x + w₁` reduces to `y + w₂`,
then `w₁` reduces to `-x + y + w₂`."]
theorem inv_of_red_of_ne {x1 b1 x2 b2}
(H1 : (x1, b1) ≠ (x2, b2))
(H2 : red ((x1, b1) :: L₁) ((x2, b2) :: L₂)) :
red L₁ ((x1, bnot b1) :: (x2, b2) :: L₂) :=
begin
have : red ((x1, b1) :: L₁) ([(x2, b2)] ++ L₂), from H2,
rcases to_append_iff.1 this with ⟨_ | ⟨p, L₃⟩, L₄, eq, h₁, h₂⟩,
{ simp [nil_iff] at h₁, contradiction },
{ cases eq,
show red (L₃ ++ L₄) ([(x1, bnot b1), (x2, b2)] ++ L₂),
apply append_append _ h₂,
have h₁ : red ((x1, bnot b1) :: (x1, b1) :: L₃) [(x1, bnot b1), (x2, b2)],
{ exact cons_cons h₁ },
have h₂ : red ((x1, bnot b1) :: (x1, b1) :: L₃) L₃,
{ exact step.cons_bnot_rev.to_red },
rcases church_rosser h₁ h₂ with ⟨L', h₁, h₂⟩,
rw [red_iff_irreducible H1] at h₁,
rwa [h₁] at h₂ }
end
@[to_additive]
theorem step.sublist (H : red.step L₁ L₂) : L₂ <+ L₁ :=
by cases H; simp; constructor; constructor; refl
/-- If `w₁ w₂` are words such that `w₁` reduces to `w₂`, then `w₂` is a sublist of `w₁`. -/
@[to_additive "If `w₁ w₂` are words such that `w₁` reduces to `w₂`,
then `w₂` is a sublist of `w₁`."]
protected theorem sublist : red L₁ L₂ → L₂ <+ L₁ :=
refl_trans_gen_of_transitive_reflexive
(λl, list.sublist.refl l) (λa b c hab hbc, list.sublist.trans hbc hab) (λa b, red.step.sublist)
@[to_additive]
theorem length_le (h : red L₁ L₂) : L₂.length ≤ L₁.length := h.sublist.length_le
@[to_additive]
theorem sizeof_of_step : ∀ {L₁ L₂ : list (α × bool)}, step L₁ L₂ → L₂.sizeof < L₁.sizeof
| _ _ (@step.bnot _ L1 L2 x b) :=
begin
induction L1 with hd tl ih,
case list.nil
{ dsimp [list.sizeof],
have H : 1 + sizeof (x, b) + (1 + sizeof (x, bnot b) + list.sizeof L2)
= (list.sizeof L2 + 1) + (sizeof (x, b) + sizeof (x, bnot b) + 1),
{ ac_refl },
rw H,
exact nat.le_add_right _ _ },
case list.cons
{ dsimp [list.sizeof],
exact nat.add_lt_add_left ih _ }
end
@[to_additive]
theorem length (h : red L₁ L₂) : ∃ n, L₁.length = L₂.length + 2 * n :=
begin
induction h with L₂ L₃ h₁₂ h₂₃ ih,
{ exact ⟨0, rfl⟩ },
{ rcases ih with ⟨n, eq⟩,
existsi (1 + n),
simp [mul_add, eq, (step.length h₂₃).symm, add_assoc] }
end
@[to_additive]
theorem antisymm (h₁₂ : red L₁ L₂) (h₂₁ : red L₂ L₁) : L₁ = L₂ :=
h₂₁.sublist.antisymm h₁₂.sublist
end red
@[to_additive]
theorem equivalence_join_red : equivalence (join (@red α)) :=
equivalence_join_refl_trans_gen $ assume a b c hab hac,
(match b, c, red.step.diamond hab hac rfl with
| b, _, or.inl rfl := ⟨b, by refl, by refl⟩
| b, c, or.inr ⟨d, hbd, hcd⟩ := ⟨d, refl_gen.single hbd, refl_trans_gen.single hcd⟩
end)
@[to_additive]
theorem join_red_of_step (h : red.step L₁ L₂) : join red L₁ L₂ :=
join_of_single reflexive_refl_trans_gen h.to_red
@[to_additive]
theorem eqv_gen_step_iff_join_red : eqv_gen red.step L₁ L₂ ↔ join red L₁ L₂ :=
iff.intro
(assume h,
have eqv_gen (join red) L₁ L₂ := h.mono (assume a b, join_red_of_step),
equivalence_join_red.eqv_gen_iff.1 this)
(join_of_equivalence (eqv_gen.is_equivalence _) $ assume a b,
refl_trans_gen_of_equivalence (eqv_gen.is_equivalence _) eqv_gen.rel)
end free_group
/-- The free group over a type, i.e. the words formed by the elements of the type and their formal
inverses, quotient by one step reduction. -/
@[to_additive "The free additive group over a type, i.e. the words formed by the elements of the
type and their formal inverses, quotient by one step reduction."]
def free_group (α : Type u) : Type u :=
quot $ @free_group.red.step α
namespace free_group
variables {α} {L L₁ L₂ L₃ L₄ : list (α × bool)}
/-- The canonical map from `list (α × bool)` to the free group on `α`. -/
@[to_additive "The canonical map from `list (α × bool)` to the free additive group on `α`."]
def mk (L) : free_group α := quot.mk red.step L
@[simp, to_additive] lemma quot_mk_eq_mk : quot.mk red.step L = mk L := rfl
@[simp, to_additive] lemma quot_lift_mk (β : Type v) (f : list (α × bool) → β)
(H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) :
quot.lift f H (mk L) = f L := rfl
@[simp, to_additive] lemma quot_lift_on_mk (β : Type v) (f : list (α × bool) → β)
(H : ∀ L₁ L₂, red.step L₁ L₂ → f L₁ = f L₂) :
quot.lift_on (mk L) f H = f L := rfl
@[simp, to_additive] lemma quot_map_mk (β : Type v) (f : list (α × bool) → list (β × bool))
(H : (red.step ⇒ red.step) f f) :
quot.map f H (mk L) = mk (f L) := rfl
@[to_additive]
instance : has_one (free_group α) := ⟨mk []⟩
@[to_additive]
lemma one_eq_mk : (1 : free_group α) = mk [] := rfl
@[to_additive]
instance : inhabited (free_group α) := ⟨1⟩
@[to_additive]
instance : has_mul (free_group α) :=
⟨λ x y, quot.lift_on x
(λ L₁, quot.lift_on y (λ L₂, mk $ L₁ ++ L₂) (λ L₂ L₃ H, quot.sound $ red.step.append_left H))
(λ L₁ L₂ H, quot.induction_on y $ λ L₃, quot.sound $ red.step.append_right H)⟩
@[simp, to_additive] lemma mul_mk : mk L₁ * mk L₂ = mk (L₁ ++ L₂) := rfl
/-- Transform a word representing a free group element into a word representing its inverse. -/
@[to_additive "Transform a word representing a free group element into a word representing its
negative."]
def inv_rev (w : list (α × bool)) : list (α × bool) :=
(list.map (λ (g : α × bool), (g.1, bnot g.2)) w).reverse
@[simp, to_additive] lemma inv_rev_length : (inv_rev L₁).length = L₁.length := by simp [inv_rev]
@[simp, to_additive] lemma inv_rev_inv_rev : (inv_rev (inv_rev L₁) = L₁) := by simp [inv_rev, (∘)]
@[simp, to_additive] lemma inv_rev_empty : inv_rev ([] : list (α × bool)) = [] := rfl
@[to_additive]
lemma inv_rev_involutive : function.involutive (@inv_rev α) := λ _, inv_rev_inv_rev
@[to_additive]
lemma inv_rev_injective : function.injective (@inv_rev α) := inv_rev_involutive.injective
@[to_additive]
lemma inv_rev_surjective : function.surjective (@inv_rev α) := inv_rev_involutive.surjective
@[to_additive]
lemma inv_rev_bijective : function.bijective (@inv_rev α) := inv_rev_involutive.bijective
@[to_additive]
instance : has_inv (free_group α) :=
⟨quot.map inv_rev (by { intros a b h, cases h, simp [inv_rev], })⟩
@[simp, to_additive] lemma inv_mk : (mk L)⁻¹ = mk (inv_rev L) := rfl
@[to_additive]
lemma red.step.inv_rev {L₁ L₂ : list (α × bool)} (h : red.step L₁ L₂) :
red.step (inv_rev L₁) (inv_rev L₂) :=
begin
cases h with a b x y,
simp [inv_rev],
end
@[to_additive]
lemma red.inv_rev {L₁ L₂ : list (α × bool)} (h : red L₁ L₂) :
red (inv_rev L₁) (inv_rev L₂) :=
relation.refl_trans_gen.lift _ (λ a b, red.step.inv_rev) h
@[simp, to_additive]
lemma red.step_inv_rev_iff : red.step (inv_rev L₁) (inv_rev L₂) ↔ red.step L₁ L₂ :=
⟨λ h, by simpa only [inv_rev_inv_rev] using h.inv_rev, λ h, h.inv_rev⟩
@[simp, to_additive] lemma red_inv_rev_iff : red (inv_rev L₁) (inv_rev L₂) ↔ red L₁ L₂ :=
⟨λ h, by simpa only [inv_rev_inv_rev] using h.inv_rev, λ h, h.inv_rev⟩
@[to_additive]
instance : group (free_group α) :=
{ mul := (*),
one := 1,
inv := has_inv.inv,
mul_assoc := by rintros ⟨L₁⟩ ⟨L₂⟩ ⟨L₃⟩; simp,
one_mul := by rintros ⟨L⟩; refl,
mul_one := by rintros ⟨L⟩; simp [one_eq_mk],
mul_left_inv := by rintros ⟨L⟩; exact (list.rec_on L rfl $
λ ⟨x, b⟩ tl ih, eq.trans (quot.sound $ by simp [inv_rev, one_eq_mk]) ih) }
/-- `of` is the canonical injection from the type to the free group over that type by sending each
element to the equivalence class of the letter that is the element. -/
@[to_additive "`of` is the canonical injection from the type to the free group over that type
by sending each element to the equivalence class of the letter that is the element."]
def of (x : α) : free_group α :=
mk [(x, tt)]
@[to_additive]
theorem red.exact : mk L₁ = mk L₂ ↔ join red L₁ L₂ :=
calc (mk L₁ = mk L₂) ↔ eqv_gen red.step L₁ L₂ : iff.intro (quot.exact _) quot.eqv_gen_sound
... ↔ join red L₁ L₂ : eqv_gen_step_iff_join_red
/-- The canonical map from the type to the free group is an injection. -/
@[to_additive "The canonical map from the type to the additive free group is an injection."]
theorem of_injective : function.injective (@of α) :=
λ _ _ H, let ⟨L₁, hx, hy⟩ := red.exact.1 H in
by simp [red.singleton_iff] at hx hy; cc
section lift
variables {β : Type v} [group β] (f : α → β) {x y : free_group α}
/-- Given `f : α → β` with `β` a group, the canonical map `list (α × bool) → β` -/
@[to_additive "Given `f : α → β` with `β` an additive group, the canonical map
`list (α × bool) → β`"]
def lift.aux : list (α × bool) → β :=
λ L, list.prod $ L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹
@[to_additive]
theorem red.step.lift {f : α → β} (H : red.step L₁ L₂) :
lift.aux f L₁ = lift.aux f L₂ :=
by cases H with _ _ _ b; cases b; simp [lift.aux]
/-- If `β` is a group, then any function from `α` to `β`
extends uniquely to a group homomorphism from
the free group over `α` to `β` -/
@[to_additive "If `β` is an additive group, then any function from `α` to `β`
extends uniquely to an additive group homomorphism from
the free additive group over `α` to `β`", simps symm_apply]
def lift : (α → β) ≃ (free_group α →* β) :=
{ to_fun := λ f,
monoid_hom.mk' (quot.lift (lift.aux f) $ λ L₁ L₂, red.step.lift) $ begin
rintros ⟨L₁⟩ ⟨L₂⟩, simp [lift.aux],
end,
inv_fun := λ g, g ∘ of,
left_inv := λ f, one_mul _,
right_inv := λ g, monoid_hom.ext $ begin
rintros ⟨L⟩,
apply list.rec_on L,
{ exact g.map_one.symm, },
{ rintros ⟨x, _ | _⟩ t (ih : _ = g (mk t)),
{ show _ = g ((of x)⁻¹ * mk t),
simpa [lift.aux] using ih },
{ show _ = g (of x * mk t),
simpa [lift.aux] using ih }, },
end }
variable {f}
@[simp, to_additive] lemma lift.mk : lift f (mk L) =
list.prod (L.map $ λ x, cond x.2 (f x.1) (f x.1)⁻¹) :=
rfl
@[simp, to_additive] lemma lift.of {x} : lift f (of x) = f x :=
one_mul _
@[to_additive]
theorem lift.unique (g : free_group α →* β)
(hg : ∀ x, g (of x) = f x) : ∀{x}, g x = lift f x :=
monoid_hom.congr_fun $ (lift.symm_apply_eq).mp (funext hg : g ∘ of = f)
/-- Two homomorphisms out of a free group are equal if they are equal on generators.
See note [partially-applied ext lemmas]. -/
@[ext, to_additive
"Two homomorphisms out of a free additive group are equal if they are equal on generators.
See note [partially-applied ext lemmas]."]
lemma ext_hom {G : Type*} [group G] (f g : free_group α →* G) (h : ∀ a, f (of a) = g (of a)) :
f = g :=
lift.symm.injective $ funext h
@[to_additive]
theorem lift.of_eq (x : free_group α) : lift of x = x :=
monoid_hom.congr_fun (lift.apply_symm_apply (monoid_hom.id _)) x
@[to_additive]
theorem lift.range_le {s : subgroup β} (H : set.range f ⊆ s) :
(lift f).range ≤ s :=
by rintros _ ⟨⟨L⟩, rfl⟩; exact list.rec_on L s.one_mem
(λ ⟨x, b⟩ tl ih, bool.rec_on b
(by simp at ih ⊢; from s.mul_mem
(s.inv_mem $ H ⟨x, rfl⟩) ih)
(by simp at ih ⊢; from s.mul_mem (H ⟨x, rfl⟩) ih))
@[to_additive]
theorem lift.range_eq_closure :
(lift f).range = subgroup.closure (set.range f) :=
begin
apply le_antisymm (lift.range_le subgroup.subset_closure),
rw subgroup.closure_le,
rintros _ ⟨a, rfl⟩,
exact ⟨of a, by simp only [lift.of]⟩,
end
end lift
section map
variables {β : Type v} (f : α → β) {x y : free_group α}
/-- Any function from `α` to `β` extends uniquely
to a group homomorphism from the free group
over `α` to the free group over `β`. -/
@[to_additive "Any function from `α` to `β` extends uniquely to an additive group homomorphism
from the additive free group over `α` to the additive free group over `β`."]
def map : free_group α →* free_group β :=
monoid_hom.mk'
(quot.map (list.map $ λ x, (f x.1, x.2)) $ λ L₁ L₂ H, by cases H; simp)
(by { rintros ⟨L₁⟩ ⟨L₂⟩, simp })
variable {f}
@[simp, to_additive] lemma map.mk : map f (mk L) = mk (L.map (λ x, (f x.1, x.2))) :=
rfl
@[simp, to_additive] lemma map.id (x : free_group α) : map id x = x :=
by rcases x with ⟨L⟩; simp [list.map_id']
@[simp, to_additive] lemma map.id' (x : free_group α) : map (λ z, z) x = x := map.id x
@[to_additive]
theorem map.comp {γ : Type w} (f : α → β) (g : β → γ) (x) :
map g (map f x) = map (g ∘ f) x :=
by rcases x with ⟨L⟩; simp
@[simp, to_additive] lemma map.of {x} : map f (of x) = of (f x) := rfl
@[to_additive]
theorem map.unique (g : free_group α →* free_group β)
(hg : ∀ x, g (of x) = of (f x)) : ∀{x}, g x = map f x :=
by rintros ⟨L⟩; exact list.rec_on L g.map_one
(λ ⟨x, b⟩ t (ih : g (mk t) = map f (mk t)), bool.rec_on b
(show g ((of x)⁻¹ * mk t) = map f ((of x)⁻¹ * mk t),
by simp [g.map_mul, g.map_inv, hg, ih])
(show g (of x * mk t) = map f (of x * mk t),
by simp [g.map_mul, hg, ih]))
@[to_additive]
theorem map_eq_lift : map f x = lift (of ∘ f) x :=
eq.symm $ map.unique _ $ λ x, by simp
/-- Equivalent types give rise to multiplicatively equivalent free groups.
The converse can be found in `group_theory.free_abelian_group_finsupp`,
as `equiv.of_free_group_equiv`
-/
@[to_additive "Equivalent types give rise to additively equivalent additive free groups.",
simps apply]
def free_group_congr {α β} (e : α ≃ β) : free_group α ≃* free_group β :=
{ to_fun := map e, inv_fun := map e.symm,
left_inv := λ x, by simp [function.comp, map.comp],
right_inv := λ x, by simp [function.comp, map.comp],
map_mul' := monoid_hom.map_mul _ }
@[simp, to_additive]
lemma free_group_congr_refl : free_group_congr (equiv.refl α) = mul_equiv.refl _ :=
mul_equiv.ext map.id
@[simp, to_additive] lemma free_group_congr_symm {α β} (e : α ≃ β) :
(free_group_congr e).symm = free_group_congr e.symm :=
rfl
@[to_additive]
lemma free_group_congr_trans {α β γ} (e : α ≃ β) (f : β ≃ γ) :
(free_group_congr e).trans (free_group_congr f) = free_group_congr (e.trans f) :=
mul_equiv.ext $ map.comp _ _
end map
section prod
variables [group α] (x y : free_group α)
/-- If `α` is a group, then any function from `α` to `α`
extends uniquely to a homomorphism from the
free group over `α` to `α`. This is the multiplicative
version of `free_group.sum`. -/
@[to_additive
"If `α` is an additive group, then any function from `α` to `α`
extends uniquely to an additive homomorphism from the
additive free group over `α` to `α`."]
def prod : free_group α →* α := lift id
variables {x y}
@[simp, to_additive] lemma prod_mk :
prod (mk L) = list.prod (L.map $ λ x, cond x.2 x.1 x.1⁻¹) :=
rfl
@[simp, to_additive] lemma prod.of {x : α} : prod (of x) = x :=
lift.of
@[to_additive]
lemma prod.unique (g : free_group α →* α)
(hg : ∀ x, g (of x) = x) {x} :
g x = prod x :=
lift.unique g hg
end prod
@[to_additive]
theorem lift_eq_prod_map {β : Type v} [group β] {f : α → β} {x} :
lift f x = prod (map f x) :=
begin
rw ←lift.unique (prod.comp (map f)),
{ refl },
{ simp }
end
section sum
variables [add_group α] (x y : free_group α)
/-- If `α` is a group, then any function from `α` to `α`
extends uniquely to a homomorphism from the
free group over `α` to `α`. This is the additive
version of `prod`. -/
def sum : α :=
@prod (multiplicative _) _ x
variables {x y}
@[simp] lemma sum_mk :
sum (mk L) = list.sum (L.map $ λ x, cond x.2 x.1 (-x.1)) :=
rfl
@[simp] lemma sum.of {x : α} : sum (of x) = x :=
prod.of
-- note: there are no bundled homs with different notation in the domain and codomain, so we copy
-- these manually
@[simp] lemma sum.map_mul : sum (x * y) = sum x + sum y :=
(@prod (multiplicative _) _).map_mul _ _
@[simp] lemma sum.map_one : sum (1:free_group α) = 0 :=
(@prod (multiplicative _) _).map_one
@[simp] lemma sum.map_inv : sum x⁻¹ = -sum x :=
(prod : free_group (multiplicative α) →* multiplicative α).map_inv _
end sum
/-- The bijection between the free group on the empty type, and a type with one element. -/
@[to_additive
"The bijection between the additive free group on the empty type, and a type with one element."]
def free_group_empty_equiv_unit : free_group empty ≃ unit :=
{ to_fun := λ _, (),
inv_fun := λ _, 1,
left_inv := by rintros ⟨_ | ⟨⟨⟨⟩, _⟩, _⟩⟩; refl,
right_inv := λ ⟨⟩, rfl }
/-- The bijection between the free group on a singleton, and the integers. -/
def free_group_unit_equiv_int : free_group unit ≃ ℤ :=
{ to_fun := λ x,
sum begin revert x, apply monoid_hom.to_fun,
apply map (λ _, (1 : ℤ)),
end,
inv_fun := λ x, of () ^ x,
left_inv :=
begin
rintros ⟨L⟩,
refine list.rec_on L rfl _,
exact (λ ⟨⟨⟩, b⟩ tl ih, by cases b; simp [zpow_add] at ih ⊢; rw ih; refl),
end,
right_inv :=
λ x, int.induction_on x (by simp)
(λ i ih, by simp at ih; simp [zpow_add, ih])
(λ i ih, by simp at ih; simp [zpow_add, ih, sub_eq_add_neg, -int.add_neg_one]) }
section category
variables {β : Type u}
@[to_additive]
instance : monad free_group.{u} :=
{ pure := λ α, of,
map := λ α β f, (map f),
bind := λ α β x f, lift f x }
@[elab_as_eliminator, to_additive]
protected theorem induction_on
{C : free_group α → Prop}
(z : free_group α)
(C1 : C 1)
(Cp : ∀ x, C $ pure x)
(Ci : ∀ x, C (pure x) → C (pure x)⁻¹)
(Cm : ∀ x y, C x → C y → C (x * y)) : C z :=
quot.induction_on z $ λ L, list.rec_on L C1 $ λ ⟨x, b⟩ tl ih,
bool.rec_on b (Cm _ _ (Ci _ $ Cp x) ih) (Cm _ _ (Cp x) ih)
@[simp, to_additive]
lemma map_pure (f : α → β) (x : α) : f <$> (pure x : free_group α) = pure (f x) := map.of
@[simp, to_additive] lemma map_one (f : α → β) : f <$> (1 : free_group α) = 1 :=
(map f).map_one
@[simp, to_additive]
lemma map_mul (f : α → β) (x y : free_group α) : f <$> (x * y) = f <$> x * f <$> y :=
(map f).map_mul x y
@[simp, to_additive] lemma map_inv (f : α → β) (x : free_group α) : f <$> (x⁻¹) = (f <$> x)⁻¹ :=
(map f).map_inv x
@[simp, to_additive] lemma pure_bind (f : α → free_group β) (x) : pure x >>= f = f x :=
lift.of
@[simp, to_additive] lemma one_bind (f : α → free_group β) : 1 >>= f = 1 :=
(lift f).map_one
@[simp, to_additive] lemma mul_bind (f : α → free_group β) (x y : free_group α) :
x * y >>= f = (x >>= f) * (y >>= f) :=
(lift f).map_mul _ _
@[simp, to_additive]
lemma inv_bind (f : α → free_group β) (x : free_group α) : x⁻¹ >>= f = (x >>= f)⁻¹ :=
(lift f).map_inv _
@[to_additive]
instance : is_lawful_monad free_group.{u} :=
{ id_map := λ α x, free_group.induction_on x (map_one id) (λ x, map_pure id x)
(λ x ih, by rw [map_inv, ih]) (λ x y ihx ihy, by rw [map_mul, ihx, ihy]),
pure_bind := λ α β x f, pure_bind f x,
bind_assoc := λ α β γ x f g, free_group.induction_on x
(by iterate 3 { rw one_bind }) (λ x, by iterate 2 { rw pure_bind })
(λ x ih, by iterate 3 { rw inv_bind }; rw ih)
(λ x y ihx ihy, by iterate 3 { rw mul_bind }; rw [ihx, ihy]),
bind_pure_comp_eq_map := λ α β f x, free_group.induction_on x
(by rw [one_bind, map_one]) (λ x, by rw [pure_bind, map_pure])
(λ x ih, by rw [inv_bind, map_inv, ih]) (λ x y ihx ihy, by rw [mul_bind, map_mul, ihx, ihy]) }
end category
section reduce
variable [decidable_eq α]
/-- The maximal reduction of a word. It is computable
iff `α` has decidable equality. -/
@[to_additive "The maximal reduction of a word. It is computable
iff `α` has decidable equality."]
def reduce (L : list (α × bool)) : list (α × bool) :=
list.rec_on L [] $ λ hd1 tl1 ih,
list.cases_on ih [hd1] $ λ hd2 tl2,
if hd1.1 = hd2.1 ∧ hd1.2 = bnot hd2.2 then tl2
else hd1 :: hd2 :: tl2
@[simp, to_additive] lemma reduce.cons (x) : reduce (x :: L) =
list.cases_on (reduce L) [x] (λ hd tl,
if x.1 = hd.1 ∧ x.2 = bnot hd.2 then tl
else x :: hd :: tl) := rfl
/-- The first theorem that characterises the function
`reduce`: a word reduces to its maximal reduction. -/
@[to_additive
"The first theorem that characterises the function
`reduce`: a word reduces to its maximal reduction."]
theorem reduce.red : red L (reduce L) :=
begin
induction L with hd1 tl1 ih,
case list.nil
{ constructor },
case list.cons
{ dsimp,
revert ih,
generalize htl : reduce tl1 = TL,
intro ih,
cases TL with hd2 tl2,
case list.nil
{ exact red.cons_cons ih },
case list.cons
{ dsimp only,
split_ifs with h,
{ transitivity,
{ exact red.cons_cons ih },
{ cases hd1, cases hd2, cases h,
dsimp at *, subst_vars,
exact red.step.cons_bnot_rev.to_red } },
{ exact red.cons_cons ih } } }
end
@[to_additive]
theorem reduce.not {p : Prop} :
∀ {L₁ L₂ L₃ : list (α × bool)} {x b}, reduce L₁ = L₂ ++ (x, b) :: (x, bnot b) :: L₃ → p
| [] L2 L3 _ _ := λ h, by cases L2; injections
| ((x,b)::L1) L2 L3 x' b' := begin
dsimp,
cases r : reduce L1,
{ dsimp, intro h,
have := congr_arg list.length h,
simp [-add_comm] at this,
exact absurd this dec_trivial },
cases hd with y c,
dsimp only,
split_ifs with h; intro H,
{ rw H at r,
exact @reduce.not L1 ((y,c)::L2) L3 x' b' r },
rcases L2 with _|⟨a, L2⟩,
{ injections, subst_vars,
simp at h, cc },
{ refine @reduce.not L1 L2 L3 x' b' _,
injection H with _ H,
rw [r, H], refl }
end
/-- The second theorem that characterises the
function `reduce`: the maximal reduction of a word
only reduces to itself. -/
@[to_additive "The second theorem that characterises the
function `reduce`: the maximal reduction of a word
only reduces to itself."]
theorem reduce.min (H : red (reduce L₁) L₂) : reduce L₁ = L₂ :=
begin
induction H with L1 L' L2 H1 H2 ih,
{ refl },
{ cases H1 with L4 L5 x b,
exact reduce.not H2 }
end
/-- `reduce` is idempotent, i.e. the maximal reduction
of the maximal reduction of a word is the maximal
reduction of the word. -/
@[simp, to_additive "`reduce` is idempotent, i.e. the maximal reduction
of the maximal reduction of a word is the maximal
reduction of the word."] theorem reduce.idem : reduce (reduce L) = reduce L :=
eq.symm $ reduce.min reduce.red
@[to_additive]
theorem reduce.step.eq (H : red.step L₁ L₂) : reduce L₁ = reduce L₂ :=
let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (reduce.red.head H) in
(reduce.min HR13).trans (reduce.min HR23).symm
/-- If a word reduces to another word, then they have
a common maximal reduction. -/
@[to_additive "If a word reduces to another word, then they have
a common maximal reduction."]
theorem reduce.eq_of_red (H : red L₁ L₂) : reduce L₁ = reduce L₂ :=
let ⟨L₃, HR13, HR23⟩ := red.church_rosser reduce.red (red.trans H reduce.red) in
(reduce.min HR13).trans (reduce.min HR23).symm
alias reduce.eq_of_red ← red.reduce_eq
alias free_add_group.reduce.eq_of_red ← free_add_group.red.reduce_eq
@[to_additive]
lemma red.reduce_right (h : red L₁ L₂) : red L₁ (reduce L₂) :=
reduce.eq_of_red h ▸ reduce.red
@[to_additive]
lemma red.reduce_left (h : red L₁ L₂) : red L₂ (reduce L₁) :=
(reduce.eq_of_red h).symm ▸ reduce.red
/-- If two words correspond to the same element in
the free group, then they have a common maximal
reduction. This is the proof that the function that
sends an element of the free group to its maximal
reduction is well-defined. -/
@[to_additive
"If two words correspond to the same element in
the additive free group, then they have a common maximal
reduction. This is the proof that the function that
sends an element of the free group to its maximal
reduction is well-defined."]
theorem reduce.sound (H : mk L₁ = mk L₂) : reduce L₁ = reduce L₂ :=
let ⟨L₃, H13, H23⟩ := red.exact.1 H in
(reduce.eq_of_red H13).trans (reduce.eq_of_red H23).symm
/-- If two words have a common maximal reduction,
then they correspond to the same element in the free group. -/
@[to_additive "If two words have a common maximal reduction,
then they correspond to the same element in the additive free group."]
theorem reduce.exact (H : reduce L₁ = reduce L₂) : mk L₁ = mk L₂ :=
red.exact.2 ⟨reduce L₂, H ▸ reduce.red, reduce.red⟩
/-- A word and its maximal reduction correspond to
the same element of the free group. -/
@[to_additive "A word and its maximal reduction correspond to
the same element of the additive free group."]
theorem reduce.self : mk (reduce L) = mk L :=
reduce.exact reduce.idem
/-- If words `w₁ w₂` are such that `w₁` reduces to `w₂`,
then `w₂` reduces to the maximal reduction of `w₁`. -/
@[to_additive "If words `w₁ w₂` are such that `w₁` reduces to `w₂`,
then `w₂` reduces to the maximal reduction of `w₁`."]
theorem reduce.rev (H : red L₁ L₂) : red L₂ (reduce L₁) :=
(reduce.eq_of_red H).symm ▸ reduce.red
/-- The function that sends an element of the free
group to its maximal reduction. -/
@[to_additive "The function that sends an element of the additive free
group to its maximal reduction."]
def to_word : free_group α → list (α × bool) :=
quot.lift reduce $ λ L₁ L₂ H, reduce.step.eq H
@[to_additive]
lemma mk_to_word : ∀{x : free_group α}, mk (to_word x) = x :=
by rintros ⟨L⟩; exact reduce.self
@[to_additive]
lemma to_word_injective : function.injective (to_word : free_group α → list (α × bool)) :=
by rintros ⟨L₁⟩ ⟨L₂⟩; exact reduce.exact
@[simp, to_additive] lemma to_word_inj {x y : free_group α} : to_word x = to_word y ↔ x = y :=
to_word_injective.eq_iff
@[simp, to_additive] lemma to_word_mk : (mk L₁).to_word = reduce L₁ := rfl
@[simp, to_additive] lemma reduce_to_word : ∀ (x : free_group α), reduce (to_word x) = to_word x :=
by { rintro ⟨L⟩, exact reduce.idem }
@[simp, to_additive] lemma to_word_one : (1 : free_group α).to_word = [] := rfl
@[simp, to_additive] lemma to_word_eq_nil_iff {x : free_group α} : (x.to_word = []) ↔ (x = 1) :=
to_word_injective.eq_iff' to_word_one
@[to_additive]
lemma reduce_inv_rev {w : list (α × bool)} : reduce (inv_rev w) = inv_rev (reduce w) :=
begin
apply reduce.min,
rw [← red_inv_rev_iff, inv_rev_inv_rev],
apply red.reduce_left,
have : red (inv_rev (inv_rev w)) (inv_rev (reduce (inv_rev w))) := reduce.red.inv_rev,
rwa inv_rev_inv_rev at this
end
@[to_additive]
lemma to_word_inv {x : free_group α} : (x⁻¹).to_word = inv_rev x.to_word :=
begin
rcases x with ⟨L⟩,
rw [quot_mk_eq_mk, inv_mk, to_word_mk, to_word_mk, reduce_inv_rev]
end
/-- Constructive Church-Rosser theorem (compare `church_rosser`). -/
@[to_additive "Constructive Church-Rosser theorem (compare `church_rosser`)."]
def reduce.church_rosser (H12 : red L₁ L₂) (H13 : red L₁ L₃) :
{ L₄ // red L₂ L₄ ∧ red L₃ L₄ } :=
⟨reduce L₁, reduce.rev H12, reduce.rev H13⟩
@[to_additive]
instance : decidable_eq (free_group α) :=
to_word_injective.decidable_eq
-- TODO @[to_additive] doesn't succeed, possibly due to a bug
instance red.decidable_rel : decidable_rel (@red α)
| [] [] := is_true red.refl
| [] (hd2::tl2) := is_false $ λ H, list.no_confusion (red.nil_iff.1 H)
| ((x,b)::tl) [] := match red.decidable_rel tl [(x, bnot b)] with
| is_true H := is_true $ red.trans (red.cons_cons H) $
(@red.step.bnot _ [] [] _ _).to_red
| is_false H := is_false $ λ H2, H $ red.cons_nil_iff_singleton.1 H2
end
| ((x1,b1)::tl1) ((x2,b2)::tl2) := if h : (x1, b1) = (x2, b2)
then match red.decidable_rel tl1 tl2 with
| is_true H := is_true $ h ▸ red.cons_cons H
| is_false H := is_false $ λ H2, H $ h ▸ (red.cons_cons_iff _).1 $ H2
end
else match red.decidable_rel tl1 ((x1,bnot b1)::(x2,b2)::tl2) with
| is_true H := is_true $ (red.cons_cons H).tail red.step.cons_bnot
| is_false H := is_false $ λ H2, H $ red.inv_of_red_of_ne h H2
end
/-- A list containing every word that `w₁` reduces to. -/
def red.enum (L₁ : list (α × bool)) : list (list (α × bool)) :=
list.filter (λ L₂, red L₁ L₂) (list.sublists L₁)
theorem red.enum.sound (H : L₂ ∈ red.enum L₁) : red L₁ L₂ :=
list.of_mem_filter H
theorem red.enum.complete (H : red L₁ L₂) : L₂ ∈ red.enum L₁ :=
list.mem_filter_of_mem (list.mem_sublists.2 $ red.sublist H) H
instance : fintype { L₂ // red L₁ L₂ } :=
fintype.subtype (list.to_finset $ red.enum L₁) $
λ L₂, ⟨λ H, red.enum.sound $ list.mem_to_finset.1 H,
λ H, list.mem_to_finset.2 $ red.enum.complete H⟩
end reduce
section metric
variable [decidable_eq α]
/-- The length of reduced words provides a norm on a free group. -/
@[to_additive "The length of reduced words provides a norm on an additive free group."]
def norm (x : free_group α) : ℕ := x.to_word.length
@[simp, to_additive] lemma norm_inv_eq {x : free_group α} : norm x⁻¹ = norm x :=
by simp only [norm, to_word_inv, inv_rev_length]
@[simp, to_additive] lemma norm_eq_zero {x : free_group α} : norm x = 0 ↔ x = 1 :=
by simp only [norm, list.length_eq_zero, to_word_eq_nil_iff]
@[simp, to_additive] lemma norm_one : norm (1 : free_group α) = 0 := rfl
@[to_additive]
theorem norm_mk_le : norm (mk L₁) ≤ L₁.length := reduce.red.length_le
@[to_additive]
lemma norm_mul_le (x y : free_group α) : norm (x * y) ≤ norm x + norm y :=
calc norm (x * y) = norm (mk (x.to_word ++ y.to_word)) : by rw [← mul_mk, mk_to_word, mk_to_word]
... ≤ (x.to_word ++ y.to_word).length : norm_mk_le
... = norm x + norm y : list.length_append _ _
end metric
end free_group
|
4687dcd9db464d89797a4e7b9fc4aa7ad3abcdfb | 5fbbd711f9bfc21ee168f46a4be146603ece8835 | /lean/natural_number_game/addition/3.lean | 546212d1873d509659aaa1aabd76816672557e93 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | goedel-gang/maths | 22596f71e3fde9c088e59931f128a3b5efb73a2c | a20a6f6a8ce800427afd595c598a5ad43da1408d | refs/heads/master | 1,623,055,941,960 | 1,621,599,441,000 | 1,621,599,441,000 | 169,335,840 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 153 | lean | lemma succ_add (a b : mynat) : succ a + b = succ (a + b) :=
begin
induction b with n hn,
repeat {rw add_zero},
repeat {rw add_succ},
rwa hn,
end
|
ce1a932102167b5bdfa96a8b736710ec37e7ff74 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/omega_complete_partial_order.lean | fb4484124088ea475ecf077a5174961813438f28 | [] | 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 | 29,436 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Simon Hudon
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.pfun
import Mathlib.order.preorder_hom
import Mathlib.tactic.wlog
import Mathlib.tactic.monotonicity.default
import Mathlib.PostPort
universes u_1 u_2 u_5 u_6 u_3 u v l u_4
namespace Mathlib
/-!
# Omega Complete Partial Orders
An omega-complete partial order is a partial order with a supremum
operation on increasing sequences indexed by natural numbers (which we
call `ωSup`). In this sense, it is strictly weaker than join complete
semi-lattices as only ω-sized totally ordered sets have a supremum.
The concept of an omega-complete partial order (ωCPO) is useful for the
formalization of the semantics of programming languages. Its notion of
supremum helps define the meaning of recursive procedures.
## Main definitions
* class `omega_complete_partial_order`
* `ite`, `map`, `bind`, `seq` as continuous morphisms
## Instances of `omega_complete_partial_order`
* `roption`
* every `complete_lattice`
* pi-types
* product types
* `monotone_hom`
* `continuous_hom` (with notation →𝒄)
* an instance of `omega_complete_partial_order (α →𝒄 β)`
* `continuous_hom.of_fun`
* `continuous_hom.of_mono`
* continuous functions:
* `id`
* `ite`
* `const`
* `roption.bind`
* `roption.map`
* `roption.seq`
## References
* [G. Markowsky, *Chain-complete posets and directed sets with applications*, https://doi.org/10.1007/BF02485815][markowsky]
* [J. M. Cadiou and Zohar Manna, *Recursive definitions of partial functions and their computations.*, https://doi.org/10.1145/942580.807072][cadiou]
* [Carl A. Gunter, *Semantics of Programming Languages: Structures and Techniques*, ISBN: 0262570955][gunter]
-/
namespace preorder_hom
/-- The constant function, as a monotone function. -/
@[simp] theorem const_to_fun (α : Type u_1) {β : Type u_2} [preorder α] [preorder β] (f : β) : ∀ (ᾰ : α), coe_fn (const α f) ᾰ = function.const α f ᾰ :=
fun (ᾰ : α) => Eq.refl (coe_fn (const α f) ᾰ)
/-- The diagonal function, as a monotone function. -/
def prod.diag {α : Type u_1} [preorder α] : α →ₘ α × α :=
mk (fun (x : α) => (x, x)) sorry
/-- The `prod.map` function, as a monotone function. -/
@[simp] theorem prod.map_to_fun {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] {α' : Type u_5} {β' : Type u_6} [preorder α'] [preorder β'] (f : α →ₘ β) (f' : α' →ₘ β') (x : α × α') : coe_fn (prod.map f f') x = prod.map (⇑f) (⇑f') x :=
Eq.refl (coe_fn (prod.map f f') x)
/-- The `prod.fst` projection, as a monotone function. -/
def prod.fst {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] : α × β →ₘ α :=
mk prod.fst sorry
/-- The `prod.snd` projection, as a monotone function. -/
def prod.snd {α : Type u_1} {β : Type u_2} [preorder α] [preorder β] : α × β →ₘ β :=
mk prod.snd sorry
/-- The `prod` constructor, as a monotone function. -/
@[simp] theorem prod.zip_to_fun {α : Type u_1} {β : Type u_2} {γ : Type u_3} [preorder α] [preorder β] [preorder γ] (f : α →ₘ β) (g : α →ₘ γ) : ∀ (ᾰ : α), coe_fn (prod.zip f g) ᾰ = (coe_fn f ᾰ, coe_fn g ᾰ) :=
fun (ᾰ : α) => Eq.refl (coe_fn f ᾰ, coe_fn g ᾰ)
/-- `roption.bind` as a monotone function -/
@[simp] theorem bind_to_fun {α : Type u_1} [preorder α] {β : Type u_2} {γ : Type u_2} (f : α →ₘ roption β) (g : α →ₘ β → roption γ) (x : α) : coe_fn (bind f g) x = coe_fn f x >>= coe_fn g x :=
Eq.refl (coe_fn (bind f g) x)
end preorder_hom
namespace omega_complete_partial_order
/-- A chain is a monotonically increasing sequence.
See the definition on page 114 of [gunter]. -/
def chain (α : Type u) [preorder α] :=
ℕ →ₘ α
namespace chain
protected instance has_coe_to_fun {α : Type u} [preorder α] : has_coe_to_fun (chain α) :=
infer_instance
protected instance inhabited {α : Type u} [preorder α] [Inhabited α] : Inhabited (chain α) :=
{ default := preorder_hom.mk (fun (_x : ℕ) => Inhabited.default) sorry }
protected instance has_mem {α : Type u} [preorder α] : has_mem α (chain α) :=
has_mem.mk fun (a : α) (c : ℕ →ₘ α) => ∃ (i : ℕ), a = coe_fn c i
protected instance has_le {α : Type u} [preorder α] : HasLessEq (chain α) :=
{ LessEq := fun (x y : chain α) => ∀ (i : ℕ), ∃ (j : ℕ), coe_fn x i ≤ coe_fn y j }
/-- `map` function for `chain` -/
@[simp] theorem map_to_fun {α : Type u} {β : Type v} [preorder α] [preorder β] (c : chain α) (f : α →ₘ β) : ∀ (ᾰ : ℕ), coe_fn (map c f) ᾰ = coe_fn f (coe_fn c ᾰ) :=
fun (ᾰ : ℕ) => Eq.refl (coe_fn f (coe_fn c ᾰ))
theorem mem_map {α : Type u} {β : Type v} [preorder α] [preorder β] (c : chain α) {f : α →ₘ β} (x : α) : x ∈ c → coe_fn f x ∈ map c f := sorry
theorem exists_of_mem_map {α : Type u} {β : Type v} [preorder α] [preorder β] (c : chain α) {f : α →ₘ β} {b : β} : b ∈ map c f → ∃ (a : α), a ∈ c ∧ coe_fn f a = b := sorry
theorem mem_map_iff {α : Type u} {β : Type v} [preorder α] [preorder β] (c : chain α) {f : α →ₘ β} {b : β} : b ∈ map c f ↔ ∃ (a : α), a ∈ c ∧ coe_fn f a = b := sorry
@[simp] theorem map_id {α : Type u} [preorder α] (c : chain α) : map c preorder_hom.id = c :=
preorder_hom.comp_id c
theorem map_comp {α : Type u} {β : Type v} {γ : Type u_1} [preorder α] [preorder β] [preorder γ] (c : chain α) {f : α →ₘ β} (g : β →ₘ γ) : map (map c f) g = map c (preorder_hom.comp g f) :=
rfl
theorem map_le_map {α : Type u} {β : Type v} [preorder α] [preorder β] (c : chain α) {f : α →ₘ β} {g : α →ₘ β} (h : f ≤ g) : map c f ≤ map c g := sorry
/-- `chain.zip` pairs up the elements of two chains that have the same index -/
@[simp] theorem zip_to_fun {α : Type u} {β : Type v} [preorder α] [preorder β] (c₀ : chain α) (c₁ : chain β) : ∀ (ᾰ : ℕ), coe_fn (zip c₀ c₁) ᾰ = (coe_fn c₀ ᾰ, coe_fn c₁ ᾰ) :=
fun (ᾰ : ℕ) => Eq.refl (coe_fn c₀ ᾰ, coe_fn c₁ ᾰ)
end chain
end omega_complete_partial_order
/-- An omega-complete partial order is a partial order with a supremum
operation on increasing sequences indexed by natural numbers (which we
call `ωSup`). In this sense, it is strictly weaker than join complete
semi-lattices as only ω-sized totally ordered sets have a supremum.
See the definition on page 114 of [gunter]. -/
class omega_complete_partial_order (α : Type u_1)
extends partial_order α
where
ωSup : omega_complete_partial_order.chain α → α
le_ωSup : ∀ (c : omega_complete_partial_order.chain α) (i : ℕ), coe_fn c i ≤ ωSup c
ωSup_le : ∀ (c : omega_complete_partial_order.chain α) (x : α), (∀ (i : ℕ), coe_fn c i ≤ x) → ωSup c ≤ x
namespace omega_complete_partial_order
/-- Transfer a `omega_complete_partial_order` on `β` to a `omega_complete_partial_order` on `α` using
a strictly monotone function `f : β →ₘ α`, a definition of ωSup and a proof that `f` is continuous
with regard to the provided `ωSup` and the ωCPO on `α`. -/
protected def lift {α : Type u} {β : Type v} [omega_complete_partial_order α] [partial_order β] (f : β →ₘ α) (ωSup₀ : chain β → β) (h : ∀ (x y : β), coe_fn f x ≤ coe_fn f y → x ≤ y) (h' : ∀ (c : chain β), coe_fn f (ωSup₀ c) = ωSup (chain.map c f)) : omega_complete_partial_order β :=
mk ωSup₀ sorry sorry
theorem le_ωSup_of_le {α : Type u} [omega_complete_partial_order α] {c : chain α} {x : α} (i : ℕ) (h : x ≤ coe_fn c i) : x ≤ ωSup c :=
le_trans h (le_ωSup c i)
theorem ωSup_total {α : Type u} [omega_complete_partial_order α] {c : chain α} {x : α} (h : ∀ (i : ℕ), coe_fn c i ≤ x ∨ x ≤ coe_fn c i) : ωSup c ≤ x ∨ x ≤ ωSup c := sorry
theorem ωSup_le_ωSup_of_le {α : Type u} [omega_complete_partial_order α] {c₀ : chain α} {c₁ : chain α} (h : c₀ ≤ c₁) : ωSup c₀ ≤ ωSup c₁ :=
ωSup_le c₀ (ωSup c₁)
fun (i : ℕ) => Exists.rec_on (h i) fun (j : ℕ) (h : coe_fn c₀ i ≤ coe_fn c₁ j) => le_trans h (le_ωSup c₁ j)
theorem ωSup_le_iff {α : Type u} [omega_complete_partial_order α] (c : chain α) (x : α) : ωSup c ≤ x ↔ ∀ (i : ℕ), coe_fn c i ≤ x :=
{ mp := fun (ᾰ : ωSup c ≤ x) (i : ℕ) => le_trans (le_ωSup c i) ᾰ,
mpr := fun (ᾰ : ∀ (i : ℕ), coe_fn c i ≤ x) => ωSup_le c x ᾰ }
/-- A subset `p : α → Prop` of the type closed under `ωSup` induces an
`omega_complete_partial_order` on the subtype `{a : α // p a}`. -/
def subtype {α : Type u_1} [omega_complete_partial_order α] (p : α → Prop) (hp : ∀ (c : chain α), (∀ (i : α), i ∈ c → p i) → p (ωSup c)) : omega_complete_partial_order (Subtype p) :=
omega_complete_partial_order.lift (preorder_hom.subtype.val p)
(fun (c : chain (Subtype p)) => { val := ωSup (chain.map c (preorder_hom.subtype.val p)), property := sorry }) sorry
sorry
/-- A monotone function `f : α →ₘ β` is continuous if it distributes over ωSup.
In order to distinguish it from the (more commonly used) continuity from topology
(see topology/basic.lean), the present definition is often referred to as
"Scott-continuity" (referring to Dana Scott). It corresponds to continuity
in Scott topological spaces (not defined here). -/
def continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →ₘ β) :=
∀ (c : chain α), coe_fn f (ωSup c) = ωSup (chain.map c f)
/-- `continuous' f` asserts that `f` is both monotone and continuous. -/
def continuous' {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α → β) :=
∃ (hf : monotone f), continuous (preorder_hom.mk f hf)
theorem continuous.to_monotone {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] {f : α → β} (hf : continuous' f) : monotone f :=
Exists.fst hf
theorem continuous.of_bundled {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α → β) (hf : monotone f) (hf' : continuous (preorder_hom.mk f hf)) : continuous' f :=
Exists.intro hf hf'
theorem continuous.of_bundled' {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →ₘ β) (hf' : continuous f) : continuous' ⇑f :=
Exists.intro (preorder_hom.monotone f) hf'
theorem continuous.to_bundled {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α → β) (hf : continuous' f) : continuous (preorder_hom.mk f (continuous.to_monotone hf)) :=
Exists.snd hf
theorem continuous_id {α : Type u} [omega_complete_partial_order α] : continuous preorder_hom.id := sorry
theorem continuous_comp {α : Type u} {β : Type v} {γ : Type u_1} [omega_complete_partial_order α] [omega_complete_partial_order β] [omega_complete_partial_order γ] (f : α →ₘ β) (g : β →ₘ γ) (hfc : continuous f) (hgc : continuous g) : continuous (preorder_hom.comp g f) := sorry
theorem id_continuous' {α : Type u} [omega_complete_partial_order α] : continuous' id := sorry
theorem const_continuous' {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (x : β) : continuous' (function.const α x) := sorry
end omega_complete_partial_order
namespace roption
theorem eq_of_chain {α : Type u} {c : omega_complete_partial_order.chain (roption α)} {a : α} {b : α} (ha : some a ∈ c) (hb : some b ∈ c) : a = b := sorry
/-- The (noncomputable) `ωSup` definition for the `ω`-CPO structure on `roption α`. -/
protected def ωSup {α : Type u} (c : omega_complete_partial_order.chain (roption α)) : roption α :=
dite (∃ (a : α), some a ∈ c) (fun (h : ∃ (a : α), some a ∈ c) => some (classical.some h))
fun (h : ¬∃ (a : α), some a ∈ c) => none
theorem ωSup_eq_some {α : Type u} {c : omega_complete_partial_order.chain (roption α)} {a : α} (h : some a ∈ c) : roption.ωSup c = some a := sorry
theorem ωSup_eq_none {α : Type u} {c : omega_complete_partial_order.chain (roption α)} (h : ¬∃ (a : α), some a ∈ c) : roption.ωSup c = none :=
dif_neg h
theorem mem_chain_of_mem_ωSup {α : Type u} {c : omega_complete_partial_order.chain (roption α)} {a : α} (h : a ∈ roption.ωSup c) : some a ∈ c := sorry
protected instance omega_complete_partial_order {α : Type u} : omega_complete_partial_order (roption α) :=
omega_complete_partial_order.mk roption.ωSup sorry sorry
theorem mem_ωSup {α : Type u} (x : α) (c : omega_complete_partial_order.chain (roption α)) : x ∈ omega_complete_partial_order.ωSup c ↔ some x ∈ c := sorry
end roption
namespace pi
/-- Function application `λ f, f a` is monotone with respect to `f` for fixed `a`. -/
def monotone_apply {α : Type u_1} {β : α → Type u_2} [(a : α) → partial_order (β a)] (a : α) : ((a : α) → β a) →ₘ β a :=
preorder_hom.mk (fun (f : (a : α) → β a) => f a) sorry
protected instance omega_complete_partial_order {α : Type u_1} {β : α → Type u_2} [(a : α) → omega_complete_partial_order (β a)] : omega_complete_partial_order ((a : α) → β a) :=
omega_complete_partial_order.mk
(fun (c : omega_complete_partial_order.chain ((a : α) → β a)) (a : α) =>
omega_complete_partial_order.ωSup (omega_complete_partial_order.chain.map c (monotone_apply a)))
sorry sorry
namespace omega_complete_partial_order
theorem flip₁_continuous' {α : Type u_1} {β : α → Type u_2} {γ : Type u_3} [(x : α) → omega_complete_partial_order (β x)] [omega_complete_partial_order γ] (f : (x : α) → γ → β x) (a : α) (hf : omega_complete_partial_order.continuous' fun (x : γ) (y : α) => f y x) : omega_complete_partial_order.continuous' (f a) := sorry
theorem flip₂_continuous' {α : Type u_1} {β : α → Type u_2} {γ : Type u_3} [(x : α) → omega_complete_partial_order (β x)] [omega_complete_partial_order γ] (f : γ → (x : α) → β x) (hf : ∀ (x : α), omega_complete_partial_order.continuous' fun (g : γ) => f g x) : omega_complete_partial_order.continuous' f := sorry
end omega_complete_partial_order
end pi
namespace prod
/-- The supremum of a chain in the product `ω`-CPO. -/
protected def ωSup {α : Type u_1} {β : Type u_2} [omega_complete_partial_order α] [omega_complete_partial_order β] (c : omega_complete_partial_order.chain (α × β)) : α × β :=
(omega_complete_partial_order.ωSup (omega_complete_partial_order.chain.map c preorder_hom.prod.fst),
omega_complete_partial_order.ωSup (omega_complete_partial_order.chain.map c preorder_hom.prod.snd))
protected instance omega_complete_partial_order {α : Type u_1} {β : Type u_2} [omega_complete_partial_order α] [omega_complete_partial_order β] : omega_complete_partial_order (α × β) :=
omega_complete_partial_order.mk prod.ωSup sorry sorry
end prod
namespace complete_lattice
/-- Any complete lattice has an `ω`-CPO structure where the countable supremum is a special case
of arbitrary suprema. -/
protected instance omega_complete_partial_order (α : Type u) [complete_lattice α] : omega_complete_partial_order α :=
omega_complete_partial_order.mk (fun (c : omega_complete_partial_order.chain α) => supr fun (i : ℕ) => coe_fn c i) sorry
sorry
theorem inf_continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] [is_total β LessEq] (f : α →ₘ β) (g : α →ₘ β) (hf : omega_complete_partial_order.continuous f) (hg : omega_complete_partial_order.continuous g) : omega_complete_partial_order.continuous (f ⊓ g) := sorry
theorem Sup_continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] (s : set (α →ₘ β)) (hs : ∀ (f : α →ₘ β), f ∈ s → omega_complete_partial_order.continuous f) : omega_complete_partial_order.continuous (Sup s) := sorry
theorem Sup_continuous' {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] (s : set (α → β)) : (∀ (t : α → β), t ∈ s → omega_complete_partial_order.continuous' t) → omega_complete_partial_order.continuous' (Sup s) := sorry
theorem sup_continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] {f : α →ₘ β} {g : α →ₘ β} (hf : omega_complete_partial_order.continuous f) (hg : omega_complete_partial_order.continuous g) : omega_complete_partial_order.continuous (f ⊔ g) := sorry
theorem top_continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] : omega_complete_partial_order.continuous ⊤ := sorry
theorem bot_continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [complete_lattice β] : omega_complete_partial_order.continuous ⊥ := sorry
end complete_lattice
namespace omega_complete_partial_order
namespace preorder_hom
/-- Function application `λ f, f a` (for fixed `a`) is a monotone function from the
monotone function space `α →ₘ β` to `β`. -/
def monotone_apply {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (a : α) : (α →ₘ β) →ₘ β :=
preorder_hom.mk (fun (f : α →ₘ β) => coe_fn f a) sorry
/-- The "forgetful functor" from `α →ₘ β` to `α → β` that takes the underlying function,
is monotone. -/
def to_fun_hom {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] : (α →ₘ β) →ₘ α → β :=
preorder_hom.mk (fun (f : α →ₘ β) => preorder_hom.to_fun f) sorry
/-- The `ωSup` operator for monotone functions. -/
@[simp] theorem ωSup_to_fun {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c : chain (α →ₘ β)) (a : α) : coe_fn (preorder_hom.ωSup c) a = ωSup (chain.map c (monotone_apply a)) :=
Eq.refl (coe_fn (preorder_hom.ωSup c) a)
protected instance omega_complete_partial_order {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] : omega_complete_partial_order (α →ₘ β) :=
omega_complete_partial_order.lift to_fun_hom preorder_hom.ωSup sorry sorry
end preorder_hom
/-- A monotone function on `ω`-continuous partial orders is said to be continuous
if for every chain `c : chain α`, `f (⊔ i, c i) = ⊔ i, f (c i)`.
This is just the bundled version of `preorder_hom.continuous`. -/
structure continuous_hom (α : Type u) (β : Type v) [omega_complete_partial_order α] [omega_complete_partial_order β]
extends α →ₘ β
where
cont : continuous (preorder_hom.mk to_fun monotone')
infixr:25 " →𝒄 " => Mathlib.omega_complete_partial_order.continuous_hom
protected instance continuous_hom.has_coe_to_fun (α : Type u) (β : Type v) [omega_complete_partial_order α] [omega_complete_partial_order β] : has_coe_to_fun (α →𝒄 β) :=
has_coe_to_fun.mk (fun (_x : α →𝒄 β) => α → β) continuous_hom.to_fun
protected instance preorder_hom.has_coe (α : Type u) (β : Type v) [omega_complete_partial_order α] [omega_complete_partial_order β] : has_coe (α →𝒄 β) (α →ₘ β) :=
has_coe.mk continuous_hom.to_preorder_hom
protected instance continuous_hom.partial_order (α : Type u) (β : Type v) [omega_complete_partial_order α] [omega_complete_partial_order β] : partial_order (α →𝒄 β) :=
partial_order.lift continuous_hom.to_fun sorry
namespace continuous_hom
theorem congr_fun {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] {f : α →𝒄 β} {g : α →𝒄 β} (h : f = g) (x : α) : coe_fn f x = coe_fn g x :=
congr_arg (fun (h : α →𝒄 β) => coe_fn h x) h
theorem congr_arg {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) {x : α} {y : α} (h : x = y) : coe_fn f x = coe_fn f y :=
congr_arg (fun (x : α) => coe_fn f x) h
theorem monotone {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) : monotone ⇑f :=
monotone' f
theorem ite_continuous' {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] {p : Prop} [hp : Decidable p] (f : α → β) (g : α → β) (hf : continuous' f) (hg : continuous' g) : continuous' fun (x : α) => ite p (f x) (g x) := sorry
theorem ωSup_bind {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (c : chain α) (f : α →ₘ roption β) (g : α →ₘ β → roption γ) : ωSup (chain.map c (preorder_hom.bind f g)) = ωSup (chain.map c f) >>= ωSup (chain.map c g) := sorry
theorem bind_continuous' {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : α → roption β) (g : α → β → roption γ) : continuous' f → continuous' g → continuous' fun (x : α) => f x >>= g x := sorry
theorem map_continuous' {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : β → γ) (g : α → roption β) (hg : continuous' g) : continuous' fun (x : α) => f <$> g x := sorry
theorem seq_continuous' {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : α → roption (β → γ)) (g : α → roption β) (hf : continuous' f) (hg : continuous' g) : continuous' fun (x : α) => f x <*> g x := sorry
theorem continuous {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (F : α →𝒄 β) (C : chain α) : coe_fn F (ωSup C) = ωSup (chain.map C ↑F) :=
cont F C
/-- Construct a continuous function from a bare function, a continuous function, and a proof that
they are equal. -/
def of_fun {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α → β) (g : α →𝒄 β) (h : f = ⇑g) : α →𝒄 β :=
mk f sorry sorry
/-- Construct a continuous function from a monotone function with a proof of continuity. -/
def of_mono {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →ₘ β) (h : ∀ (c : chain α), coe_fn f (ωSup c) = ωSup (chain.map c f)) : α →𝒄 β :=
mk ⇑f sorry h
/-- The identity as a continuous function. -/
@[simp] theorem id_to_fun {α : Type u} [omega_complete_partial_order α] : ∀ (ᾰ : α), coe_fn id ᾰ = ᾰ :=
fun (ᾰ : α) => Eq.refl ᾰ
/-- The composition of continuous functions. -/
def comp {α : Type u} {β : Type v} {γ : Type u_3} [omega_complete_partial_order α] [omega_complete_partial_order β] [omega_complete_partial_order γ] (f : β →𝒄 γ) (g : α →𝒄 β) : α →𝒄 γ :=
of_mono (preorder_hom.comp ↑f ↑g) sorry
protected theorem ext {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) (g : α →𝒄 β) (h : ∀ (x : α), coe_fn f x = coe_fn g x) : f = g := sorry
protected theorem coe_inj {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) (g : α →𝒄 β) (h : ⇑f = ⇑g) : f = g :=
continuous_hom.ext f g (congr_fun h)
@[simp] theorem comp_id {β : Type v} {γ : Type u_3} [omega_complete_partial_order β] [omega_complete_partial_order γ] (f : β →𝒄 γ) : comp f id = f :=
continuous_hom.ext (comp f id) f fun (x : β) => Eq.refl (coe_fn (comp f id) x)
@[simp] theorem id_comp {β : Type v} {γ : Type u_3} [omega_complete_partial_order β] [omega_complete_partial_order γ] (f : β →𝒄 γ) : comp id f = f :=
continuous_hom.ext (comp id f) f fun (x : β) => Eq.refl (coe_fn (comp id f) x)
@[simp] theorem comp_assoc {α : Type u} {β : Type v} {γ : Type u_3} {φ : Type u_4} [omega_complete_partial_order α] [omega_complete_partial_order β] [omega_complete_partial_order γ] [omega_complete_partial_order φ] (f : γ →𝒄 φ) (g : β →𝒄 γ) (h : α →𝒄 β) : comp f (comp g h) = comp (comp f g) h :=
continuous_hom.ext (comp f (comp g h)) (comp (comp f g) h) fun (x : α) => Eq.refl (coe_fn (comp f (comp g h)) x)
@[simp] theorem coe_apply {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (a : α) (f : α →𝒄 β) : coe_fn (↑f) a = coe_fn f a :=
rfl
/-- `function.const` is a continuous function. -/
def const {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : β) : α →𝒄 β :=
of_mono (preorder_hom.const α f) sorry
@[simp] theorem const_apply {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : β) (a : α) : coe_fn (const f) a = f :=
rfl
protected instance inhabited {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] [Inhabited β] : Inhabited (α →𝒄 β) :=
{ default := const Inhabited.default }
namespace prod
/-- The application of continuous functions as a monotone function.
(It would make sense to make it a continuous function, but we are currently constructing a
`omega_complete_partial_order` instance for `α →𝒄 β`, and we cannot use it as the domain or image
of a continuous function before we do.) -/
def apply {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] : (α →𝒄 β) × α →ₘ β :=
preorder_hom.mk (fun (f : (α →𝒄 β) × α) => coe_fn (prod.fst f) (prod.snd f)) sorry
end prod
/-- The map from continuous functions to monotone functions is itself a monotone function. -/
@[simp] theorem to_mono_to_fun {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (f : α →𝒄 β) : coe_fn to_mono f = ↑f :=
Eq.refl (coe_fn to_mono f)
/-- When proving that a chain of applications is below a bound `z`, it suffices to consider the
functions and values being selected from the same index in the chains.
This lemma is more specific than necessary, i.e. `c₀` only needs to be a
chain of monotone functions, but it is only used with continuous functions. -/
@[simp] theorem forall_forall_merge {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (i j : ℕ), coe_fn (coe_fn c₀ i) (coe_fn c₁ j) ≤ z) ↔ ∀ (i : ℕ), coe_fn (coe_fn c₀ i) (coe_fn c₁ i) ≤ z := sorry
@[simp] theorem forall_forall_merge' {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c₀ : chain (α →𝒄 β)) (c₁ : chain α) (z : β) : (∀ (j i : ℕ), coe_fn (coe_fn c₀ i) (coe_fn c₁ j) ≤ z) ↔ ∀ (i : ℕ), coe_fn (coe_fn c₀ i) (coe_fn c₁ i) ≤ z := sorry
/-- The `ωSup` operator for continuous functions, which takes the pointwise countable supremum
of the functions in the `ω`-chain. -/
protected def ωSup {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c : chain (α →𝒄 β)) : α →𝒄 β :=
of_mono (ωSup (chain.map c to_mono)) sorry
protected instance omega_complete_partial_order {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] : omega_complete_partial_order (α →𝒄 β) :=
omega_complete_partial_order.lift to_mono continuous_hom.ωSup sorry sorry
theorem ωSup_def {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c : chain (α →𝒄 β)) (x : α) : coe_fn (ωSup c) x = coe_fn (continuous_hom.ωSup c) x :=
rfl
theorem ωSup_ωSup {α : Type u} {β : Type v} [omega_complete_partial_order α] [omega_complete_partial_order β] (c₀ : chain (α →𝒄 β)) (c₁ : chain α) : coe_fn (ωSup c₀) (ωSup c₁) = ωSup (preorder_hom.comp prod.apply (chain.zip c₀ c₁)) := sorry
/-- A family of continuous functions yields a continuous family of functions. -/
def flip {β : Type v} {γ : Type u_3} [omega_complete_partial_order β] [omega_complete_partial_order γ] {α : Type u_1} (f : α → β →𝒄 γ) : β →𝒄 α → γ :=
mk (fun (x : β) (y : α) => coe_fn (f y) x) sorry sorry
/-- `roption.bind` as a continuous function. -/
def bind {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : α →𝒄 roption β) (g : α →𝒄 β → roption γ) : α →𝒄 roption γ :=
of_mono (preorder_hom.bind ↑f ↑g) sorry
/-- `roption.map` as a continuous function. -/
@[simp] theorem map_to_fun {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : β → γ) (g : α →𝒄 roption β) (x : α) : coe_fn (map f g) x = f <$> coe_fn g x :=
Eq.refl (coe_fn (map f g) x)
/-- `roption.seq` as a continuous function. -/
def seq {α : Type u} [omega_complete_partial_order α] {β : Type v} {γ : Type v} (f : α →𝒄 roption (β → γ)) (g : α →𝒄 roption β) : α →𝒄 roption γ :=
of_fun (fun (x : α) => coe_fn f x <*> coe_fn g x) (bind f (flip (flip map g))) sorry
|
4f8b629992874619de4d3f6c4dab6adb32a9184c | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/native_run/hello_world.lean | 6986a54ceb542382082425f6a799bd64345e94f6 | [
"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 | 75 | lean | import system.IO
definition main : IO unit :=
put_str "Hello Lean!\n"
|
a9bedb1925cd67f82821c64dc3a5721f5b532695 | c777c32c8e484e195053731103c5e52af26a25d1 | /archive/imo/imo2011_q5.lean | abf6897ad352d6705ce9e3d445e71352d2e92304 | [
"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 | 2,087 | lean | /-
Copyright (c) 2021 Alain Verberkmoes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alain Verberkmoes
-/
import data.int.dvd.basic
/-!
# IMO 2011 Q5
Let `f` be a function from the set of integers to the set
of positive integers. Suppose that, for any two integers
`m` and `n`, the difference `f(m) - f(n)` is divisible by
`f(m - n)`. Prove that, for all integers `m` and `n` with
`f(m) ≤ f(n)`, the number `f(n)` is divisible by `f(m)`.
-/
open int
theorem imo2011_q5 (f : ℤ → ℤ) (hpos : ∀ n : ℤ, 0 < f n)
(hdvd : ∀ m n : ℤ, f (m - n) ∣ f m - f n) :
∀ m n : ℤ, f m ≤ f n → f m ∣ f n :=
begin
intros m n h_fm_le_fn,
cases lt_or_eq_of_le h_fm_le_fn with h_fm_lt_fn h_fm_eq_fn,
{ -- m < n
let d := f m - f (m - n),
have h_fn_dvd_d : f n ∣ d,
{ rw ←sub_sub_self m n,
exact hdvd m (m - n) },
have h_d_lt_fn : d < f n,
{ calc d < f m : sub_lt_self _ (hpos (m - n))
... < f n : h_fm_lt_fn },
have h_neg_d_lt_fn : -d < f n,
{ calc -d = f (m - n) - f m : neg_sub _ _
... < f (m - n) : sub_lt_self _ (hpos m)
... ≤ f n - f m : le_of_dvd (sub_pos.mpr h_fm_lt_fn) _
... < f n : sub_lt_self _ (hpos m),
-- ⊢ f (m - n) ∣ f n - f m
rw [←dvd_neg, neg_sub], exact hdvd m n },
have h_d_eq_zero : d = 0,
{ obtain (hd | hd | hd) : d > 0 ∨ d = 0 ∨ d < 0 := trichotomous d 0,
{ -- d > 0
have h₁ : f n ≤ d, from le_of_dvd hd h_fn_dvd_d,
have h₂ : ¬ f n ≤ d, from not_le.mpr h_d_lt_fn,
contradiction },
{ -- d = 0
exact hd },
{ -- d < 0
have h₁ : f n ≤ -d, from le_of_dvd (neg_pos.mpr hd) h_fn_dvd_d.neg_right,
have h₂ : ¬ f n ≤ -d, from not_le.mpr h_neg_d_lt_fn,
contradiction } },
have h₁ : f m = f (m - n), from sub_eq_zero.mp h_d_eq_zero,
have h₂ : f (m - n) ∣ f m - f n, from hdvd m n,
rw ←h₁ at h₂,
exact (dvd_iff_dvd_of_dvd_sub h₂).mp dvd_rfl },
{ -- m = n
rw h_fm_eq_fn }
end
|
340217a2ad8c11c41010075e994745a1e11795ac | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/combinators_auto.lean | 3ad073eac0c6dc5268e0a1b5a77435022cf756ad | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,892 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
Monad combinators, as in Haskell's Control.Monad.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.monad
import Mathlib.Lean3Lib.init.control.alternative
import Mathlib.Lean3Lib.init.data.list.basic
universes u v w u_1 u_2 u_3
namespace Mathlib
def list.mmap {m : Type u → Type v} [Monad m] {α : Type w} {β : Type u} (f : α → m β) :
List α → m (List β) :=
sorry
def list.mmap' {m : Type → Type v} [Monad m] {α : Type u} {β : Type} (f : α → m β) :
List α → m Unit :=
sorry
def mjoin {m : Type u → Type u} [Monad m] {α : Type u} (a : m (m α)) : m α := a >>= id
def list.mfilter {m : Type → Type v} [Monad m] {α : Type} (f : α → m Bool) : List α → m (List α) :=
sorry
def list.mfoldl {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} :
(s → α → m s) → s → List α → m s :=
sorry
def list.mfoldr {m : Type u → Type v} [Monad m] {s : Type u} {α : Type w} :
(α → s → m s) → s → List α → m s :=
sorry
def list.mfirst {m : Type u → Type v} [Monad m] [alternative m] {α : Type w} {β : Type u}
(f : α → m β) : List α → m β :=
sorry
def when {m : Type → Type} [Monad m] (c : Prop) [h : Decidable c] (t : m Unit) : m Unit :=
ite c t (pure Unit.unit)
def mcond {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm : m α) (fm : m α) : m α :=
do
let b ← mbool
cond b tm fm
def mwhen {m : Type → Type} [Monad m] (c : m Bool) (t : m Unit) : m Unit :=
mcond c t (return Unit.unit)
namespace monad
def mapm {m : Type u_1 → Type u_2} [Monad m] {α : Type u_3} {β : Type u_1} (f : α → m β) :
List α → m (List β) :=
mmap
def mapm' {m : Type → Type u_1} [Monad m] {α : Type u_2} {β : Type} (f : α → m β) :
List α → m Unit :=
mmap'
def join {m : Type u_1 → Type u_1} [Monad m] {α : Type u_1} (a : m (m α)) : m α := mjoin
def filter {m : Type → Type u_1} [Monad m] {α : Type} (f : α → m Bool) : List α → m (List α) :=
mfilter
def foldl {m : Type u_1 → Type u_2} [Monad m] {s : Type u_1} {α : Type u_3} :
(s → α → m s) → s → List α → m s :=
mfoldl
def cond {m : Type → Type} [Monad m] {α : Type} (mbool : m Bool) (tm : m α) (fm : m α) : m α :=
mcond
def sequence {m : Type u → Type v} [Monad m] {α : Type u} : List (m α) → m (List α) := sorry
def sequence' {m : Type → Type u} [Monad m] {α : Type} : List (m α) → m Unit := sorry
def whenb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit :=
cond b t (return Unit.unit)
def unlessb {m : Type → Type} [Monad m] (b : Bool) (t : m Unit) : m Unit :=
cond b (return Unit.unit) t
end Mathlib |
397e49b8ea573b4bf3e678dc34bbd8fa5dca6ac6 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/equiv/transfer_instance.lean | d439a1e07940e1e3defc3c9e71e3e97680a32fbb | [
"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 | 12,041 | 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
-/
import data.equiv.basic
import algebra.field
import algebra.module
import algebra.algebra.basic
import algebra.group.type_tags
import ring_theory.ideal.basic
/-!
# Transfer algebraic structures across `equiv`s
In this file we prove theorems of the following form: if `β` has a
group structure and `α ≃ β` then `α` has a group structure, and
similarly for monoids, semigroups, rings, integral domains, fields and
so on.
Note that most of these constructions can also be obtained using the `transport` tactic.
## Tags
equiv, group, ring, field, module, algebra
-/
universes u v
variables {α : Type u} {β : Type v}
namespace equiv
section instances
variables (e : α ≃ β)
/-- Transfer `has_one` across an `equiv` -/
@[to_additive "Transfer `has_zero` across an `equiv`"]
protected def has_one [has_one β] : has_one α := ⟨e.symm 1⟩
@[to_additive]
lemma one_def [has_one β] : @has_one.one _ (equiv.has_one e) = e.symm 1 := rfl
/-- Transfer `has_mul` across an `equiv` -/
@[to_additive "Transfer `has_add` across an `equiv`"]
protected def has_mul [has_mul β] : has_mul α := ⟨λ x y, e.symm (e x * e y)⟩
@[to_additive]
lemma mul_def [has_mul β] (x y : α) :
@has_mul.mul _ (equiv.has_mul e) x y = e.symm (e x * e y) := rfl
/-- Transfer `has_div` across an `equiv` -/
@[to_additive "Transfer `has_sub` across an `equiv`"]
protected def has_div [has_div β] : has_div α := ⟨λ x y, e.symm (e x / e y)⟩
@[to_additive]
lemma div_def [has_div β] (x y : α) :
@has_div.div _ (equiv.has_div e) x y = e.symm (e x / e y) := rfl
/-- Transfer `has_inv` across an `equiv` -/
@[to_additive "Transfer `has_neg` across an `equiv`"]
protected def has_inv [has_inv β] : has_inv α := ⟨λ x, e.symm (e x)⁻¹⟩
@[to_additive]
lemma inv_def [has_inv β] (x : α) : @has_inv.inv _ (equiv.has_inv e) x = e.symm (e x)⁻¹ := rfl
/-- Transfer `has_scalar` across an `equiv` -/
protected def has_scalar {R : Type*} [has_scalar R β] : has_scalar R α :=
⟨λ r x, e.symm (r • (e x))⟩
lemma smul_def {R : Type*} [has_scalar R β] (r : R) (x : α) :
@has_scalar.smul _ _ (equiv.has_scalar e) r x = e.symm (r • (e x)) := rfl
/--
An equivalence `e : α ≃ β` gives a multiplicative equivalence `α ≃* β`
where the multiplicative structure on `α` is
the one obtained by transporting a multiplicative structure on `β` back along `e`.
-/
@[to_additive
"An equivalence `e : α ≃ β` gives a additive equivalence `α ≃+ β`
where the additive structure on `α` is
the one obtained by transporting an additive structure on `β` back along `e`."]
def mul_equiv (e : α ≃ β) [has_mul β] :
by { letI := equiv.has_mul e, exact α ≃* β } :=
begin
introsI,
exact
{ map_mul' := λ x y, by { apply e.symm.injective, simp, refl, },
..e }
end
@[simp, to_additive] lemma mul_equiv_apply (e : α ≃ β) [has_mul β] (a : α) :
(mul_equiv e) a = e a := rfl
@[to_additive] lemma mul_equiv_symm_apply (e : α ≃ β) [has_mul β] (b : β) :
by { letI := equiv.has_mul e, exact (mul_equiv e).symm b = e.symm b } :=
begin
intros, refl,
end
/--
An equivalence `e : α ≃ β` gives a ring equivalence `α ≃+* β`
where the ring structure on `α` is
the one obtained by transporting a ring structure on `β` back along `e`.
-/
def ring_equiv (e : α ≃ β) [has_add β] [has_mul β] :
by { letI := equiv.has_add e, letI := equiv.has_mul e, exact α ≃+* β } :=
begin
introsI,
exact
{ map_add' := λ x y, by { apply e.symm.injective, simp, refl, },
map_mul' := λ x y, by { apply e.symm.injective, simp, refl, },
..e }
end
@[simp] lemma ring_equiv_apply (e : α ≃ β) [has_add β] [has_mul β] (a : α) :
(ring_equiv e) a = e a := rfl
lemma ring_equiv_symm_apply (e : α ≃ β) [has_add β] [has_mul β] (b : β) :
by { letI := equiv.has_add e, letI := equiv.has_mul e, exact (ring_equiv e).symm b = e.symm b } :=
begin
intros, refl,
end
/-- Transfer `semigroup` across an `equiv` -/
@[to_additive "Transfer `add_semigroup` across an `equiv`"]
protected def semigroup [semigroup β] : semigroup α :=
let mul := e.has_mul in
by resetI; apply e.injective.semigroup _; intros; exact e.apply_symm_apply _
/-- Transfer `comm_semigroup` across an `equiv` -/
@[to_additive "Transfer `add_comm_semigroup` across an `equiv`"]
protected def comm_semigroup [comm_semigroup β] : comm_semigroup α :=
let mul := e.has_mul in
by resetI; apply e.injective.comm_semigroup _; intros; exact e.apply_symm_apply _
/-- Transfer `mul_zero_class` across an `equiv` -/
protected def mul_zero_class [mul_zero_class β] : mul_zero_class α :=
let zero := e.has_zero, mul := e.has_mul in
by resetI; apply e.injective.mul_zero_class _; intros; exact e.apply_symm_apply _
/-- Transfer `mul_one_class` across an `equiv` -/
@[to_additive "Transfer `add_zero_class` across an `equiv`"]
protected def mul_one_class [mul_one_class β] : mul_one_class α :=
let one := e.has_one, mul := e.has_mul in
by resetI; apply e.injective.mul_one_class _; intros; exact e.apply_symm_apply _
/-- Transfer `monoid` across an `equiv` -/
@[to_additive "Transfer `add_monoid` across an `equiv`"]
protected def monoid [monoid β] : monoid α :=
let one := e.has_one, mul := e.has_mul in
by resetI; apply e.injective.monoid _; intros; exact e.apply_symm_apply _
/-- Transfer `comm_monoid` across an `equiv` -/
@[to_additive "Transfer `add_comm_monoid` across an `equiv`"]
protected def comm_monoid [comm_monoid β] : comm_monoid α :=
let one := e.has_one, mul := e.has_mul in
by resetI; apply e.injective.comm_monoid _; intros; exact e.apply_symm_apply _
/-- Transfer `group` across an `equiv` -/
@[to_additive "Transfer `add_group` across an `equiv`"]
protected def group [group β] : group α :=
let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in
by resetI; apply e.injective.group _; intros; exact e.apply_symm_apply _
/-- Transfer `comm_group` across an `equiv` -/
@[to_additive "Transfer `add_comm_group` across an `equiv`"]
protected def comm_group [comm_group β] : comm_group α :=
let one := e.has_one, mul := e.has_mul, inv := e.has_inv, div := e.has_div in
by resetI; apply e.injective.comm_group _; intros; exact e.apply_symm_apply _
/-- Transfer `semiring` across an `equiv` -/
protected def semiring [semiring β] : semiring α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in
by resetI; apply e.injective.semiring _; intros; exact e.apply_symm_apply _
/-- Transfer `comm_semiring` across an `equiv` -/
protected def comm_semiring [comm_semiring β] : comm_semiring α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul in
by resetI; apply e.injective.comm_semiring _; intros; exact e.apply_symm_apply _
/-- Transfer `ring` across an `equiv` -/
protected def ring [ring β] : ring α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub in
by resetI; apply e.injective.ring _; intros; exact e.apply_symm_apply _
/-- Transfer `comm_ring` across an `equiv` -/
protected def comm_ring [comm_ring β] : comm_ring α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub in
by resetI; apply e.injective.comm_ring _; intros; exact e.apply_symm_apply _
/-- Transfer `nonzero` across an `equiv` -/
protected theorem nontrivial [nontrivial β] : nontrivial α :=
e.surjective.nontrivial
/-- Transfer `domain` across an `equiv` -/
protected def domain [domain β] : domain α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub in
by resetI; apply e.injective.domain _; intros; exact e.apply_symm_apply _
/-- Transfer `integral_domain` across an `equiv` -/
protected def integral_domain [integral_domain β] : integral_domain α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub in
by resetI; apply e.injective.integral_domain _; intros; exact e.apply_symm_apply _
/-- Transfer `division_ring` across an `equiv` -/
protected def division_ring [division_ring β] : division_ring α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub, inv := e.has_inv, div := e.has_div in
by resetI; apply e.injective.division_ring _; intros; exact e.apply_symm_apply _
/-- Transfer `field` across an `equiv` -/
protected def field [field β] : field α :=
let zero := e.has_zero, add := e.has_add, one := e.has_one, mul := e.has_mul, neg := e.has_neg,
sub := e.has_sub, inv := e.has_inv, div := e.has_div in
by resetI; apply e.injective.field _; intros; exact e.apply_symm_apply _
section R
variables (R : Type*)
include R
section
variables [monoid R]
/-- Transfer `mul_action` across an `equiv` -/
protected def mul_action (e : α ≃ β) [mul_action R β] : mul_action R α :=
{ one_smul := by simp [smul_def],
mul_smul := by simp [smul_def, mul_smul],
..equiv.has_scalar e }
/-- Transfer `distrib_mul_action` across an `equiv` -/
protected def distrib_mul_action (e : α ≃ β) [add_comm_monoid β] :
begin
letI := equiv.add_comm_monoid e,
exact Π [distrib_mul_action R β], distrib_mul_action R α
end :=
begin
intros,
letI := equiv.add_comm_monoid e,
exact (
{ smul_zero := by simp [zero_def, smul_def],
smul_add := by simp [add_def, smul_def, smul_add],
..equiv.mul_action R e } : distrib_mul_action R α)
end
end
section
variables [semiring R]
/-- Transfer `semimodule` across an `equiv` -/
protected def semimodule (e : α ≃ β) [add_comm_monoid β] :
begin
letI := equiv.add_comm_monoid e,
exact Π [semimodule R β], semimodule R α
end :=
begin
introsI,
exact (
{ zero_smul := by simp [zero_def, smul_def],
add_smul := by simp [add_def, smul_def, add_smul],
..equiv.distrib_mul_action R e } : semimodule R α)
end
/--
An equivalence `e : α ≃ β` gives a linear equivalence `α ≃ₗ[R] β`
where the `R`-module structure on `α` is
the one obtained by transporting an `R`-module structure on `β` back along `e`.
-/
def linear_equiv (e : α ≃ β) [add_comm_monoid β] [semimodule R β] :
begin
letI := equiv.add_comm_monoid e,
letI := equiv.semimodule R e,
exact α ≃ₗ[R] β
end :=
begin
introsI,
exact
{ map_smul' := λ r x, by { apply e.symm.injective, simp, refl, },
..equiv.add_equiv e }
end
end
section
variables [comm_semiring R]
/-- Transfer `algebra` across an `equiv` -/
protected def algebra (e : α ≃ β) [semiring β] :
begin
letI := equiv.semiring e,
exact Π [algebra R β], algebra R α
end :=
begin
introsI,
fapply ring_hom.to_algebra',
{ exact ((ring_equiv e).symm : β →+* α).comp (algebra_map R β), },
{ intros r x,
simp only [function.comp_app, ring_hom.coe_comp],
have p := ring_equiv_symm_apply e,
dsimp at p,
erw p, clear p,
apply (ring_equiv e).injective,
simp only [(ring_equiv e).map_mul],
simp [algebra.commutes], }
end
/--
An equivalence `e : α ≃ β` gives an algebra equivalence `α ≃ₐ[R] β`
where the `R`-algebra structure on `α` is
the one obtained by transporting an `R`-algebra structure on `β` back along `e`.
-/
def alg_equiv (e : α ≃ β) [semiring β] [algebra R β] :
begin
letI := equiv.semiring e,
letI := equiv.algebra R e,
exact α ≃ₐ[R] β
end :=
begin
introsI,
exact
{ commutes' := λ r, by { apply e.symm.injective, simp, refl, },
..equiv.ring_equiv e }
end
end
end R
end instances
end equiv
namespace ring_equiv
protected lemma local_ring {A B : Type*} [comm_ring A] [local_ring A] [comm_ring B] (e : A ≃+* B) :
local_ring B :=
begin
haveI := e.symm.to_equiv.nontrivial,
refine @local_of_surjective A B _ _ _ _ e e.to_equiv.surjective,
end
end ring_equiv
|
a7214462b023a4383ec5880adae8f021cd79195a | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/data/int/parity.lean | 7c5184bc1a61018051053a9419fde7addc3fcc15 | [
"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 | 6,997 | lean | /-
Copyright (c) 2019 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Benjamin Davidson
-/
import data.int.modeq
import data.nat.parity
/-!
# Parity of integers
This file contains theorems about the `even` and `odd` predicates on the integers.
## Tags
even, odd
-/
namespace int
variables {m n : ℤ}
@[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
local attribute [simp] -- euclidean_domain.mod_eq_zero uses (2 ∣ n) as normal form
theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 :=
by cases mod_two_eq_zero_or_one n with h h; simp [h]
theorem even_iff : even n ↔ n % 2 = 0 :=
⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩
theorem odd_iff : odd n ↔ n % 2 = 1 :=
⟨λ ⟨m, hm⟩, by { rw [hm, add_mod], norm_num },
λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by { rw h, abel })⟩⟩
lemma not_even_iff : ¬ even n ↔ n % 2 = 1 :=
by rw [even_iff, mod_two_ne_zero]
lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 :=
by rw [odd_iff, mod_two_ne_one]
lemma even_iff_not_odd : even n ↔ ¬ odd n :=
by rw [not_odd_iff, even_iff]
@[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n :=
by rw [not_even_iff, odd_iff]
lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} :=
by simp [← set.compl_set_of, is_compl_compl]
lemma even_or_odd (n : ℤ) : even n ∨ odd n :=
or.imp_right odd_iff_not_even.2 $ em $ even n
lemma even_or_odd' (n : ℤ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 :=
by simpa only [exists_or_distrib, ← odd, ← even] using even_or_odd n
lemma even_xor_odd (n : ℤ) : xor (even n) (odd n) :=
begin
cases even_or_odd n with h,
{ exact or.inl ⟨h, even_iff_not_odd.mp h⟩ },
{ exact or.inr ⟨h, odd_iff_not_even.mp h⟩ },
end
lemma even_xor_odd' (n : ℤ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) :=
begin
rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩;
use k,
{ simpa only [xor, true_and, eq_self_iff_true, not_true, or_false, and_false]
using (succ_ne_self (2*k)).symm },
{ simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff,
one_ne_zero, and_self] },
end
@[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 :=
not_even_iff
instance : decidable_pred (even : ℤ → Prop) :=
λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm
instance decidable_pred_odd : decidable_pred (odd : ℤ → Prop) :=
λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm
@[simp] theorem even_zero : even (0 : ℤ) := ⟨0, dec_trivial⟩
@[simp] theorem not_even_one : ¬ even (1 : ℤ) :=
by rw even_iff; norm_num
@[simp] theorem even_bit0 (n : ℤ) : even (bit0 n) :=
⟨n, by rw [bit0, two_mul]⟩
@[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) :=
by 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₂, int.add_mod];
norm_num
theorem even.add_even (hm : even m) (hn : even n) : even (m + n) :=
even_add.2 $ iff_of_true hm hn
theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) :=
by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not]
theorem odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) :=
even_add'.2 $ iff_of_true hm hn
@[simp] theorem not_even_bit1 (n : ℤ) : ¬ even (bit1 n) :=
by simp [bit1] with parity_simps
lemma two_not_dvd_two_mul_add_one (n : ℤ) : ¬(2 ∣ 2 * n + 1) :=
by convert not_even_bit1 n; exact two_mul n
@[parity_simps] theorem even_sub : even (m - n) ↔ (even m ↔ even n) :=
by simp [sub_eq_add_neg] with parity_simps
theorem even.sub_even (hm : even m) (hn : even n) : even (m - n) :=
even_sub.2 $ iff_of_true hm hn
theorem even_sub' : even (m - n) ↔ (odd m ↔ odd n) :=
by rw [even_sub, even_iff_not_odd, even_iff_not_odd, not_iff_not]
theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) :=
even_sub'.2 $ iff_of_true hm hn
@[parity_simps] theorem even_add_one : even (n + 1) ↔ ¬ even n :=
by simp [even_add]
@[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n :=
by 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₂, int.mul_mod];
norm_num
theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n :=
by simp [not_or_distrib] with parity_simps
theorem even.mul_left (hm : even m) (n : ℤ) : even (m * n) :=
even_mul.mpr $ or.inl hm
theorem even.mul_right (m : ℤ) (hn : even n) : even (m * n) :=
even_mul.mpr $ or.inr hn
theorem odd.mul (hm : odd m) (hn : odd n) : odd (m * n) :=
odd_mul.mpr ⟨hm, hn⟩
theorem odd.of_mul_left (h : odd (m * n)) : odd m :=
(odd_mul.mp h).1
theorem odd.of_mul_right (h : odd (m * n)) : odd n :=
(odd_mul.mp h).2
@[parity_simps] theorem even_pow {n : ℕ} : even (m ^ n) ↔ even m ∧ n ≠ 0 :=
by { induction n with n ih; simp [*, even_mul, pow_succ], tauto }
theorem even_pow' {n : ℕ} (h : n ≠ 0) : even (m ^ n) ↔ even m :=
even_pow.trans $ and_iff_left h
@[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) :=
by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even]
theorem odd.add_even (hm : odd m) (hn : even n) : odd (m + n) :=
odd_add.2 $ iff_of_true hm hn
theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) :=
by rw [add_comm, odd_add]
theorem even.add_odd (hm : even m) (hn : odd n) : odd (m + n) :=
odd_add'.2 $ iff_of_true hn hm
lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n :=
λ hnot, by simpa [hnot] with parity_simps using h
@[parity_simps] theorem odd_sub : odd (m - n) ↔ (odd m ↔ even n) :=
by rw [odd_iff_not_even, even_sub, not_iff, odd_iff_not_even]
theorem odd.sub_even (hm : odd m) (hn : even n) : odd (m - n) :=
odd_sub.2 $ iff_of_true hm hn
theorem odd_sub' : odd (m - n) ↔ (odd n ↔ even m) :=
by rw [odd_iff_not_even, even_sub, not_iff, not_iff_comm, odd_iff_not_even]
theorem even.sub_odd (hm : even m) (hn : odd n) : odd (m - n) :=
odd_sub'.2 $ iff_of_true hn hm
lemma even_mul_succ_self (n : ℤ) : even (n * (n + 1)) :=
begin
rw even_mul,
convert n.even_or_odd,
simp with parity_simps
end
@[simp, norm_cast] theorem even_coe_nat (n : ℕ) : even (n : ℤ) ↔ even n :=
by rw_mod_cast [even_iff, nat.even_iff]
@[simp, norm_cast] theorem odd_coe_nat (n : ℕ) : odd (n : ℤ) ↔ odd n :=
by rw [odd_iff_not_even, nat.odd_iff_not_even, even_coe_nat]
@[simp] theorem nat_abs_even : even n.nat_abs ↔ even n :=
coe_nat_dvd_left.symm
@[simp] theorem nat_abs_odd : odd n.nat_abs ↔ odd n :=
by rw [odd_iff_not_even, nat.odd_iff_not_even, nat_abs_even]
-- Here are examples of how `parity_simps` can be used with `int`.
example (m n : ℤ) (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 int
|
0e20e4699f8aec109f2fc1e7d8b7377a1d5ab7d8 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/nat/factorial/big_operators.lean | e31c5f242280bb6ee441b6443aab7468b10e3a11 | [
"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,216 | lean | /-
Copyright (c) 2022 Pim Otte. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kyle Miller, Pim Otte
-/
import data.nat.factorial.basic
import algebra.big_operators.order
/-!
# Factorial with big operators
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains some lemmas on factorials in combination with big operators.
While in terms of semantics they could be in the `basic.lean` file, importing
`algebra.big_operators.basic` leads to a cyclic import.
-/
open_locale nat big_operators
namespace nat
variables {α : Type*} (s : finset α) (f : α → ℕ)
lemma prod_factorial_pos : 0 < ∏ i in s, (f i)! :=
finset.prod_pos (λ i _, factorial_pos (f i))
lemma prod_factorial_dvd_factorial_sum : (∏ i in s, (f i)!) ∣ (∑ i in s, f i)! :=
begin
classical,
induction s using finset.induction with a' s' has ih,
{ simp only [finset.sum_empty, finset.prod_empty, factorial], },
{ simp only [finset.prod_insert has, finset.sum_insert has],
refine dvd_trans (mul_dvd_mul_left ((f a')!) ih) _,
apply nat.factorial_mul_factorial_dvd_factorial_add, },
end
end nat
|
ffbc56784b99f726eba6a12109cf2079a16dbaa7 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/open_namespaces.lean | aebd8185134122eec178d1f4bd776ad7be5d25af | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 92 | lean | open nat
namespace foo
open int
run_command tactic.open_namespaces >>= tactic.trace
end foo
|
e3454c50b571b82702cd1e93d5643868435f4a42 | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/tactic/linarith.lean | 79b015a0cc0c497568dbb644c4aa20a45094040d | [
"Apache-2.0"
] | permissive | aceg00/mathlib | 5e15e79a8af87ff7eb8c17e2629c442ef24e746b | 8786ea6d6d46d6969ac9a869eb818bf100802882 | refs/heads/master | 1,649,202,698,930 | 1,580,924,783,000 | 1,580,924,783,000 | 149,197,272 | 0 | 0 | Apache-2.0 | 1,537,224,208,000 | 1,537,224,207,000 | null | UTF-8 | Lean | false | false | 33,018 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
-/
import tactic.ring data.nat.gcd data.list.basic meta.rb_map data.tree
/-!
A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination.
`linarith` is (in principle) complete for ℚ and ℝ. It is not complete for non-dense orders, i.e. ℤ.
@TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains
@TODO: delay proofs of denominator normalization and nat casting until after contradiction is found
-/
meta def nat.to_pexpr : ℕ → pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))
open native
namespace linarith
section lemmas
lemma int.coe_nat_bit0 (n : ℕ) : (↑(bit0 n : ℕ) : ℤ) = bit0 (↑n : ℤ) := by simp [bit0]
lemma int.coe_nat_bit1 (n : ℕ) : (↑(bit1 n : ℕ) : ℤ) = bit1 (↑n : ℤ) := by simp [bit1, bit0]
lemma int.coe_nat_bit0_mul (n : ℕ) (x : ℕ) : (↑(bit0 n * x) : ℤ) = (↑(bit0 n) : ℤ) * (↑x : ℤ) := by simp
lemma int.coe_nat_bit1_mul (n : ℕ) (x : ℕ) : (↑(bit1 n * x) : ℤ) = (↑(bit1 n) : ℤ) * (↑x : ℤ) := by simp
lemma int.coe_nat_one_mul (x : ℕ) : (↑(1 * x) : ℤ) = 1 * (↑x : ℤ) := by simp
lemma int.coe_nat_zero_mul (x : ℕ) : (↑(0 * x) : ℤ) = 0 * (↑x : ℤ) := by simp
lemma int.coe_nat_mul_bit0 (n : ℕ) (x : ℕ) : (↑(x * bit0 n) : ℤ) = (↑x : ℤ) * (↑(bit0 n) : ℤ) := by simp
lemma int.coe_nat_mul_bit1 (n : ℕ) (x : ℕ) : (↑(x * bit1 n) : ℤ) = (↑x : ℤ) * (↑(bit1 n) : ℤ) := by simp
lemma int.coe_nat_mul_one (x : ℕ) : (↑(x * 1) : ℤ) = (↑x : ℤ) * 1 := by simp
lemma int.coe_nat_mul_zero (x : ℕ) : (↑(x * 0) : ℤ) = (↑x : ℤ) * 0 := by simp
lemma nat_eq_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 = n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 = z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff]
lemma nat_le_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 ≤ n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 ≤ z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le]
lemma nat_lt_subst {n1 n2 : ℕ} {z1 z2 : ℤ} (hn : n1 < n2) (h1 : ↑n1 = z1) (h2 : ↑n2 = z2) : z1 < z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt]
lemma eq_of_eq_of_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b = 0) : a + b = 0 :=
by simp *
lemma le_of_eq_of_le {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b ≤ 0) : a + b ≤ 0 :=
by simp *
lemma lt_of_eq_of_lt {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b < 0) : a + b < 0 :=
by simp *
lemma le_of_le_of_eq {α} [ordered_semiring α] {a b : α} (ha : a ≤ 0) (hb : b = 0) : a + b ≤ 0 :=
by simp *
lemma lt_of_lt_of_eq {α} [ordered_semiring α] {a b : α} (ha : a < 0) (hb : b = 0) : a + b < 0 :=
by simp *
lemma mul_neg {α} [ordered_ring α] {a b : α} (ha : a < 0) (hb : b > 0) : b * a < 0 :=
have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha,
neg_of_neg_pos (by simpa)
lemma mul_nonpos {α} [ordered_ring α] {a b : α} (ha : a ≤ 0) (hb : b > 0) : b * a ≤ 0 :=
have (-b)*a ≥ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha,
(by simpa)
lemma mul_eq {α} [ordered_semiring α] {a b : α} (ha : a = 0) (hb : b > 0) : b * a = 0 :=
by simp *
lemma eq_of_not_lt_of_not_gt {α} [linear_order α] (a b : α) (h1 : ¬ a < b) (h2 : ¬ b < a) : a = b :=
le_antisymm (le_of_not_gt h2) (le_of_not_gt h1)
lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *]
lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *]
lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp *
private meta def apnn : tactic unit := `[norm_num]
lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2)
(h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 :=
have h3 : n1 * n2 = k, from h3,
by rw [←h3, mul_comm n1, mul_assoc n2, ←mul_assoc n1, h1, ←mul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH
lemma div_subst {α} [field α] {n1 n2 k e1 e2 t1 : α} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) :
k * (e1 / e2) = t1 :=
by rw [←h3, mul_assoc, mul_div_comm, h2, ←mul_assoc, h1, mul_comm, one_mul]
end lemmas
section datatypes
@[derive decidable_eq, derive inhabited]
inductive ineq
| eq | le | lt
open ineq
def ineq.max : ineq → ineq → ineq
| eq a := a
| le a := a
| lt a := lt
def ineq.is_lt : ineq → ineq → bool
| eq le := tt
| eq lt := tt
| le lt := tt
| _ _ := ff
def ineq.to_string : ineq → string
| eq := "="
| le := "≤"
| lt := "<"
instance : has_to_string ineq := ⟨ineq.to_string⟩
/--
The main datatype for FM elimination.
Variables are represented by natural numbers, each of which has an integer coefficient.
Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1.
The represented term is coeffs.keys.sum (λ i, coeffs.find i * Var[i]).
str determines the direction of the comparison -- is it < 0, ≤ 0, or = 0?
-/
@[derive _root_.inhabited]
meta structure comp :=
(str : ineq)
(coeffs : rb_map ℕ int)
meta inductive comp_source
| assump : ℕ → comp_source
| add : comp_source → comp_source → comp_source
| scale : ℕ → comp_source → comp_source
meta def comp_source.flatten : comp_source → rb_map ℕ ℕ
| (comp_source.assump n) := mk_rb_map.insert n 1
| (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2)
| (comp_source.scale n c) := (comp_source.flatten c).map (λ v, v * n)
meta def comp_source.to_string : comp_source → string
| (comp_source.assump e) := to_string e
| (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2
| (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c
meta instance comp_source.has_to_format : has_to_format comp_source :=
⟨λ a, comp_source.to_string a⟩
meta structure pcomp :=
(c : comp)
(src : comp_source)
meta def map_lt (m1 m2 : rb_map ℕ int) : bool :=
list.lex (prod.lex (<) (<)) m1.to_list m2.to_list
-- make more efficient
meta def comp.lt (c1 c2 : comp) : bool :=
(c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs
meta instance comp.has_lt : has_lt comp := ⟨λ a b, comp.lt a b⟩
meta instance pcomp.has_lt : has_lt pcomp := ⟨λ p1 p2, p1.c < p2.c⟩
-- short-circuit type class inference
meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp → pcomp → Prop) := by apply_instance
meta def comp.coeff_of (c : comp) (a : ℕ) : ℤ :=
c.coeffs.zfind a
meta def comp.scale (c : comp) (n : ℕ) : comp :=
{ c with coeffs := c.coeffs.map ((*) (n : ℤ)) }
meta def comp.add (c1 c2 : comp) : comp :=
⟨c1.str.max c2.str, c1.coeffs.add c2.coeffs⟩
meta def pcomp.scale (c : pcomp) (n : ℕ) : pcomp :=
⟨c.c.scale n, comp_source.scale n c.src⟩
meta def pcomp.add (c1 c2 : pcomp) : pcomp :=
⟨c1.c.add c2.c, comp_source.add c1.src c2.src⟩
meta instance pcomp.to_format : has_to_format pcomp :=
⟨λ p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"⟩
meta instance comp.to_format : has_to_format comp :=
⟨λ p, to_fmt p.coeffs⟩
end datatypes
section fm_elim
/-- If c1 and c2 both contain variable a with opposite coefficients,
produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/
meta def elim_var (c1 c2 : comp) (a : ℕ) : option (ℕ × ℕ × comp) :=
let v1 := c1.coeff_of a,
v2 := c2.coeff_of a in
if v1 * v2 < 0 then
let vlcm := nat.lcm v1.nat_abs v2.nat_abs,
v1' := vlcm / v1.nat_abs,
v2' := vlcm / v2.nat_abs in
some ⟨v1', v2', comp.add (c1.scale v1') (c2.scale v2')⟩
else none
meta def pelim_var (p1 p2 : pcomp) (a : ℕ) : option pcomp :=
do (n1, n2, c) ← elim_var p1.c p2.c a,
return ⟨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)⟩
meta def comp.is_contr (c : comp) : bool := c.coeffs.empty ∧ c.str = ineq.lt
meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr
meta def elim_with_set (a : ℕ) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp :=
if ¬ p.c.coeffs.contains a then mk_rb_set.insert p else
comps.fold mk_rb_set $ λ pc s,
match pelim_var p pc a with
| some pc := s.insert pc
| none := s
end
/--
The state for the elimination monad.
vars: the set of variables present in comps
comps: a set of comparisons
inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, ≤, =} 0,
indexed by ℕ.
has_false: stores a pcomp of 0 < 0 if one has been found
TODO: is it more efficient to store comps as a list, to avoid comparisons?
-/
meta structure linarith_structure :=
(vars : rb_set ℕ)
(comps : rb_set pcomp)
@[reducible] meta def linarith_monad :=
state_t linarith_structure (except_t pcomp id)
meta instance : monad linarith_monad := state_t.monad
meta instance : monad_except pcomp linarith_monad :=
state_t.monad_except pcomp
meta def get_vars : linarith_monad (rb_set ℕ) :=
linarith_structure.vars <$> get
meta def get_var_list : linarith_monad (list ℕ) :=
rb_set.to_list <$> get_vars
meta def get_comps : linarith_monad (rb_set pcomp) :=
linarith_structure.comps <$> get
meta def validate : linarith_monad unit :=
do ⟨_, comps⟩ ← get,
match comps.to_list.find (λ p : pcomp, p.is_contr) with
| none := return ()
| some c := throw c
end
meta def update (vars : rb_set ℕ) (comps : rb_set pcomp) : linarith_monad unit :=
state_t.put ⟨vars, comps⟩ >> validate
meta def monad.elim_var (a : ℕ) : linarith_monad unit :=
do vs ← get_vars,
when (vs.contains a) $
do comps ← get_comps,
let cs' := comps.fold mk_rb_set (λ p s, s.union (elim_with_set a p comps)),
update (vs.erase a) cs'
meta def elim_all_vars : linarith_monad unit :=
get_var_list >>= list.mmap' monad.elim_var
end fm_elim
section parse
open ineq tactic
meta def map_of_expr_mul_aux (c1 c2 : rb_map ℕ ℤ) : option (rb_map ℕ ℤ) :=
match c1.keys, c2.keys with
| [0], _ := some $ c2.scale (c1.zfind 0)
| _, [0] := some $ c1.scale (c2.zfind 0)
| [], _ := some mk_rb_map
| _, [] := some mk_rb_map
| _, _ := none
end
meta def list.mfind {α} (tac : α → tactic unit) : list α → tactic α
| [] := failed
| (h::t) := tac h >> return h <|> list.mfind t
meta def rb_map.find_defeq (red : transparency) {v} (m : expr_map v) (e : expr) : tactic v :=
prod.snd <$> list.mfind (λ p, is_def_eq e p.1 red) m.to_list
/--
Turns an expression into a map from ℕ to ℤ, for use in a comp object.
The expr_map ℕ argument identifies which expressions have already been assigned numbers.
Returns a new map.
-/
meta def map_of_expr (red : transparency) : expr_map ℕ → expr → tactic (expr_map ℕ × rb_map ℕ ℤ)
| m e@`(%%e1 * %%e2) :=
(do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
mp ← map_of_expr_mul_aux comp1 comp2,
return (m', mp)) <|>
(do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|>
(let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1))
| m `(%%e1 + %%e2) :=
do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
return (m', comp1.add comp2)
| m `(%%e1 - %%e2) :=
do (m', comp1) ← map_of_expr m e1,
(m', comp2) ← map_of_expr m' e2,
return (m', comp1.add (comp2.scale (-1)))
| m `(-%%e) := do (m', comp) ← map_of_expr m e, return (m', comp.scale (-1))
| m e :=
match e.to_int with
| some 0 := return ⟨m, mk_rb_map⟩
| some z := return ⟨m, mk_rb_map.insert 0 z⟩
| none :=
(do k ← rb_map.find_defeq red m e, return (m, mk_rb_map.insert k 1)) <|>
(let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1))
end
meta def parse_into_comp_and_expr : expr → option (ineq × expr)
| `(%%e < 0) := (ineq.lt, e)
| `(%%e ≤ 0) := (ineq.le, e)
| `(%%e = 0) := (ineq.eq, e)
| _ := none
meta def to_comp (red : transparency) (e : expr) (m : expr_map ℕ) : tactic (comp × expr_map ℕ) :=
do (iq, e) ← parse_into_comp_and_expr e,
(m', comp') ← map_of_expr red m e,
return ⟨⟨iq, comp'⟩, m'⟩
meta def to_comp_fold (red : transparency) : expr_map ℕ → list expr →
tactic (list (option comp) × expr_map ℕ)
| m [] := return ([], m)
| m (h::t) :=
(do (c, m') ← to_comp red h m,
(l, mp) ← to_comp_fold m' t,
return (c::l, mp)) <|>
(do (l, mp) ← to_comp_fold m t,
return (none::l, mp))
/--
Takes a list of proofs of props of the form t {<, ≤, =} 0, and creates a linarith_structure.
-/
meta def mk_linarith_structure (red : transparency) (l : list expr) : tactic (linarith_structure × rb_map ℕ (expr × expr)) :=
do pftps ← l.mmap infer_type,
(l', map) ← to_comp_fold red mk_rb_map pftps,
let lz := list.enum $ ((l.zip pftps).zip l').filter_map (λ ⟨a, b⟩, prod.mk a <$> b),
let prmap := rb_map.of_list $ lz.map (λ ⟨n, x⟩, (n, x.1)),
let vars : rb_set ℕ := rb_map.set_of_list $ list.range map.size.succ,
let pc : rb_set pcomp := rb_map.set_of_list $
lz.map (λ ⟨n, x⟩, ⟨x.2, comp_source.assump n⟩),
return (⟨vars, pc⟩, prmap)
meta def linarith_monad.run (red : transparency) {α} (tac : linarith_monad α) (l : list expr) : tactic ((pcomp ⊕ α) × rb_map ℕ (expr × expr)) :=
do (struct, inputs) ← mk_linarith_structure red l,
match (state_t.run (validate >> tac) struct).run with
| (except.ok (a, _)) := return (sum.inr a, inputs)
| (except.error contr) := return (sum.inl contr, inputs)
end
end parse
section prove
open ineq tactic
meta def get_rel_sides : expr → tactic (expr × expr)
| `(%%a < %%b) := return (a, b)
| `(%%a ≤ %%b) := return (a, b)
| `(%%a = %%b) := return (a, b)
| `(%%a ≥ %%b) := return (a, b)
| `(%%a > %%b) := return (a, b)
| _ := failed
meta def mul_expr (n : ℕ) (e : expr) : pexpr :=
if n = 1 then ``(%%e) else
``(%%(nat.to_pexpr n) * %%e)
meta def add_exprs_aux : pexpr → list pexpr → pexpr
| p [] := p
| p [a] := ``(%%p + %%a)
| p (h::t) := add_exprs_aux ``(%%p + %%h) t
meta def add_exprs : list pexpr → pexpr
| [] := ``(0)
| (h::t) := add_exprs_aux h t
meta def find_contr (m : rb_set pcomp) : option pcomp :=
m.keys.find (λ p, p.c.is_contr)
meta def ineq_const_mul_nm : ineq → name
| lt := ``mul_neg
| le := ``mul_nonpos
| eq := ``mul_eq
meta def ineq_const_nm : ineq → ineq → (name × ineq)
| eq eq := (``eq_of_eq_of_eq, eq)
| eq le := (``le_of_eq_of_le, le)
| eq lt := (``lt_of_eq_of_lt, lt)
| le eq := (``le_of_le_of_eq, le)
| le le := (`add_nonpos, le)
| le lt := (`add_neg_of_nonpos_of_neg, lt)
| lt eq := (``lt_of_lt_of_eq, lt)
| lt le := (`add_neg_of_neg_of_nonpos, lt)
| lt lt := (`add_neg, lt)
meta def mk_single_comp_zero_pf (c : ℕ) (h : expr) : tactic (ineq × expr) :=
do tp ← infer_type h,
some (iq, e) ← return $ parse_into_comp_and_expr tp,
if c = 0 then
do e' ← mk_app ``zero_mul [e], return (eq, e')
else if c = 1 then return (iq, h)
else
do nm ← resolve_name (ineq_const_mul_nm iq),
tp ← (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type,
cpos ← to_expr ``((%%c.to_pexpr : %%tp) > 0),
(_, ex) ← solve_aux cpos `[norm_num, done],
-- e' ← mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why?
e' ← to_expr ``(%%nm %%h %%ex) ff,
return (iq, e')
meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : ℕ) : tactic (ineq × expr) :=
do (iq, h') ← mk_single_comp_zero_pf coeff npf,
let (nm, niq) := ineq_const_nm c iq,
n ← resolve_name nm,
e' ← to_expr ``(%%n %%pf %%h'),
return (niq, e')
/--
Takes a list of coefficients [c] and list of expressions, of equal length.
Each expression is a proof of a prop of the form t {<, ≤, =} 0.
Produces a proof that the sum of (c*t) {<, ≤, =} 0, where the comp is as strong as possible.
-/
meta def mk_lt_zero_pf : list ℕ → list expr → tactic expr
| _ [] := fail "no linear hypotheses found"
| [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h
| (c::ct) (h::t) :=
do (iq, h') ← mk_single_comp_zero_pf c h,
prod.snd <$> (ct.zip t).mfoldl (λ pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h')
| _ _ := fail "not enough args to mk_lt_zero_pf"
meta def term_of_ineq_prf (prf : expr) : tactic expr :=
do (lhs, _) ← infer_type prf >>= get_rel_sides,
return lhs
meta structure linarith_config :=
(discharger : tactic unit := `[ring])
(restrict_type : option Type := none)
(restrict_type_reflect : reflected restrict_type . apply_instance)
(exfalso : bool := tt)
(transparency : transparency := reducible)
meta def ineq_pf_tp (pf : expr) : tactic expr :=
do (_, z) ← infer_type pf >>= get_rel_sides,
infer_type z
meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr :=
to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp)))
/--
Assumes e is a proof that t = 0. Creates a proof that -t = 0.
-/
meta def mk_neg_eq_zero_pf (e : expr) : tactic expr :=
to_expr ``(neg_eq_zero.mpr %%e)
meta def add_neg_eq_pfs : list expr → tactic (list expr)
| [] := return []
| (h::t) :=
do some (iq, tp) ← parse_into_comp_and_expr <$> infer_type h,
match iq with
| ineq.eq := do nep ← mk_neg_eq_zero_pf h, tl ← add_neg_eq_pfs t, return $ h::nep::tl
| _ := list.cons h <$> add_neg_eq_pfs t
end
/--
Takes a list of proofs of propositions of the form t {<, ≤, =} 0,
and tries to prove the goal `false`.
-/
meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr → tactic unit
| [] := fail "no args to linarith"
| l@(h::t) :=
do l' ← add_neg_eq_pfs l,
hz ← ineq_pf_tp h >>= mk_neg_one_lt_zero_pf,
(sum.inl contr, inputs) ← elim_all_vars.run cfg.transparency (hz::l')
| fail "linarith failed to find a contradiction",
let coeffs := inputs.keys.map (λ k, (contr.src.flatten.ifind k)),
let pfs : list expr := inputs.keys.map (λ k, (inputs.ifind k).1),
let zip := (coeffs.zip pfs).filter (λ pr, pr.1 ≠ 0),
let (coeffs, pfs) := zip.unzip,
mls ← zip.mmap (λ pr, do e ← term_of_ineq_prf pr.2, return (mul_expr pr.1 e)),
sm ← to_expr $ add_exprs mls,
tgt ← to_expr ``(%%sm = 0),
(a, b) ← solve_aux tgt (cfg.discharger >> done),
pf ← mk_lt_zero_pf coeffs pfs,
pftp ← infer_type pf,
(_, nep, _) ← rewrite_core b pftp,
pf' ← mk_eq_mp nep pf,
mk_app `lt_irrefl [pf'] >>= exact
end prove
section normalize
open tactic
set_option eqn_compiler.max_steps 50000
meta def rem_neg (prf : expr) : expr → tactic expr
| `(_ ≤ _) := to_expr ``(lt_of_not_ge %%prf)
| `(_ < _) := to_expr ``(le_of_not_gt %%prf)
| `(_ > _) := to_expr ``(le_of_not_gt %%prf)
| `(_ ≥ _) := to_expr ``(lt_of_not_ge %%prf)
| e := failed
meta def rearr_comp : expr → expr → tactic expr
| prf `(%%a ≤ 0) := return prf
| prf `(%%a < 0) := return prf
| prf `(%%a = 0) := return prf
| prf `(%%a ≥ 0) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(0 ≥ %%a) := to_expr ``(show %%a ≤ 0, from %%prf)
| prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf)
| prf `(0 = %%a) := to_expr ``(eq.symm %%prf)
| prf `(0 ≤ %%a) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(%%a ≤ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf)
| prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a ≥ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(¬ %%t) := do nprf ← rem_neg prf t, tp ← infer_type nprf, rearr_comp nprf tp
| prf _ := fail "couldn't rearrange comp"
meta def is_numeric : expr → option ℚ
| `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2
| `(-%%e) := rat.neg <$> is_numeric e
| e := e.to_rat
meta def find_cancel_factor : expr → ℕ × tree ℕ
| `(%%e1 + %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 - %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 * %%e2) :=
match is_numeric e1, is_numeric e2 with
| none, none := (1, tree.node 1 tree.nil tree.nil)
| _, _ :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in
(pd, tree.node pd t1 t2)
end
| `(%%e1 / %%e2) :=
match is_numeric e2 with
| some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in
(n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil))
| none := (1, tree.node 1 tree.nil tree.nil)
end
| `(-%%e) := find_cancel_factor e
| _ := (1, tree.node 1 tree.nil tree.nil)
open tree
meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr
| v (node _ lhs rhs) `(%%e1 + %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2]
| v (node _ lhs rhs) `(%%e1 - %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2]
| v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2,
ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v,
ntp ← to_expr ``(%%ln' * %%vln' = %%v'),
(_, npf) ← solve_aux ntp `[norm_num, done],
mk_app ``mul_subst [v1, v2, npf]
| v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1,
rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v,
ntp ← to_expr ``(%%rn' / %%e2 = 1),
(_, npf) ← solve_aux ntp `[norm_num, done],
ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'),
(_, npf2) ← solve_aux ntp2 `[norm_num, done],
mk_app ``div_subst [v1, npf, npf2]
| v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v']
| v _ e :=
do tp ← infer_type e,
v' ← tp.of_nat v,
e' ← to_expr ``(%%v' * %%e),
mk_app `eq.refl [e']
/--
e is a term with rational division. produces a natural number n and a proof that n*e = e',
where e' has no division.
-/
meta def kill_factors (e : expr) : tactic (ℕ × expr) :=
let (n, t) := find_cancel_factor e in
do e' ← mk_prod_prf n t e, return (n, e')
open expr
meta def expr_contains (n : name) : expr → bool
| (const nm _) := nm = n
| (lam _ _ _ bd) := expr_contains bd
| (pi _ _ _ bd) := expr_contains bd
| (app e1 e2) := expr_contains e1 || expr_contains e2
| _ := ff
lemma sub_into_lt {α} [ordered_semiring α] {a b : α} (he : a = b) (hl : a ≤ 0) : b ≤ 0 :=
by rwa he at hl
meta def norm_hyp_aux (h' lhs : expr) : tactic expr :=
do (v, lhs') ← kill_factors lhs,
if v = 1 then return h' else do
(ih, h'') ← mk_single_comp_zero_pf v h',
(_, nep, _) ← infer_type h'' >>= rewrite_core lhs',
mk_eq_mp nep h''
meta def norm_hyp (h : expr) : tactic expr :=
do htp ← infer_type h,
h' ← rearr_comp h htp,
some (c, lhs) ← parse_into_comp_and_expr <$> infer_type h',
if expr_contains `has_div.div lhs then
norm_hyp_aux h' lhs
else return h'
meta def get_contr_lemma_name : expr → option name
| `(%%a < %%b) := return `lt_of_not_ge
| `(%%a ≤ %%b) := return `le_of_not_gt
| `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt
| `(%%a ≠ %%b) := return `not.intro
| `(%%a ≥ %%b) := return `le_of_not_gt
| `(%%a > %%b) := return `lt_of_not_ge
| `(¬ %%a < %%b) := return `not.intro
| `(¬ %%a ≤ %%b) := return `not.intro
| `(¬ %%a = %%b) := return `not.intro
| `(¬ %%a ≥ %%b) := return `not.intro
| `(¬ %%a > %%b) := return `not.intro
| _ := none
-- assumes the input t is of type ℕ. Produces t' of type ℤ such that ↑t = t' and a proof of equality
meta def cast_expr (e : expr) : tactic (expr × expr) :=
do s ← [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one,
``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul,
``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one,
``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk,
ce ← to_expr ``(↑%%e : ℤ),
simplify s [] ce {fail_if_unchanged := ff}
meta def is_nat_int_coe : expr → option expr
| `((↑(%%n : ℕ) : ℤ)) := some n
| _ := none
meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr :=
mk_app `int.coe_nat_nonneg [e]
meta def get_nat_comps : expr → list expr
| `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b)
| `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b)
| e := match is_nat_int_coe e with
| some e' := [e']
| none := []
end
meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) :=
(get_nat_comps e).mmap mk_coe_nat_nonneg_prf
meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) :=
do (a', prfa) ← cast_expr a,
(b', prfb) ← cast_expr b,
la ← mk_coe_nat_nonneg_prfs a',
lb ← mk_coe_nat_nonneg_prfs b',
pf' ← mk_app ln [pf, prfa, prfb],
return $ pf'::(la.append lb)
meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) :=
do tp ← infer_type pf,
match tp with
| `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst
| `(%%a ≤ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst
| `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst
| `(%%a ≥ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst
| `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst
| `(¬ %%a ≤ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst
| `(¬ %%a < %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst
| `(¬ %%a ≥ %%b) := do pf' ← mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst
| `(¬ %%a > %%b) := do pf' ← mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst
| _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality"
end
meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr :=
do tp ← infer_type pf,
match tp with
| `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) %%pf)
| `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) %%pf)
| `(¬ %%a ≤ %%b) := to_expr ``(@cast (%%a > %%b) (%%a ≥ %%b + 1) (by refl) (lt_of_not_ge %%pf))
| `(¬ %%a ≥ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 ≤ %%b) (by refl) (lt_of_not_ge %%pf))
| _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality"
end
meta def guard_is_nat_prop : expr → tactic unit
| `(%%a = _) := infer_type a >>= unify `(ℕ)
| `(%%a ≤ _) := infer_type a >>= unify `(ℕ)
| `(%%a < _) := infer_type a >>= unify `(ℕ)
| `(%%a ≥ _) := infer_type a >>= unify `(ℕ)
| `(%%a > _) := infer_type a >>= unify `(ℕ)
| `(¬ %%p) := guard_is_nat_prop p
| _ := failed
meta def guard_is_strict_int_prop : expr → tactic unit
| `(%%a < _) := infer_type a >>= unify `(ℤ)
| `(%%a > _) := infer_type a >>= unify `(ℤ)
| `(¬ %%a ≤ _) := infer_type a >>= unify `(ℤ)
| `(¬ %%a ≥ _) := infer_type a >>= unify `(ℤ)
| _ := failed
meta def replace_nat_pfs : list expr → tactic (list expr)
| [] := return []
| (h::t) :=
(do infer_type h >>= guard_is_nat_prop,
ls ← mk_int_pfs_of_nat_pf h,
list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t
meta def replace_strict_int_pfs : list expr → tactic (list expr)
| [] := return []
| (h::t) :=
(do infer_type h >>= guard_is_strict_int_prop,
l ← mk_non_strict_int_pf_of_strict_int_pf h,
list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t
meta def partition_by_type_aux : rb_lmap expr expr → list expr → tactic (rb_lmap expr expr)
| m [] := return m
| m (h::t) := do tp ← ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t
meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) :=
partition_by_type_aux mk_rb_map l
private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit :=
(first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed"
/--
Takes a list of proofs of propositions.
Filters out the proofs of linear (in)equalities,
and tries to use them to prove `false`.
If pref_type is given, starts by working over this type
-/
meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit :=
do l' ← replace_nat_pfs l,
l'' ← replace_strict_int_pfs l',
ls ← list.reduce_option <$> l''.mmap (λ h, (do s ← norm_hyp h, return (some s)) <|> return none)
>>= partition_by_type,
pref_type ← (unify pref_type.iget `(ℕ) >> return (some `(ℤ) : option expr)) <|> return pref_type,
match cfg.restrict_type, ls.values, pref_type with
| some rtp, _, _ :=
do m ← mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m ← instantiate_mvars m,
prove_false_by_linarith1 cfg (ls.ifind m)
| none, [ls'], _ := prove_false_by_linarith1 cfg ls'
| none, ls', none := try_linarith_on_lists cfg ls'
| none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values
end
end normalize
end linarith
section
open tactic linarith
open lean lean.parser interactive tactic interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def linarith.elab_arg_list : option (list pexpr) → tactic (list expr)
| none := return []
| (some l) := l.mmap i_to_expr
meta def linarith.preferred_type_of_goal : option expr → tactic (option expr)
| none := return none
| (some e) := some <$> ineq_pf_tp e
/--
linarith.interactive_aux cfg o_goal restrict_hyps args:
* cfg is a linarith_config object
* o_goal : option expr is the local constant corresponding to the former goal, if there was one
* restrict_hyps : bool is tt if `linarith only [...]` was used
* args : option (list pexpr) is the optional list of arguments in `linarith [...]`
-/
meta def linarith.interactive_aux (cfg : linarith_config) :
option expr → bool → option (list pexpr) → tactic unit
| none tt none := fail "linarith only called with no arguments"
| none tt (some l) := l.mmap i_to_expr >>= prove_false_by_linarith cfg none
| (some e) tt l :=
do tp ← ineq_pf_tp e,
list.cons e <$> linarith.elab_arg_list l >>= prove_false_by_linarith cfg (some tp)
| oe ff l :=
do otp ← linarith.preferred_type_of_goal oe,
list.append <$> local_context <*>
(list.filter (λ a, bnot $ expr.is_local_constant a) <$> linarith.elab_arg_list l) >>=
prove_false_by_linarith cfg otp
/--
Tries to prove a goal of `false` by linear arithmetic on hypotheses.
If the goal is a linear (in)equality, tries to prove it by contradiction.
If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the
hypotheses.
`linarith` will use all relevant hypotheses in the local context.
`linarith [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context.
`linarith only [h1, h2, h3, t1, t2, t3]` will use only the goal (if relevant), local hypotheses
h1, h2, h3, and proofs t1, t2, t3. It will ignore the rest of the local context.
`linarith!` will use a stronger reducibility setting to identify atoms.
Config options:
`linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false`
`linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T`
`linarith {discharger := tac}` will use `tac` instead of `ring` for normalization.
Options: `ring2`, `ring SOP`, `simp`
-/
meta def tactic.interactive.linarith (red : parse ((tk "!")?))
(restr : parse ((tk "only")?)) (hyps : parse pexpr_list?)
(cfg : linarith_config := {}) : tactic unit :=
let cfg :=
if red.is_some then {cfg with transparency := semireducible, discharger := `[ring!]}
else cfg in
do t ← target,
match get_contr_lemma_name t with
| some nm := seq (applyc nm) $
do t ← intro1, linarith.interactive_aux cfg (some t) restr.is_some hyps
| none := if cfg.exfalso then exfalso >> linarith.interactive_aux cfg none restr.is_some hyps
else fail "linarith failed: target type is not an inequality."
end
end
|
ffa0473af41130a52d57167576987643589ba3e6 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/category_theory/preadditive/biproducts.lean | 1cf7658ff7818b271d2471f487fc65a9e94b6bd8 | [
"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 | 11,481 | 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 tactic.abel
import category_theory.limits.shapes.biproducts
import category_theory.preadditive
/-!
# Basic facts about morphisms between biproducts in preadditive categories.
* In any category (with zero morphisms), if `biprod.map f g` is an isomorphism,
then both `f` and `g` are isomorphisms.
The remaining lemmas hold in any preadditive category.
* If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,
then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`
so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),
via Gaussian elimination.
* As a corollary of the previous two facts,
if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,
we can construct an isomorphism `X₂ ≅ Y₂`.
* If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`,
or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero.
* If `f : ⨁ S ⟶ ⨁ T` is an isomorphism,
then every column (corresponding to a nonzero summand in the domain)
has some nonzero matrix entry.
-/
open category_theory
open category_theory.preadditive
open category_theory.limits
universes v u
noncomputable theory
namespace category_theory
variables {C : Type u} [category.{v} C]
section
variables [has_zero_morphisms.{v} C] [has_binary_biproducts.{v} C]
/--
If
```
(f 0)
(0 g)
```
is invertible, then `f` is invertible.
-/
def is_iso_left_of_is_iso_biprod_map
{W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso f :=
{ inv := biprod.inl ≫ inv (biprod.map f g) ≫ biprod.fst,
hom_inv_id' :=
begin
have t := congr_arg (λ p : W ⊞ X ⟶ W ⊞ X, biprod.inl ≫ p ≫ biprod.fst)
(is_iso.hom_inv_id (biprod.map f g)),
simp only [category.id_comp, category.assoc, biprod.inl_map_assoc] at t,
simp [t],
end,
inv_hom_id' :=
begin
have t := congr_arg (λ p : Y ⊞ Z ⟶ Y ⊞ Z, biprod.inl ≫ p ≫ biprod.fst)
(is_iso.inv_hom_id (biprod.map f g)),
simp only [category.id_comp, category.assoc, biprod.map_fst] at t,
simp only [category.assoc],
simp [t],
end }
/--
If
```
(f 0)
(0 g)
```
is invertible, then `g` is invertible.
-/
def is_iso_right_of_is_iso_biprod_map
{W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso g :=
begin
letI : is_iso (biprod.map g f) := by
{ rw [←biprod.braiding_map_braiding],
apply_instance, },
exact is_iso_left_of_is_iso_biprod_map g f,
end
end
section
variables [preadditive.{v} C] [has_binary_biproducts.{v} C]
variables {X₁ X₂ Y₁ Y₂ : C}
variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂)
/--
The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components.
-/
def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ :=
biprod.fst ≫ f₁₁ ≫ biprod.inl +
biprod.fst ≫ f₁₂ ≫ biprod.inr +
biprod.snd ≫ f₂₁ ≫ biprod.inl +
biprod.snd ≫ f₂₂ ≫ biprod.inr
@[simp]
lemma biprod.inl_of_components :
biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ =
f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr :=
by simp [biprod.of_components]
@[simp]
lemma biprod.inr_of_components :
biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ =
f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr :=
by simp [biprod.of_components]
@[simp]
lemma biprod.of_components_fst :
biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst =
biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ :=
by simp [biprod.of_components]
@[simp]
lemma biprod.of_components_snd :
biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd =
biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ :=
by simp [biprod.of_components]
@[simp]
lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) :
biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd)
(biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f :=
begin
ext; simp,
end
@[simp]
lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C}
(f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂)
(g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) :
biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ =
biprod.of_components
(f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂)
(f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) :=
begin
dsimp [biprod.of_components],
apply biprod.hom_ext; apply biprod.hom_ext';
simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add,
biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd,
biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc,
comp_zero, zero_comp,
category.comp_id, category.assoc],
end
/--
The unipotent upper triangular matrix
```
(1 r)
(0 1)
```
as an isomorphism.
-/
@[simps]
def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ :=
{ hom := biprod.of_components (𝟙 _) r 0 (𝟙 _),
inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), }
/--
The unipotent lower triangular matrix
```
(1 0)
(r 1)
```
as an isomorphism.
-/
@[simps]
def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ :=
{ hom := biprod.of_components (𝟙 _) 0 r (𝟙 _),
inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), }
/--
If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,
then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`
so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),
via Gaussian elimination.
(This is the version of `biprod.gaussian` written in terms of components.)
-/
def biprod.gaussian' [is_iso f₁₁] :
Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂),
L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ :=
⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)),
biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)),
f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂,
by ext; simp; abel⟩
/--
If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,
then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂`
so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`),
via Gaussian elimination.
-/
def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] :
Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂),
L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ :=
begin
let := biprod.gaussian'
(biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd)
(biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd),
simpa [biprod.of_components_eq],
end
/--
If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism,
then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination.
-/
def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ :=
begin
obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂,
letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, },
letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g),
exact as_iso g,
end
/--
If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism,
then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination.
-/
def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ :=
begin
letI : is_iso (biprod.of_components
(biprod.inl ≫ f.hom ≫ biprod.fst)
(biprod.inl ≫ f.hom ≫ biprod.snd)
(biprod.inr ≫ f.hom ≫ biprod.fst)
(biprod.inr ≫ f.hom ≫ biprod.snd)) :=
by { simp only [biprod.of_components_eq], apply_instance, },
exact biprod.iso_elim'
(biprod.inl ≫ f.hom ≫ biprod.fst)
(biprod.inl ≫ f.hom ≫ biprod.snd)
(biprod.inr ≫ f.hom ≫ biprod.fst)
(biprod.inr ≫ f.hom ≫ biprod.snd)
end
lemma biprod.column_nonzero_of_iso {W X Y Z : C}
(f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] :
𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 :=
begin
classical,
by_contradiction,
rw [not_or_distrib, not_or_distrib, not_not, not_not] at a,
rcases a with ⟨nz, a₁, a₂⟩,
set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst,
have h₁ : x = 𝟙 W, by simp [x],
have h₀ : x = 0,
{ dsimp [x],
rw [←category.id_comp (inv f), category.assoc, ←biprod.total],
conv_lhs { slice 2 3, rw [comp_add], },
simp only [category.assoc],
rw [comp_add_assoc, add_comp],
conv_lhs { congr, skip, slice 1 3, rw a₂, },
simp only [zero_comp, add_zero],
conv_lhs { slice 1 3, rw a₁, },
simp only [zero_comp], },
exact nz (h₁.symm.trans h₀),
end
end
variables [preadditive.{v} C]
lemma biproduct.column_nonzero_of_iso'
{σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ]
{S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T]
(s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] :
(∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 :=
begin
intro z,
set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s,
have h₁ : x = 𝟙 (S s), by simp [x],
have h₀ : x = 0,
{ dsimp [x],
rw [←category.id_comp (inv f), category.assoc, ←biproduct.total],
simp only [comp_sum_assoc],
conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], },
simp, },
exact h₁.symm.trans h₀,
end
/--
If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source,
then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero.
-/
def biproduct.column_nonzero_of_iso
{σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ]
{S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T]
(s : σ) (nz : 𝟙 (S s) ≠ 0)
[∀ t, decidable_eq (S s ⟶ T t)]
(f : ⨁ S ⟶ ⨁ T) [is_iso f] :
trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) :=
begin
apply trunc_sigma_of_exists,
-- Do this before we run `classical`, so we get the right `decidable_eq` instances.
have t := biproduct.column_nonzero_of_iso'.{v} s f,
classical,
by_contradiction,
simp only [not_exists_not] at a,
exact nz (t a)
end
end category_theory
|
3d3969b39f797052ecb20d624d5a3294f1198795 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/charpoly/basic.lean | 7fc3fd13a2b60bd672df264cad3d762c7dd9f60a | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 3,784 | lean | /-
Copyright (c) 2021 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import linear_algebra.free_module.finite.basic
import linear_algebra.matrix.charpoly.coeff
import field_theory.minpoly.field
/-!
# Characteristic polynomial
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define the characteristic polynomial of `f : M →ₗ[R] M`, where `M` is a finite and
free `R`-module. The proof that `f.charpoly` is the characteristic polynomial of the matrix of `f`
in any basis is in `linear_algebra/charpoly/to_matrix`.
## Main definition
* `linear_map.charpoly f` : the characteristic polynomial of `f : M →ₗ[R] M`.
-/
universes u v w
variables {R : Type u} {M : Type v} [comm_ring R] [nontrivial R]
variables [add_comm_group M] [module R M] [module.free R M] [module.finite R M] (f : M →ₗ[R] M)
open_locale classical matrix polynomial
noncomputable theory
open module.free polynomial matrix
namespace linear_map
section basic
/-- The characteristic polynomial of `f : M →ₗ[R] M`. -/
def charpoly : R[X] :=
(to_matrix (choose_basis R M) (choose_basis R M) f).charpoly
lemma charpoly_def :
f.charpoly = (to_matrix (choose_basis R M) (choose_basis R M) f).charpoly := rfl
end basic
section coeff
lemma charpoly_monic : f.charpoly.monic := charpoly_monic _
end coeff
section cayley_hamilton
/-- The **Cayley-Hamilton Theorem**, that the characteristic polynomial of a linear map, applied
to the linear map itself, is zero.
See `matrix.aeval_self_charpoly` for the equivalent statement about matrices. -/
lemma aeval_self_charpoly : aeval f f.charpoly = 0 :=
begin
apply (linear_equiv.map_eq_zero_iff (alg_equiv_matrix (choose_basis R M)).to_linear_equiv).1,
rw [alg_equiv.to_linear_equiv_apply, ← alg_equiv.coe_alg_hom,
← polynomial.aeval_alg_hom_apply _ _ _, charpoly_def],
exact aeval_self_charpoly _,
end
lemma is_integral : is_integral R f := ⟨f.charpoly, ⟨charpoly_monic f, aeval_self_charpoly f⟩⟩
lemma minpoly_dvd_charpoly {K : Type u} {M : Type v} [field K] [add_comm_group M] [module K M]
[finite_dimensional K M] (f : M →ₗ[K] M) : minpoly K f ∣ f.charpoly :=
minpoly.dvd _ _ (aeval_self_charpoly f)
/-- Any endomorphism polynomial `p` is equivalent under evaluation to `p %ₘ f.charpoly`; that is,
`p` is equivalent to a polynomial with degree less than the dimension of the module. -/
lemma aeval_eq_aeval_mod_charpoly (p : R[X]) : aeval f p = aeval f (p %ₘ f.charpoly) :=
(aeval_mod_by_monic_eq_self_of_root f.charpoly_monic f.aeval_self_charpoly).symm
/-- Any endomorphism power can be computed as the sum of endomorphism powers less than the
dimension of the module. -/
lemma pow_eq_aeval_mod_charpoly (k : ℕ) : f^k = aeval f (X^k %ₘ f.charpoly) :=
by rw [←aeval_eq_aeval_mod_charpoly, map_pow, aeval_X]
variable {f}
lemma minpoly_coeff_zero_of_injective (hf : function.injective f) : (minpoly R f).coeff 0 ≠ 0 :=
begin
intro h,
obtain ⟨P, hP⟩ := X_dvd_iff.2 h,
have hdegP : P.degree < (minpoly R f).degree,
{ rw [hP, mul_comm],
refine degree_lt_degree_mul_X (λ h, _),
rw [h, mul_zero] at hP,
exact minpoly.ne_zero (is_integral f) hP },
have hPmonic : P.monic,
{ suffices : (minpoly R f).monic,
{ rwa [monic.def, hP, mul_comm, leading_coeff_mul_X, ← monic.def] at this },
exact minpoly.monic (is_integral f) },
have hzero : aeval f (minpoly R f) = 0 := minpoly.aeval _ _,
simp only [hP, mul_eq_comp, ext_iff, hf, aeval_X, map_eq_zero_iff, coe_comp, alg_hom.map_mul,
zero_apply] at hzero,
exact not_le.2 hdegP (minpoly.min _ _ hPmonic (ext hzero)),
end
end cayley_hamilton
end linear_map
|
18c58f0fc2bda021779df8a445b295743ccf64e4 | 7cef822f3b952965621309e88eadf618da0c8ae9 | /src/measure_theory/outer_measure.lean | 4fad3def18186c82a9b92ec321228f00265e7991 | [
"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 | 19,576 | 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
Outer measures -- overapproximations of measures
-/
import algebra.big_operators algebra.module
topology.instances.ennreal analysis.specific_limits
measure_theory.measurable_space
noncomputable theory
open set lattice finset function filter encodable
open_locale classical
namespace measure_theory
structure outer_measure (α : Type*) :=
(measure_of : set α → ennreal)
(empty : measure_of ∅ = 0)
(mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂)
(Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑i, measure_of (s i)))
namespace outer_measure
instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩
section basic
variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α}
@[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty
theorem mono' (m : outer_measure α) {s₁ s₂}
(h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h
theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0)
{β} [encodable β] (s : β → set α) :
(∑ b, m (s b)) = ∑ i, m (⋃ b ∈ decode2 β i, s b) :=
begin
have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some,
{ intros n h,
cases decode2 β n with b,
{ exact (h (by simp [m0])).elim },
{ exact rfl } },
refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _,
{ intros m n hm hn e,
have := mem_decode2.1 (option.get_mem (H n hn)),
rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this },
{ intros b h,
refine ⟨encode b, _, _⟩,
{ convert h, simp [ext_iff, encodek2] },
{ exact option.get_of_mem _ (encodek2 _) } },
{ intros n h,
transitivity, swap,
rw [show decode2 β n = _, from option.get_mem (H n h)],
congr, simp [ext_iff, -option.some_get] }
end
protected theorem Union (m : outer_measure α)
{β} [encodable β] (s : β → set α) :
m (⋃i, s i) ≤ (∑i, m (s i)) :=
by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _
lemma Union_null (m : outer_measure α)
{β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 :=
by simpa [h] using m.Union s
protected lemma union (m : outer_measure α) (s₁ s₂ : set α) :
m (s₁ ∪ s₂) ≤ m s₁ + m s₂ :=
begin
convert m.Union (λ b, cond b s₁ s₂),
{ simp [union_eq_Union] },
{ rw tsum_fintype, change _ = _ + _, simp }
end
lemma union_null (m : outer_measure α) {s₁ s₂ : set α}
(h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 :=
by simpa [h₁, h₂] using m.union s₁ s₂
@[ext] lemma ext : ∀{μ₁ μ₂ : outer_measure α},
(∀s, μ₁ s = μ₂ s) → μ₁ = μ₂
| ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h
instance : has_zero (outer_measure α) :=
⟨{ measure_of := λ_, 0,
empty := rfl,
mono := assume _ _ _, le_refl 0,
Union_nat := assume s, zero_le _ }⟩
@[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl
instance : inhabited (outer_measure α) := ⟨0⟩
instance : has_add (outer_measure α) :=
⟨λm₁ m₂,
{ measure_of := λs, m₁ s + m₂ s,
empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty],
mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h),
Union_nat := assume s,
calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤
(∑i, m₁ (s i)) + (∑i, m₂ (s i)) :
add_le_add' (m₁.Union_nat s) (m₂.Union_nat s)
... = _ : ennreal.tsum_add.symm}⟩
@[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ + m₂) s = m₁ s + m₂ s := rfl
instance add_comm_monoid : add_comm_monoid (outer_measure α) :=
{ zero := 0,
add := (+),
add_comm := assume a b, ext $ assume s, add_comm _ _,
add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _,
add_zero := assume a, ext $ assume s, add_zero _,
zero_add := assume a, ext $ assume s, zero_add _ }
instance : has_bot (outer_measure α) := ⟨0⟩
instance outer_measure.order_bot : order_bot (outer_measure α) :=
{ le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s,
bot := 0,
le_refl := assume a s, le_refl _,
le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s),
le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s),
bot_le := assume a s, zero_le _ }
section supremum
instance : has_Sup (outer_measure α) :=
⟨λms, {
measure_of := λs, ⨆m:ms, m.val s,
empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty,
mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs,
Union_nat := assume f, supr_le $ assume m,
calc m.val (⋃i, f i) ≤ (∑ (i : ℕ), m.val (f i)) : m.val.Union_nat _
... ≤ (∑i, ⨆m:ms, m.val (f i)) :
ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩
private lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms :=
λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩
private lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m :=
λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s)
instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩
private lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := Sup_le $ assume m' h', h' _ hm
private lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := le_Sup hm
instance : complete_lattice (outer_measure α) :=
{ top := Sup univ,
le_top := assume a, le_Sup (mem_univ a),
Sup := Sup,
Sup_le := assume s m, Sup_le,
le_Sup := assume s m, le_Sup,
Inf := Inf,
Inf_le := assume s m, Inf_le,
le_Inf := assume s m, le_Inf,
sup := λa b, Sup {a, b},
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 ha hb, Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
inf := λa b, Inf {a, b},
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 ha hb, le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt},
.. outer_measure.order_bot }
@[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) :
(Sup ms) s = ⨆ m : ms, m s := rfl
@[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) :
(⨆ i : ι, f i) s = ⨆ i, f i s :=
le_antisymm
(supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i)
(supr_le $ λ i, le_supr
(λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s)
⟨f i, i, rfl⟩)
@[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) :
(m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s :=
by have := supr_apply (λ b, cond b m₁ m₂) s;
rwa [supr_bool_eq, supr_bool_eq] at this
end supremum
def map {β} (f : α → β) (m : outer_measure α) : outer_measure β :=
{ measure_of := λs, m (f ⁻¹' s),
empty := m.empty,
mono := λ s t h, m.mono (preimage_mono h),
Union_nat := λ s, by rw [preimage_Union]; exact
m.Union_nat (λ i, f ⁻¹' s i) }
@[simp] theorem map_apply {β} (f : α → β)
(m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl
@[simp] theorem map_id (m : outer_measure α) : map id m = m :=
ext $ λ s, rfl
@[simp] theorem map_map {β γ} (f : α → β) (g : β → γ)
(m : outer_measure α) : map g (map f m) = map (g ∘ f) m :=
ext $ λ s, rfl
instance : functor outer_measure := {map := λ α β, map}
instance : is_lawful_functor outer_measure :=
{ id_map := λ α, map_id,
comp_map := λ α β γ f g m, (map_map f g m).symm }
/-- The dirac outer measure. -/
def dirac (a : α) : outer_measure α :=
{ measure_of := λs, ⨆ h : a ∈ s, 1,
empty := by simp,
mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩),
Union_nat := λ s, supr_le $ λ h,
let ⟨i, h⟩ := mem_Union.1 h in
le_trans (by exact le_supr _ h) (ennreal.le_tsum i) }
@[simp] theorem dirac_apply (a : α) (s : set α) :
dirac a s = ⨆ h : a ∈ s, 1 := rfl
def sum {ι} (f : ι → outer_measure α) : outer_measure α :=
{ measure_of := λs, ∑ i, f i s,
empty := by simp,
mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h),
Union_nat := λ s, by rw ennreal.tsum_comm; exact
ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) }
@[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) :
sum f s = ∑ i, f i s := rfl
instance : has_scalar ennreal (outer_measure α) :=
⟨λ a m, {
measure_of := λs, a * m s,
empty := by simp,
mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h),
Union_nat := λ s, by rw ennreal.mul_tsum; exact
canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩
@[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) :
(a • m) s = a * m s := rfl
instance : semimodule ennreal (outer_measure α) :=
{ smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _,
add_smul := λ a b m, ext $ λ s, add_mul _ _ _,
mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _,
one_smul := λ m, ext $ λ s, one_mul _,
zero_smul := λ m, ext $ λ s, zero_mul _,
smul_zero := λ a, ext $ λ s, mul_zero _,
..outer_measure.has_scalar }
theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) :
(a • dirac b) s = ⨆ h : b ∈ s, a :=
by by_cases b ∈ s; simp [h]
theorem top_apply {s : set α} (h : s ≠ ∅) : (⊤ : outer_measure α) s = ⊤ :=
let ⟨a, as⟩ := set.exists_mem_of_ne_empty h in
top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $
by simp [smul_dirac_apply, as]
end basic
section of_function
set_option eqn_compiler.zeta true
/-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is
a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/
protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) :
outer_measure α :=
let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑i, m (f i) in
{ measure_of := μ,
empty := le_antisymm
(infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty])
(zero_le _),
mono := assume s₁ s₂ hs, infi_le_infi $ assume f,
infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩,
Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin
assume ε hε (hb : (∑i, μ (s i)) < ⊤),
rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩,
refine le_trans _ (add_le_add_left' (le_of_lt hl)),
rw ← ennreal.tsum_add,
choose f hf using show
∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑i, m (f i)) < μ (s i) + ε' i,
{ intro,
have : μ (s i) < μ (s i) + ε' i :=
ennreal.lt_add_right
(lt_of_le_of_lt (by apply ennreal.le_tsum) hb)
(by simpa using hε' i),
simpa [μ, infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2),
rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm],
swap, {apply_instance},
refine infi_le_of_le _ (infi_le _ _),
exact Union_subset (λ i, subset.trans (hf i).1 $
Union_subset $ λ j, subset.trans (by simp) $
subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)),
end }
theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) :
outer_measure.of_function m m_empty s ≤ m s :=
let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in
infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $
calc (∑i, m (f i)) = ({0} : finset ℕ).sum (λi, m (f i)) :
tsum_eq_sum $ by intro i; cases i; simp [m_empty]
... = m s : by simp; refl
theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} :
μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s :=
⟨λ H s, le_trans (H _) (of_function_le _ _ _),
λ H s, le_infi $ λ f, le_infi $ λ hs,
le_trans (μ.mono hs) $ le_trans (μ.Union f) $
ennreal.tsum_le_tsum $ λ i, H _⟩
end of_function
section caratheodory_measurable
universe u
parameters {α : Type u} (m : outer_measure α)
include m
local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc
variables {s s₁ s₂ : set α}
private def C (s : set α) := ∀t, m t = m (t ∩ s) + m (t \ s)
private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $
by convert m.union _ _; rw inter_union_diff t s
@[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty]
private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq]
@[simp] private lemma C_compl_iff : C (- s) ↔ C s :=
⟨λ h, by simpa using C_compl m h, C_compl⟩
private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) :=
λ t, begin
rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)),
inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁,
inter_eq_self_of_subset_right (set.subset_union_left _ _),
union_diff_left, h₂ (t ∩ s₁)],
simp [diff_eq]
end
private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} :
m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) :=
by rw [h₁, set.inter_assoc, union_inter_cancel_left,
inter_diff_assoc, union_diff_cancel_left h]
private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i)
| 0 h := by simp [nat.not_lt_zero]
| (n + 1) h := by rw Union_lt_succ; exact C_union m
(h n (le_refl (n + 1)))
(C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _)
private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) :=
by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂)
private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} :
∀ {n}, (finset.range n).sum (λi, m (t ∩ s i)) = m (t ∩ ⋃i<n, s i)
| 0 := by simp [nat.not_lt_zero, m.empty]
| (nat.succ n) := begin
simp [Union_lt_succ, range_succ],
rw [measure_inter_union m _ (h n), C_sum],
intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩
end
private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : C (⋃i, s i) :=
C_iff_le.2 $ λ t, begin
have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)),
{ convert m.Union (λ i, t ∩ s i),
{ rw inter_Union },
{ simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } },
refine le_trans (add_le_add_right' hp) _,
rw ennreal.supr_add,
refine supr_le (λ n, le_trans (add_le_add_left' _)
(ge_of_eq (C_Union_lt m (λ i _, h i) _))),
refine m.mono (diff_subset_diff_right _),
exact bUnion_subset (λ i _, subset_Union _ i),
end
private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i))
(hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑i, m (s i) :=
begin
refine le_antisymm (m.Union_nat s) _,
rw ennreal.tsum_eq_supr_nat,
refine supr_le (λ n, _),
have := @C_sum _ m _ h hd univ n,
simp at this, simp [this],
exact m.mono (bUnion_subset (λ i _, subset_Union _ i)),
end
private def caratheodory_dynkin : measurable_space.dynkin_system α :=
{ has := C,
has_empty := C_empty,
has_compl := assume s, C_compl,
has_Union_nat := assume f hf hn, C_Union_nat hn hf }
/-- Given an outer measure `μ`, the Caratheodory measurable space is
defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/
protected def caratheodory : measurable_space α :=
caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter
lemma is_caratheodory {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) :=
iff.rfl
lemma is_caratheodory_le {s : set α} :
caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t :=
C_iff_le
protected lemma Union_eq_of_caratheodory {s : ℕ → set α}
(h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) :
m (⋃i, s i) = ∑i, m (s i) :=
f_Union h hd
end caratheodory_measurable
variables {α : Type*}
lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α}
{h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) :
(outer_measure.of_function m h₀).caratheodory.is_measurable s :=
let o := (outer_measure.of_function m h₀) in
(is_caratheodory_le o).2 $ λ t,
le_infi $ λ f, le_infi $ λ hf, begin
refine le_trans (add_le_add'
(infi_le_of_le (λi, f i ∩ s) $ infi_le _ _)
(infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _,
{ rw ← Union_inter,
exact inter_subset_inter_left _ hf },
{ rw ← Union_diff,
exact diff_subset_diff_left hf },
{ rw ← ennreal.tsum_add,
exact ennreal.tsum_le_tsum (λ i, hs _) }
end
@[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ :=
top_unique $ λ s _ t, (add_zero _).symm
theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ :=
top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t,
by by_cases ht : t = ∅; simp [ht, top_apply]
theorem le_add_caratheodory (m₁ m₂ : outer_measure α) :
m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory :=
λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t]
theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) :
(⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory :=
λ s h t, by simp [λ i,
measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add]
theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) :
m.caratheodory ≤ (a • m).caratheodory :=
λ s h t, by simp [h t, mul_add]
@[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ :=
top_unique $ λ s _ t, begin
by_cases a ∈ t; simp [h],
by_cases a ∈ s; simp [h]
end
section Inf_gen
def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal :=
⨆(h : s ≠ ∅), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s
@[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 :=
by simp [Inf_gen]
lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t ≠ ∅) :
Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) :=
by rw [Inf_gen, supr_pos h]
lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) :
Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) :=
begin
by_cases ht : t = ∅,
{ simp [ht],
refine (bot_unique $ infi_le_of_le μ $ _).symm,
refine infi_le_of_le h (le_refl ⊥) },
{ exact Inf_gen_nonempty1 m t ht }
end
lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) :
Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) :=
begin
refine le_antisymm
(assume t', le_of_function.2 (assume t, _) _)
(lattice.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _);
by_cases ht : t = ∅; simp [ht, Inf_gen_nonempty1],
{ assume μ hμ, exact (show Inf m ≤ μ, from lattice.Inf_le hμ) t },
{ exact infi_le_of_le μ (infi_le _ hμ) }
end
end Inf_gen
end outer_measure
end measure_theory
|
576ea6b99b8d4fd014868525d17a7cf866b9a8cb | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Lean/Elab/Deriving/Repr.lean | 2b5289bd963dc8b43ef2146564ad1ebd8a21a608 | [
"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 | 5,213 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Transform
import Lean.Meta.Inductive
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.Repr
open Lean.Parser.Term
open Meta
open Std
def mkReprHeader (indVal : InductiveVal) : TermElabM Header := do
let header ← mkHeader `Repr 1 indVal
return { header with
binders := header.binders.push (← `(bracketedBinder| (prec : Nat)))
}
def mkBodyForStruct (header : Header) (indVal : InductiveVal) : TermElabM Term := do
let ctorVal ← getConstInfoCtor indVal.ctors.head!
let fieldNames := getStructureFields (← getEnv) indVal.name
let numParams := indVal.numParams
let target := mkIdent header.targetNames[0]!
forallTelescopeReducing ctorVal.type fun xs _ => do
let mut fields ← `(Format.nil)
if xs.size != numParams + fieldNames.size then
throwError "'deriving Repr' failed, unexpected number of fields in structure"
for i in [:fieldNames.size] do
let fieldName := fieldNames[i]!
let fieldNameLit := Syntax.mkStrLit (toString fieldName)
let x := xs[numParams + i]!
if i > numParams then
fields ← `($fields ++ "," ++ Format.line)
if (← isType x <||> isProof x) then
fields ← `($fields ++ $fieldNameLit ++ " := " ++ "_")
else
let indent := Syntax.mkNumLit <| toString ((toString fieldName |>.length) + " := ".length)
fields ← `($fields ++ $fieldNameLit ++ " := " ++ (Format.group (Format.nest $indent (repr ($target.$(mkIdent fieldName):ident)))))
`(Format.bracket "{ " $fields:term " }")
def mkBodyForInduct (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Term := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkAlts : TermElabM (Array (TSyntax ``matchAlt)) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName
let alt ← forallTelescopeReducing ctorInfo.type fun xs _ => do
let mut patterns := #[]
-- add `_` pattern for indices
for _ in [:indVal.numIndices] do
patterns := patterns.push (← `(_))
let mut ctorArgs := #[]
let mut rhs : Term := Syntax.mkStrLit (toString ctorInfo.name)
rhs ← `(Format.text $rhs)
-- add `_` for inductive parameters, they are inaccessible
for _ in [:indVal.numParams] do
ctorArgs := ctorArgs.push (← `(_))
for i in [:ctorInfo.numFields] do
let x := xs[indVal.numParams + i]!
let a := mkIdent (← mkFreshUserName `a)
ctorArgs := ctorArgs.push a
let localDecl ← x.fvarId!.getDecl
if localDecl.binderInfo.isExplicit then
if (← inferType x).isAppOf indVal.name then
rhs ← `($rhs ++ Format.line ++ $(mkIdent auxFunName):ident $a:ident max_prec)
else
rhs ← `($rhs ++ Format.line ++ reprArg $a)
patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*))
`(matchAltExpr| | $[$patterns:term],* => Repr.addAppParen (Format.group (Format.nest (if prec >= max_prec then 1 else 2) ($rhs:term))) prec)
alts := alts.push alt
return alts
def mkBody (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Term := do
if isStructure (← getEnv) indVal.name then
mkBodyForStruct header indVal
else
mkBodyForInduct header indVal auxFunName
def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Command := do
let auxFunName := ctx.auxFunNames[i]!
let indVal := ctx.typeInfos[i]!
let header ← mkReprHeader indVal
let mut body ← mkBody header indVal auxFunName
if ctx.usePartial then
let letDecls ← mkLocalInstanceLetDecls ctx `Repr header.argNames
body ← mkLet letDecls body
let binders := header.binders
if ctx.usePartial then
`(private partial def $(mkIdent auxFunName):ident $binders:bracketedBinder* : Format := $body:term)
else
`(private def $(mkIdent auxFunName):ident $binders:bracketedBinder* : Format := $body:term)
def mkMutualBlock (ctx : Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (← mkAuxFunction ctx i)
`(mutual
$auxDefs:command*
end)
private def mkReprInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do
let ctx ← mkContext "repr" declNames[0]!
let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `Repr declNames)
trace[Elab.Deriving.repr] "\n{cmds}"
return cmds
open Command
def mkReprInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if (← declNames.allM isInductive) && declNames.size > 0 then
let cmds ← liftTermElabM <| mkReprInstanceCmds declNames
cmds.forM elabCommand
return true
else
return false
builtin_initialize
registerDerivingHandler `Repr mkReprInstanceHandler
registerTraceClass `Elab.Deriving.repr
end Lean.Elab.Deriving.Repr
|
c7818a2fcc85e9efe32593dc5dc718a23ba081ed | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/num/basic.lean | b01298f9d5e83b2e7d7f0463b1d7e1b8d2bd340e | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 13,779 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
Binary representation of integers using inductive types.
Note: Unlike in Coq, where this representation is preferred because of
the reliance on kernel reduction, in Lean this representation is discouraged
in favor of the "Peano" natural numbers `nat`, and the purpose of this
collection of theorems is to show the equivalence of the different approaches.
-/
import data.pnat data.bool data.vector data.bitvec
/-- The type of positive binary numbers.
13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/
inductive pos_num : Type
| one : pos_num
| bit1 : pos_num → pos_num
| bit0 : pos_num → pos_num
instance : has_one pos_num := ⟨pos_num.one⟩
instance : decidable_eq pos_num := by tactic.mk_dec_eq_instance
/-- The type of nonnegative binary numbers, using `pos_num`.
13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/
inductive num : Type
| zero : num
| pos : pos_num → num
instance : has_zero num := ⟨num.zero⟩
instance : has_one num := ⟨num.pos 1⟩
instance : decidable_eq num := by tactic.mk_dec_eq_instance
/-- Representation of integers using trichotomy around zero.
13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one)))
-13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/
inductive znum : Type
| zero : znum
| pos : pos_num → znum
| neg : pos_num → znum
instance : has_zero znum := ⟨znum.zero⟩
instance : has_one znum := ⟨znum.pos 1⟩
instance : decidable_eq znum := by tactic.mk_dec_eq_instance
/-- See `snum`. -/
inductive nzsnum : Type
| msb : bool → nzsnum
| bit : bool → nzsnum → nzsnum
/-- Alternative representation of integers using a sign bit at the end.
The convention on sign here is to have the argument to `msb` denote
the sign of the MSB itself, with all higher bits set to the negation
of this sign. The result is interpreted in two's complement.
13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt))))
-13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff))))
As with `num`, a special case must be added for zero, which has no msb,
but by two's complement symmetry there is a second special case for -1.
Here the `bool` field indicates the sign of the number.
0 = ..0000000(base 2) = zero ff
-1 = ..1111111(base 2) = zero tt -/
inductive snum : Type
| zero : bool → snum
| nz : nzsnum → snum
instance : has_coe nzsnum snum := ⟨snum.nz⟩
instance : has_zero snum := ⟨snum.zero ff⟩
instance : has_one nzsnum := ⟨nzsnum.msb tt⟩
instance : has_one snum := ⟨snum.nz 1⟩
instance : decidable_eq nzsnum := by tactic.mk_dec_eq_instance
instance : decidable_eq snum := by tactic.mk_dec_eq_instance
namespace pos_num
def bit (b : bool) : pos_num → pos_num := cond b bit1 bit0
def succ : pos_num → pos_num
| 1 := bit0 one
| (bit1 n) := bit0 (succ n)
| (bit0 n) := bit1 n
def is_one : pos_num → bool
| 1 := tt
| _ := ff
protected def add : pos_num → pos_num → pos_num
| 1 b := succ b
| a 1 := succ a
| (bit0 a) (bit0 b) := bit0 (add a b)
| (bit1 a) (bit1 b) := bit0 (succ (add a b))
| (bit0 a) (bit1 b) := bit1 (add a b)
| (bit1 a) (bit0 b) := bit1 (add a b)
instance : has_add pos_num := ⟨pos_num.add⟩
def pred' : pos_num → num
| 1 := 0
| (bit0 n) := num.pos (num.cases_on (pred' n) 1 bit1)
| (bit1 n) := num.pos (bit0 n)
def pred (a : pos_num) : pos_num :=
num.cases_on (pred' a) 1 id
def size : pos_num → pos_num
| 1 := 1
| (bit0 n) := succ (size n)
| (bit1 n) := succ (size n)
protected def mul (a : pos_num) : pos_num → pos_num
| 1 := a
| (bit0 b) := bit0 (mul b)
| (bit1 b) := bit0 (mul b) + a
instance : has_mul pos_num := ⟨pos_num.mul⟩
def of_nat_succ : ℕ → pos_num
| 0 := 1
| (nat.succ n) := succ (of_nat_succ n)
def of_nat (n : ℕ) : pos_num := of_nat_succ (nat.pred n)
open ordering
def cmp : pos_num → pos_num → ordering
| 1 1 := eq
| _ 1 := gt
| 1 _ := lt
| (bit0 a) (bit0 b) := cmp a b
| (bit0 a) (bit1 b) := ordering.cases_on (cmp a b) lt lt gt
| (bit1 a) (bit0 b) := ordering.cases_on (cmp a b) lt gt gt
| (bit1 a) (bit1 b) := cmp a b
instance : has_lt pos_num := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le pos_num := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel pos_num (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel pos_num (≤)
| a b := by dsimp [(≤)]; apply_instance
end pos_num
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α]
def cast_pos_num : pos_num → α
| 1 := 1
| (pos_num.bit0 a) := bit0 (cast_pos_num a)
| (pos_num.bit1 a) := bit1 (cast_pos_num a)
def cast_num : num → α
| 0 := 0
| (num.pos p) := cast_pos_num p
@[priority 0] instance pos_num_coe : has_coe pos_num α := ⟨cast_pos_num⟩
@[priority 0] instance num_nat_coe : has_coe num α := ⟨cast_num⟩
end
namespace num
open pos_num
def succ' : num → pos_num
| 0 := 1
| (pos p) := succ p
def succ (n : num) : num := pos (succ' n)
protected def add : num → num → num
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
instance : has_add num := ⟨num.add⟩
protected def bit0 : num → num
| 0 := 0
| (pos n) := pos (pos_num.bit0 n)
protected def bit1 : num → num
| 0 := 1
| (pos n) := pos (pos_num.bit1 n)
def bit (b : bool) : num → num := cond b num.bit1 num.bit0
def size : num → num
| 0 := 0
| (pos n) := pos (pos_num.size n)
protected def mul : num → num → num
| 0 _ := 0
| _ 0 := 0
| (pos a) (pos b) := pos (a * b)
instance : has_mul num := ⟨num.mul⟩
open ordering
def cmp : num → num → ordering
| 0 0 := eq
| _ 0 := gt
| 0 _ := lt
| (pos a) (pos b) := pos_num.cmp a b
instance : has_lt num := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le num := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel num (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel num (≤)
| a b := by dsimp [(≤)]; apply_instance
def to_znum : num → znum
| 0 := 0
| (pos a) := znum.pos a
def to_znum_neg : num → znum
| 0 := 0
| (pos a) := znum.neg a
end num
namespace znum
open pos_num
def zneg : znum → znum
| 0 := 0
| (pos a) := neg a
| (neg a) := pos a
instance : has_neg znum := ⟨zneg⟩
def succ : znum → znum
| 0 := 1
| (pos a) := pos (pos_num.succ a)
| (neg a) := (pos_num.pred' a).to_znum_neg
def pred : znum → znum
| 0 := neg 1
| (pos a) := (pos_num.pred' a).to_znum
| (neg a) := neg (pos_num.succ a)
protected def bit0 : znum → znum
| 0 := 0
| (pos n) := pos (pos_num.bit0 n)
| (neg n) := neg (pos_num.bit0 n)
protected def bit1 : znum → znum
| 0 := 1
| (pos n) := pos (pos_num.bit1 n)
| (neg n) := neg (num.cases_on (pred' n) 1 pos_num.bit1)
protected def bitm1 : znum → znum
| 0 := neg 1
| (pos n) := pos (num.cases_on (pred' n) 1 pos_num.bit1)
| (neg n) := neg (pos_num.bit1 n)
end znum
namespace pos_num
open znum
def sub' : pos_num → pos_num → znum
| a 1 := (pred' a).to_znum
| 1 b := (pred' b).to_znum_neg
| (bit0 a) (bit0 b) := (sub' a b).bit0
| (bit0 a) (bit1 b) := (sub' a b).bitm1
| (bit1 a) (bit0 b) := (sub' a b).bit1
| (bit1 a) (bit1 b) := (sub' a b).bit0
def of_znum' : znum → option pos_num
| (znum.pos p) := some p
| _ := none
def of_znum : znum → pos_num
| (znum.pos p) := p
| _ := 1
protected def sub (a b : pos_num) : pos_num :=
match sub' a b with
| (znum.pos p) := p
| _ := 1
end
instance : has_sub pos_num := ⟨pos_num.sub⟩
end pos_num
namespace num
def ppred : num → option num
| 0 := none
| (pos p) := some p.pred'
def pred : num → num
| 0 := 0
| (pos p) := p.pred'
def of_znum' : znum → option num
| 0 := some 0
| (znum.pos p) := some (pos p)
| (znum.neg p) := none
def of_znum : znum → num
| (znum.pos p) := pos p
| _ := 0
def sub' : num → num → znum
| 0 0 := 0
| (pos a) 0 := znum.pos a
| 0 (pos b) := znum.neg b
| (pos a) (pos b) := a.sub' b
def psub (a b : num) : option num :=
of_znum' (sub' a b)
protected def sub (a b : num) : num :=
of_znum (sub' a b)
instance : has_sub num := ⟨num.sub⟩
end num
namespace znum
open pos_num
protected def add : znum → znum → znum
| 0 a := a
| b 0 := b
| (pos a) (pos b) := pos (a + b)
| (pos a) (neg b) := sub' a b
| (neg a) (pos b) := sub' b a
| (neg a) (neg b) := neg (a + b)
instance : has_add znum := ⟨znum.add⟩
protected def mul : znum → znum → znum
| 0 a := 0
| b 0 := 0
| (pos a) (pos b) := pos (a * b)
| (pos a) (neg b) := neg (a * b)
| (neg a) (pos b) := neg (a * b)
| (neg a) (neg b) := pos (a * b)
instance : has_mul znum := ⟨znum.mul⟩
open ordering
def cmp : znum → znum → ordering
| 0 0 := eq
| (pos a) (pos b) := pos_num.cmp a b
| (neg a) (neg b) := pos_num.cmp b a
| (pos _) _ := gt
| (neg _) _ := lt
| _ (pos _) := lt
| _ (neg _) := gt
instance : has_lt znum := ⟨λa b, cmp a b = ordering.lt⟩
instance : has_le znum := ⟨λa b, ¬ b < a⟩
instance decidable_lt : @decidable_rel znum (<)
| a b := by dsimp [(<)]; apply_instance
instance decidable_le : @decidable_rel znum (≤)
| a b := by dsimp [(≤)]; apply_instance
end znum
section
variables {α : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α]
def cast_znum : znum → α
| 0 := 0
| (znum.pos p) := p
| (znum.neg p) := -p
@[priority 0] instance znum_coe : has_coe znum α := ⟨cast_znum⟩
end
/- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits,
and the negation of the MSB is sign-extended to all higher bits. -/
namespace nzsnum
notation a :: b := bit a b
def sign : nzsnum → bool
| (msb b) := bnot b
| (b :: p) := sign p
@[pattern] def not : nzsnum → nzsnum
| (msb b) := msb (bnot b)
| (b :: p) := bnot b :: not p
prefix ~ := not
def bit0 : nzsnum → nzsnum := bit ff
def bit1 : nzsnum → nzsnum := bit tt
def head : nzsnum → bool
| (msb b) := b
| (b :: p) := b
def tail : nzsnum → snum
| (msb b) := snum.zero (bnot b)
| (b :: p) := p
end nzsnum
namespace snum
open nzsnum
def sign : snum → bool
| (zero z) := z
| (nz p) := p.sign
@[pattern] def not : snum → snum
| (zero z) := zero (bnot z)
| (nz p) := ~p
prefix ~ := not
@[pattern] def bit : bool → snum → snum
| b (zero z) := if b = z then zero b else msb b
| b (nz p) := p.bit b
notation a :: b := bit a b
def bit0 : snum → snum := bit ff
def bit1 : snum → snum := bit tt
theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl
theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl
end snum
namespace nzsnum
open snum
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p
| (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b))
| (bit b p) := s b p (drec' p)
end nzsnum
namespace snum
open nzsnum
def head : snum → bool
| (zero z) := z
| (nz p) := p.head
def tail : snum → snum
| (zero z) := zero z
| (nz p) := p.tail
def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b))
(s : Π b p, C p → C (b :: p)) : Π p, C p
| (zero b) := z b
| (nz p) := p.drec' z s
def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α :=
drec' z s
def bits : snum → Π n, vector bool n
| p 0 := vector.nil
| p (n+1) := head p :: bits (tail p) n
def test_bit : nat → snum → bool
| 0 p := head p
| (n+1) p := test_bit n (tail p)
def succ : snum → snum :=
rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p))
def pred : snum → snum :=
rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp))
protected def neg (n : snum) : snum := succ ~n
instance : has_neg snum := ⟨snum.neg⟩
-- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt)
def czadd : bool → bool → snum → snum
| ff ff p := p
| ff tt p := pred p
| tt ff p := succ p
| tt tt p := p
def cadd : snum → snum → bool → snum :=
rec' (λ a p c, czadd c a p) $ λa p IH,
rec' (λb c, czadd c b (a :: p)) $ λb q _ c,
bitvec.xor3 a b c :: IH q (bitvec.carry a b c)
protected def add (a b : snum) : snum := cadd a b ff
instance : has_add snum := ⟨snum.add⟩
protected def sub (a b : snum) : snum := a + -b
instance : has_sub snum := ⟨snum.sub⟩
protected def mul (a : snum) : snum → snum :=
rec' (λ b, cond b (-a) 0) $ λb q IH,
cond b (bit0 IH + a) (bit0 IH)
instance : has_mul snum := ⟨snum.mul⟩
end snum
namespace int
def of_snum : snum → ℤ :=
snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH))
instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩
end int
instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩
instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
|
5b3560e5d7ef36f5a17af444664945cdeaec6cb5 | c45b34bfd44d8607a2e8762c926e3cfaa7436201 | /uexp/src/uexp/rules/pullConstantThroughUnion.lean | eba3e255ae816bc2b19ef4e97f7ee8ecb364a4f9 | [
"BSD-2-Clause"
] | permissive | Shamrock-Frost/Cosette | b477c442c07e45082348a145f19ebb35a7f29392 | 24cbc4adebf627f13f5eac878f04ffa20d1209af | refs/heads/master | 1,619,721,304,969 | 1,526,082,841,000 | 1,526,082,841,000 | 121,695,605 | 1 | 0 | null | 1,518,737,210,000 | 1,518,737,210,000 | null | UTF-8 | Lean | false | false | 1,331 | lean | import ..sql
import ..tactics
import ..u_semiring
import ..extra_constants
import ..ucongr
import ..TDP
import ..UDP
set_option profiler true
open Expr
open Proj
open Pred
open SQL
open tree
notation `int` := datatypes.int
constant integer_2 : const int
theorem rule:
forall ( Γ scm_emp: Schema) (rel_emp: relation scm_emp) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp),
denoteSQL (((SELECT1 (combine (e2p (constantExpr integer_2)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (e2p (constantExpr integer_2)) (combine (right⋅emp_deptno) (right⋅emp_job))) FROM1 (table rel_emp) )) : SQL Γ _ )
= denoteSQL ((SELECT1 (combine (e2p (constantExpr integer_2)) (combine (right⋅left) (right⋅right))) FROM1 (((SELECT1 (combine (right⋅emp_deptno) (right⋅emp_job)) FROM1 (table rel_emp) )) UNION ALL ((SELECT1 (combine (right⋅emp_deptno) (right⋅emp_job)) FROM1 (table rel_emp) ))) ) : SQL Γ _) :=
begin
intros,
unfold_all_denotations,
funext,
unfold pair,
simp,
UDP,
end |
007a48c0ee498f2ca4039e0586462e8c92e8fd31 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/decomposition/lebesgue.lean | eb1a19d20703b088b267ade2125ded0db779484c | [
"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 | 63,329 | lean | /-
Copyright (c) 2021 Kexing Ying. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kexing Ying
-/
import measure_theory.measure.complex
import measure_theory.measure.sub
import measure_theory.decomposition.jordan
import measure_theory.measure.with_density_vector_measure
import measure_theory.function.ae_eq_of_integral
/-!
# Lebesgue decomposition
This file proves the Lebesgue decomposition theorem. The Lebesgue decomposition theorem states that,
given two σ-finite measures `μ` and `ν`, there exists a σ-finite measure `ξ` and a measurable
function `f` such that `μ = ξ + fν` and `ξ` is mutually singular with respect to `ν`.
The Lebesgue decomposition provides the Radon-Nikodym theorem readily.
## Main definitions
* `measure_theory.measure.have_lebesgue_decomposition` : A pair of measures `μ` and `ν` is said
to `have_lebesgue_decomposition` if there exist a measure `ξ` and a measurable function `f`,
such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`
* `measure_theory.measure.singular_part` : If a pair of measures `have_lebesgue_decomposition`,
then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it
returns the zero measure.
* `measure_theory.measure.rn_deriv`: If a pair of measures
`have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from
`have_lebesgue_decomposition`, otherwise it returns the zero function.
* `measure_theory.signed_measure.have_lebesgue_decomposition` : A signed measure `s` and a
measure `μ` is said to `have_lebesgue_decomposition` if both the positive part and negative
part of `s` `have_lebesgue_decomposition` with respect to `μ`.
* `measure_theory.signed_measure.singular_part` : The singular part between a signed measure `s`
and a measure `μ` is simply the singular part of the positive part of `s` with respect to `μ`
minus the singular part of the negative part of `s` with respect to `μ`.
* `measure_theory.signed_measure.rn_deriv` : The Radon-Nikodym derivative of a signed
measure `s` with respect to a measure `μ` is the Radon-Nikodym derivative of the positive part of
`s` with respect to `μ` minus the Radon-Nikodym derivative of the negative part of `s` with
respect to `μ`.
## Main results
* `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite` :
the Lebesgue decomposition theorem.
* `measure_theory.measure.eq_singular_part` : Given measures `μ` and `ν`, if `s` is a measure
mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then
`s = μ.singular_part ν`.
* `measure_theory.measure.eq_rn_deriv` : Given measures `μ` and `ν`, if `s` is a
measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`,
then `f = μ.rn_deriv ν`.
* `measure_theory.signed_measure.singular_part_add_with_density_rn_deriv_eq` :
the Lebesgue decomposition theorem between a signed measure and a σ-finite positive measure.
# Tags
Lebesgue decomposition theorem
-/
noncomputable theory
open_locale classical measure_theory nnreal ennreal
open set
variables {α β : Type*} {m : measurable_space α} {μ ν : measure_theory.measure α}
include m
namespace measure_theory
namespace measure
/-- A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exists a
measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to
`ν` and `μ = ξ + ν.with_density f`. -/
class have_lebesgue_decomposition (μ ν : measure α) : Prop :=
(lebesgue_decomposition :
∃ (p : measure α × (α → ℝ≥0∞)), measurable p.2 ∧ p.1 ⟂ₘ ν ∧ μ = p.1 + ν.with_density p.2)
/-- If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the
measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. For sigma-finite
measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`. -/
@[irreducible]
def singular_part (μ ν : measure α) : measure α :=
if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).1 else 0
/-- If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the
measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function.
For sigma-finite measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`.-/
@[irreducible]
def rn_deriv (μ ν : measure α) : α → ℝ≥0∞ :=
if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).2 else 0
lemma have_lebesgue_decomposition_spec (μ ν : measure α)
[h : have_lebesgue_decomposition μ ν] :
measurable (μ.rn_deriv ν) ∧ (μ.singular_part ν) ⟂ₘ ν ∧
μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) :=
begin
rw [singular_part, rn_deriv, dif_pos h, dif_pos h],
exact classical.some_spec h.lebesgue_decomposition,
end
lemma have_lebesgue_decomposition_add (μ ν : measure α)
[have_lebesgue_decomposition μ ν] :
μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) :=
(have_lebesgue_decomposition_spec μ ν).2.2
instance have_lebesgue_decomposition_smul
(μ ν : measure α) [have_lebesgue_decomposition μ ν] (r : ℝ≥0) :
(r • μ).have_lebesgue_decomposition ν :=
{ lebesgue_decomposition :=
begin
obtain ⟨hmeas, hsing, hadd⟩ := have_lebesgue_decomposition_spec μ ν,
refine ⟨⟨r • μ.singular_part ν, r • μ.rn_deriv ν⟩, _, hsing.smul _, _⟩,
{ change measurable ((r : ℝ≥0∞) • _), -- cannot remove this line
exact hmeas.const_smul _ },
{ change _ = (r : ℝ≥0∞) • _ + ν.with_density ((r : ℝ≥0∞) • _),
rw [with_density_smul _ hmeas, ← smul_add, ← hadd],
refl }
end }
@[measurability]
lemma measurable_rn_deriv (μ ν : measure α) :
measurable $ μ.rn_deriv ν :=
begin
by_cases h : have_lebesgue_decomposition μ ν,
{ exactI (have_lebesgue_decomposition_spec μ ν).1 },
{ rw [rn_deriv, dif_neg h],
exact measurable_zero }
end
lemma mutually_singular_singular_part (μ ν : measure α) :
μ.singular_part ν ⟂ₘ ν :=
begin
by_cases h : have_lebesgue_decomposition μ ν,
{ exactI (have_lebesgue_decomposition_spec μ ν).2.1 },
{ rw [singular_part, dif_neg h],
exact mutually_singular.zero_left }
end
lemma singular_part_le (μ ν : measure α) : μ.singular_part ν ≤ μ :=
begin
by_cases hl : have_lebesgue_decomposition μ ν,
{ casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h,
conv_rhs { rw h },
exact measure.le_add_right le_rfl },
{ rw [singular_part, dif_neg hl],
exact measure.zero_le μ }
end
lemma with_density_rn_deriv_le (μ ν : measure α) :
ν.with_density (μ.rn_deriv ν) ≤ μ :=
begin
by_cases hl : have_lebesgue_decomposition μ ν,
{ casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h,
conv_rhs { rw h },
exact measure.le_add_left le_rfl },
{ rw [rn_deriv, dif_neg hl, with_density_zero],
exact measure.zero_le μ }
end
instance [is_finite_measure μ] : is_finite_measure (μ.singular_part ν) :=
is_finite_measure_of_le μ $ singular_part_le μ ν
instance [sigma_finite μ] : sigma_finite (μ.singular_part ν) :=
sigma_finite_of_le μ $ singular_part_le μ ν
instance [topological_space α] [is_locally_finite_measure μ] :
is_locally_finite_measure (μ.singular_part ν) :=
is_locally_finite_measure_of_le $ singular_part_le μ ν
instance [is_finite_measure μ] : is_finite_measure (ν.with_density $ μ.rn_deriv ν) :=
is_finite_measure_of_le μ $ with_density_rn_deriv_le μ ν
instance [sigma_finite μ] : sigma_finite (ν.with_density $ μ.rn_deriv ν) :=
sigma_finite_of_le μ $ with_density_rn_deriv_le μ ν
instance [topological_space α] [is_locally_finite_measure μ] :
is_locally_finite_measure (ν.with_density $ μ.rn_deriv ν) :=
is_locally_finite_measure_of_le $ with_density_rn_deriv_le μ ν
lemma lintegral_rn_deriv_lt_top_of_measure_ne_top
{μ : measure α} (ν : measure α) {s : set α} (hs : μ s ≠ ∞) :
∫⁻ x in s, μ.rn_deriv ν x ∂ν < ∞ :=
begin
by_cases hl : have_lebesgue_decomposition μ ν,
{ haveI := hl,
obtain ⟨-, -, hadd⟩ := have_lebesgue_decomposition_spec μ ν,
suffices : ∫⁻ x in to_measurable μ s, μ.rn_deriv ν x ∂ν < ∞,
from lt_of_le_of_lt (lintegral_mono_set (subset_to_measurable _ _)) this,
rw [← with_density_apply _ (measurable_set_to_measurable _ _)],
refine lt_of_le_of_lt
(le_add_left le_rfl : _ ≤ μ.singular_part ν (to_measurable μ s) +
ν.with_density (μ.rn_deriv ν) (to_measurable μ s)) _,
rw [← measure.add_apply, ← hadd, measure_to_measurable],
exact hs.lt_top },
{ erw [measure.rn_deriv, dif_neg hl, lintegral_zero],
exact with_top.zero_lt_top },
end
lemma lintegral_rn_deriv_lt_top
(μ ν : measure α) [is_finite_measure μ] :
∫⁻ x, μ.rn_deriv ν x ∂ν < ∞ :=
begin
rw [← set_lintegral_univ],
exact lintegral_rn_deriv_lt_top_of_measure_ne_top _ (measure_lt_top _ _).ne,
end
/-- The Radon-Nikodym derivative of a sigma-finite measure `μ` with respect to another
measure `ν` is `ν`-almost everywhere finite. -/
theorem rn_deriv_lt_top (μ ν : measure α) [sigma_finite μ] :
∀ᵐ x ∂ν, μ.rn_deriv ν x < ∞ :=
begin
suffices : ∀ n, ∀ᵐ x ∂ν, x ∈ spanning_sets μ n → μ.rn_deriv ν x < ∞,
{ filter_upwards [ae_all_iff.2 this] with _ hx using hx _ (mem_spanning_sets_index _ _), },
assume n,
rw ← ae_restrict_iff' (measurable_spanning_sets _ _),
apply ae_lt_top (measurable_rn_deriv _ _),
refine (lintegral_rn_deriv_lt_top_of_measure_ne_top _ _).ne,
exact (measure_spanning_sets_lt_top _ _).ne
end
/-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a
measurable function such that `μ = s + fν`, then `s = μ.singular_part μ`.
This theorem provides the uniqueness of the `singular_part` in the Lebesgue decomposition theorem,
while `measure_theory.measure.eq_rn_deriv` provides the uniqueness of the
`rn_deriv`. -/
theorem eq_singular_part {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f)
(hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) :
s = μ.singular_part ν :=
begin
haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩,
obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν,
obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩,
rw hadd' at hadd,
have hνinter : ν (S ∩ T)ᶜ = 0,
{ rw compl_inter,
refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _),
rw [hT₃, hS₃, add_zero],
exact le_rfl },
have heq : s.restrict (S ∩ T)ᶜ = (μ.singular_part ν).restrict (S ∩ T)ᶜ,
{ ext1 A hA,
have hf : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0,
{ refine with_density_absolutely_continuous ν _ _,
rw ← nonpos_iff_eq_zero,
exact hνinter ▸ measure_mono (inter_subset_right _ _) },
have hrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0,
{ refine with_density_absolutely_continuous ν _ _,
rw ← nonpos_iff_eq_zero,
exact hνinter ▸ measure_mono (inter_subset_right _ _) },
rw [restrict_apply hA, restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hf,
← add_apply, ← hadd, add_apply, hrn, add_zero] },
have heq' : ∀ A : set α, measurable_set A → s A = s.restrict (S ∩ T)ᶜ A,
{ intros A hA,
have hsinter : s (A ∩ (S ∩ T)) = 0,
{ rw ← nonpos_iff_eq_zero,
exact hS₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_left _ _)) },
rw [restrict_apply hA, ← diff_eq, ae_disjoint.measure_diff_left hsinter] },
ext1 A hA,
have hμinter : μ.singular_part ν (A ∩ (S ∩ T)) = 0,
{ rw ← nonpos_iff_eq_zero,
exact hT₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_right _ _)) },
rw [heq' A hA, heq, restrict_apply hA, ← diff_eq, ae_disjoint.measure_diff_left hμinter]
end
lemma singular_part_zero (ν : measure α) : (0 : measure α).singular_part ν = 0 :=
begin
refine (eq_singular_part measurable_zero mutually_singular.zero_left _).symm,
rw [zero_add, with_density_zero],
end
lemma singular_part_smul (μ ν : measure α) (r : ℝ≥0) :
(r • μ).singular_part ν = r • (μ.singular_part ν) :=
begin
by_cases hr : r = 0,
{ rw [hr, zero_smul, zero_smul, singular_part_zero] },
by_cases hl : have_lebesgue_decomposition μ ν,
{ haveI := hl,
refine (eq_singular_part ((measurable_rn_deriv μ ν).const_smul (r : ℝ≥0∞))
(mutually_singular.smul r (have_lebesgue_decomposition_spec _ _).2.1) _).symm,
rw [with_density_smul _ (measurable_rn_deriv _ _), ← smul_add,
← have_lebesgue_decomposition_add μ ν, ennreal.smul_def] },
{ rw [singular_part, singular_part, dif_neg hl, dif_neg, smul_zero],
refine λ hl', hl _,
rw ← inv_smul_smul₀ hr μ,
exact @measure.have_lebesgue_decomposition_smul _ _ _ _ hl' _ }
end
lemma singular_part_add (μ₁ μ₂ ν : measure α)
[have_lebesgue_decomposition μ₁ ν] [have_lebesgue_decomposition μ₂ ν] :
(μ₁ + μ₂).singular_part ν = μ₁.singular_part ν + μ₂.singular_part ν :=
begin
refine (eq_singular_part
((measurable_rn_deriv μ₁ ν).add (measurable_rn_deriv μ₂ ν))
((have_lebesgue_decomposition_spec _ _).2.1.add_left (have_lebesgue_decomposition_spec _ _).2.1)
_).symm,
erw with_density_add_left (measurable_rn_deriv μ₁ ν),
conv_rhs { rw [add_assoc, add_comm (μ₂.singular_part ν), ← add_assoc, ← add_assoc] },
rw [← have_lebesgue_decomposition_add μ₁ ν, add_assoc,
add_comm (ν.with_density (μ₂.rn_deriv ν)),
← have_lebesgue_decomposition_add μ₂ ν]
end
lemma singular_part_with_density (ν : measure α) {f : α → ℝ≥0∞} (hf : measurable f) :
(ν.with_density f).singular_part ν = 0 :=
begin
have : ν.with_density f = 0 + ν.with_density f, by rw zero_add,
exact (eq_singular_part hf mutually_singular.zero_left this).symm,
end
/-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a
measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`.
This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition
theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the
`singular_part`. Here, the uniqueness is given in terms of the measures, while the uniqueness in
terms of the functions is given in `eq_rn_deriv`. -/
theorem eq_with_density_rn_deriv {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f)
(hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) :
ν.with_density f = ν.with_density (μ.rn_deriv ν) :=
begin
haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩,
obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν,
obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩,
rw hadd' at hadd,
have hνinter : ν (S ∩ T)ᶜ = 0,
{ rw compl_inter,
refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _),
rw [hT₃, hS₃, add_zero],
exact le_rfl },
have heq : (ν.with_density f).restrict (S ∩ T) =
(ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T),
{ ext1 A hA,
have hs : s (A ∩ (S ∩ T)) = 0,
{ rw ← nonpos_iff_eq_zero,
exact hS₂ ▸ measure_mono ((inter_subset_right _ _).trans (inter_subset_left _ _)) },
have hsing : μ.singular_part ν (A ∩ (S ∩ T)) = 0,
{ rw ← nonpos_iff_eq_zero,
exact hT₂ ▸ measure_mono
((inter_subset_right _ _).trans (inter_subset_right _ _)) },
rw [restrict_apply hA, restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))),
← hs, ← add_apply, add_comm, ← hadd, add_apply, hsing, zero_add] },
have heq' : ∀ A : set α, measurable_set A →
ν.with_density f A = (ν.with_density f).restrict (S ∩ T) A,
{ intros A hA,
have hνfinter : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0,
{ rw ← nonpos_iff_eq_zero,
exact with_density_absolutely_continuous ν f hνinter ▸
measure_mono (inter_subset_right _ _) },
rw [restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hνfinter,
← diff_eq, measure_inter_add_diff _ (hS₁.inter hT₁)] },
ext1 A hA,
have hνrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0,
{ rw ← nonpos_iff_eq_zero,
exact with_density_absolutely_continuous ν (μ.rn_deriv ν) hνinter ▸
measure_mono (inter_subset_right _ _) },
rw [heq' A hA, heq, ← add_zero ((ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T) A),
← hνrn, restrict_apply hA, ← diff_eq, measure_inter_add_diff _ (hS₁.inter hT₁)]
end
/-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a
measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`.
This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition
theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the
`singular_part`. Here, the uniqueness is given in terms of the functions, while the uniqueness in
terms of the functions is given in `eq_with_density_rn_deriv`. -/
theorem eq_rn_deriv [sigma_finite ν] {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f)
(hs : s ⟂ₘ ν) (hadd : μ = s + ν.with_density f) :
f =ᵐ[ν] μ.rn_deriv ν :=
begin
refine ae_eq_of_forall_set_lintegral_eq_of_sigma_finite hf (measurable_rn_deriv μ ν) _,
assume a ha h'a,
calc ∫⁻ (x : α) in a, f x ∂ν = ν.with_density f a : (with_density_apply f ha).symm
... = ν.with_density (μ.rn_deriv ν) a : by rw eq_with_density_rn_deriv hf hs hadd
... = ∫⁻ (x : α) in a, μ.rn_deriv ν x ∂ν : with_density_apply _ ha
end
/-- The Radon-Nikodym derivative of `f ν` with respect to `ν` is `f`. -/
theorem rn_deriv_with_density (ν : measure α) [sigma_finite ν] {f : α → ℝ≥0∞} (hf : measurable f) :
(ν.with_density f).rn_deriv ν =ᵐ[ν] f :=
begin
have : ν.with_density f = 0 + ν.with_density f, by rw zero_add,
exact (eq_rn_deriv hf mutually_singular.zero_left this).symm,
end
/-- The Radon-Nikodym derivative of the restriction of a measure to a measurable set is the
indicator function of this set. -/
theorem rn_deriv_restrict (ν : measure α) [sigma_finite ν] {s : set α} (hs : measurable_set s) :
(ν.restrict s).rn_deriv ν =ᵐ[ν] s.indicator 1 :=
begin
rw ← with_density_indicator_one hs,
exact rn_deriv_with_density _ (measurable_one.indicator hs)
end
open vector_measure signed_measure
/-- If two finite measures `μ` and `ν` are not mutually singular, there exists some `ε > 0` and
a measurable set `E`, such that `ν(E) > 0` and `E` is positive with respect to `μ - εν`.
This lemma is useful for the Lebesgue decomposition theorem. -/
lemma exists_positive_of_not_mutually_singular
(μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] (h : ¬ μ ⟂ₘ ν) :
∃ ε : ℝ≥0, 0 < ε ∧ ∃ E : set α, measurable_set E ∧ 0 < ν E ∧
0 ≤[E] μ.to_signed_measure - (ε • ν).to_signed_measure :=
begin
-- for all `n : ℕ`, obtain the Hahn decomposition for `μ - (1 / n) ν`
have : ∀ n : ℕ, ∃ i : set α, measurable_set i ∧
0 ≤[i] (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ∧
(μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[iᶜ] 0,
{ intro, exact exists_compl_positive_negative _ },
choose f hf₁ hf₂ hf₃ using this,
-- set `A` to be the intersection of all the negative parts of obtained Hahn decompositions
-- and we show that `μ A = 0`
set A := ⋂ n, (f n)ᶜ with hA₁,
have hAmeas : measurable_set A,
{ exact measurable_set.Inter (λ n, (hf₁ n).compl) },
have hA₂ : ∀ n : ℕ, (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[A] 0,
{ intro n, exact restrict_le_restrict_subset _ _ (hf₁ n).compl (hf₃ n) (Inter_subset _ _) },
have hA₃ : ∀ n : ℕ, μ A ≤ (1 / (n + 1) : ℝ≥0) * ν A,
{ intro n,
have := nonpos_of_restrict_le_zero _ (hA₂ n),
rwa [to_signed_measure_sub_apply hAmeas, sub_nonpos, ennreal.to_real_le_to_real] at this,
exacts [ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)] },
have hμ : μ A = 0,
{ lift μ A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with μA,
lift ν A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with νA,
rw ennreal.coe_eq_zero,
by_cases hb : 0 < νA,
{ suffices : ∀ b, 0 < b → μA ≤ b,
{ by_contra,
have h' := this (μA / 2) (half_pos (zero_lt_iff.2 h)),
rw ← @not_not (μA ≤ μA / 2) at h',
exact h' (not_le.2 (nnreal.half_lt_self h)) },
intros c hc,
have : ∃ n : ℕ, 1 / (n + 1 : ℝ) < c * νA⁻¹, refine exists_nat_one_div_lt _,
{ refine mul_pos hc _,
rw _root_.inv_pos, exact hb },
rcases this with ⟨n, hn⟩,
have hb₁ : (0 : ℝ) < νA⁻¹, { rw _root_.inv_pos, exact hb },
have h' : 1 / (↑n + 1) * νA < c,
{ rw [← nnreal.coe_lt_coe, ← mul_lt_mul_right hb₁, nnreal.coe_mul, mul_assoc,
← nnreal.coe_inv, ← nnreal.coe_mul, _root_.mul_inv_cancel, ← nnreal.coe_mul,
mul_one, nnreal.coe_inv],
{ exact hn },
{ exact ne.symm (ne_of_lt hb) } },
refine le_trans _ (le_of_lt h'),
rw [← ennreal.coe_le_coe, ennreal.coe_mul],
exact hA₃ n },
{ rw [not_lt, le_zero_iff] at hb,
specialize hA₃ 0,
simp [hb, le_zero_iff] at hA₃,
assumption } },
-- since `μ` and `ν` are not mutually singular, `μ A = 0` implies `ν Aᶜ > 0`
rw mutually_singular at h, push_neg at h,
have := h _ hAmeas hμ,
simp_rw [hA₁, compl_Inter, compl_compl] at this,
-- as `Aᶜ = ⋃ n, f n`, `ν Aᶜ > 0` implies there exists some `n` such that `ν (f n) > 0`
obtain ⟨n, hn⟩ := exists_measure_pos_of_not_measure_Union_null this,
-- thus, choosing `f n` as the set `E` suffices
exact ⟨1 / (n + 1), by simp, f n, hf₁ n, hn, hf₂ n⟩,
end
namespace lebesgue_decomposition
/-- Given two measures `μ` and `ν`, `measurable_le μ ν` is the set of measurable
functions `f`, such that, for all measurable sets `A`, `∫⁻ x in A, f x ∂μ ≤ ν A`.
This is useful for the Lebesgue decomposition theorem. -/
def measurable_le (μ ν : measure α) : set (α → ℝ≥0∞) :=
{ f | measurable f ∧ ∀ (A : set α) (hA : measurable_set A), ∫⁻ x in A, f x ∂μ ≤ ν A }
lemma zero_mem_measurable_le : (0 : α → ℝ≥0∞) ∈ measurable_le μ ν :=
⟨measurable_zero, λ A hA, by simp⟩
lemma sup_mem_measurable_le {f g : α → ℝ≥0∞}
(hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) :
(λ a, f a ⊔ g a) ∈ measurable_le μ ν :=
begin
simp_rw ennreal.sup_eq_max,
refine ⟨measurable.max hf.1 hg.1, λ A hA, _⟩,
have h₁ := hA.inter (measurable_set_le hf.1 hg.1),
have h₂ := hA.inter (measurable_set_lt hg.1 hf.1),
rw [set_lintegral_max hf.1 hg.1],
refine (add_le_add (hg.2 _ h₁) (hf.2 _ h₂)).trans_eq _,
{ simp only [← not_le, ← compl_set_of, ← diff_eq],
exact measure_inter_add_diff _ (measurable_set_le hf.1 hg.1) }
end
lemma supr_succ_eq_sup {α} (f : ℕ → α → ℝ≥0∞) (m : ℕ) (a : α) :
(⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a :=
begin
ext x,
simp only [option.mem_def, ennreal.some_eq_coe],
split; intro h; rw ← h, symmetry,
all_goals
{ set c := (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) with hc,
set d := (f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a) with hd,
rw [@le_antisymm_iff ℝ≥0∞, hc, hd], -- Specifying the type is weirdly necessary
refine ⟨_, _⟩,
{ refine supr₂_le (λ n hn, _),
rcases nat.of_le_succ hn with (h | h),
{ exact le_sup_of_le_right (le_supr₂ n h) },
{ exact h ▸ le_sup_left } },
{ refine sup_le _ (bsupr_mono $ λ n hn, hn.trans m.le_succ),
convert @le_supr₂ _ _ (λ i, i ≤ m + 1) _ _ m.succ le_rfl,
refl } }
end
lemma supr_mem_measurable_le
(f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) :
(λ x, ⨆ k (hk : k ≤ n), f k x) ∈ measurable_le μ ν :=
begin
induction n with m hm,
{ refine ⟨_, _⟩,
{ simp [(hf 0).1] },
{ intros A hA, simp [(hf 0).2 A hA] } },
{ have : (λ (a : α), ⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) =
(λ a, f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a),
{ exact funext (λ _, supr_succ_eq_sup _ _ _) },
refine ⟨measurable_supr (λ n, measurable.supr_Prop _ (hf n).1), λ A hA, _⟩,
rw this, exact (sup_mem_measurable_le (hf m.succ) hm).2 A hA }
end
lemma supr_mem_measurable_le'
(f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) :
(⨆ k (hk : k ≤ n), f k) ∈ measurable_le μ ν :=
begin
convert supr_mem_measurable_le f hf n,
ext, simp
end
section supr_lemmas --TODO: these statements should be moved elsewhere
omit m
lemma supr_monotone {α : Type*} (f : ℕ → α → ℝ≥0∞) :
monotone (λ n x, ⨆ k (hk : k ≤ n), f k x) :=
λ n m hnm x, bsupr_mono $ λ i, ge_trans hnm
lemma supr_monotone' {α : Type*} (f : ℕ → α → ℝ≥0∞) (x : α) :
monotone (λ n, ⨆ k (hk : k ≤ n), f k x) :=
λ n m hnm, supr_monotone f hnm x
lemma supr_le_le {α : Type*} (f : ℕ → α → ℝ≥0∞) (n k : ℕ) (hk : k ≤ n) :
f k ≤ λ x, ⨆ k (hk : k ≤ n), f k x :=
λ x, le_supr₂ k hk
end supr_lemmas
/-- `measurable_le_eval μ ν` is the set of `∫⁻ x, f x ∂μ` for all `f ∈ measurable_le μ ν`. -/
def measurable_le_eval (μ ν : measure α) : set ℝ≥0∞ :=
(λ f : α → ℝ≥0∞, ∫⁻ x, f x ∂μ) '' measurable_le μ ν
end lebesgue_decomposition
open lebesgue_decomposition
/-- Any pair of finite measures `μ` and `ν`, `have_lebesgue_decomposition`. That is to say,
there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular
with respect to `ν` and `μ = ξ + ν.with_density f`.
This is not an instance since this is also shown for the more general σ-finite measures with
`measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite`. -/
theorem have_lebesgue_decomposition_of_finite_measure [is_finite_measure μ] [is_finite_measure ν] :
have_lebesgue_decomposition μ ν :=
⟨begin
have h := @exists_seq_tendsto_Sup _ _ _ _ _ (measurable_le_eval ν μ)
⟨0, 0, zero_mem_measurable_le, by simp⟩ (order_top.bdd_above _),
choose g hmono hg₂ f hf₁ hf₂ using h,
-- we set `ξ` to be the supremum of an increasing sequence of functions obtained from above
set ξ := ⨆ n k (hk : k ≤ n), f k with hξ,
-- we see that `ξ` has the largest integral among all functions in `measurable_le`
have hξ₁ : Sup (measurable_le_eval ν μ) = ∫⁻ a, ξ a ∂ν,
{ have := @lintegral_tendsto_of_tendsto_of_monotone _ _ ν
(λ n, ⨆ k (hk : k ≤ n), f k) (⨆ n k (hk : k ≤ n), f k) _ _ _,
{ refine tendsto_nhds_unique _ this,
refine tendsto_of_tendsto_of_tendsto_of_le_of_le hg₂ tendsto_const_nhds _ _,
{ intro n, rw ← hf₂ n,
apply lintegral_mono,
simp only [supr_apply, supr_le_le f n n le_rfl] },
{ intro n,
exact le_Sup ⟨⨆ (k : ℕ) (hk : k ≤ n), f k, supr_mem_measurable_le' _ hf₁ _, rfl⟩ } },
{ intro n,
refine measurable.ae_measurable _,
convert (supr_mem_measurable_le _ hf₁ n).1,
ext, simp },
{ refine filter.eventually_of_forall (λ a, _),
simp [supr_monotone' f _] },
{ refine filter.eventually_of_forall (λ a, _),
simp [tendsto_at_top_supr (supr_monotone' f a)] } },
have hξm : measurable ξ,
{ convert measurable_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1),
ext, simp [hξ] },
-- `ξ` is the `f` in the theorem statement and we set `μ₁` to be `μ - ν.with_density ξ`
-- since we need `μ₁ + ν.with_density ξ = μ`
set μ₁ := μ - ν.with_density ξ with hμ₁,
have hle : ν.with_density ξ ≤ μ,
{ intros B hB,
rw [hξ, with_density_apply _ hB],
simp_rw [supr_apply],
rw lintegral_supr (λ i, (supr_mem_measurable_le _ hf₁ i).1) (supr_monotone _),
exact supr_le (λ i, (supr_mem_measurable_le _ hf₁ i).2 B hB) },
haveI : is_finite_measure (ν.with_density ξ),
{ refine is_finite_measure_with_density _,
have hle' := hle univ measurable_set.univ,
rw [with_density_apply _ measurable_set.univ, measure.restrict_univ] at hle',
exact ne_top_of_le_ne_top (measure_ne_top _ _) hle' },
refine ⟨⟨μ₁, ξ⟩, hξm, _, _⟩,
{ by_contra,
-- if they are not mutually singular, then from `exists_positive_of_not_mutually_singular`,
-- there exists some `ε > 0` and a measurable set `E`, such that `μ(E) > 0` and `E` is
-- positive with respect to `ν - εμ`
obtain ⟨ε, hε₁, E, hE₁, hE₂, hE₃⟩ := exists_positive_of_not_mutually_singular μ₁ ν h,
simp_rw hμ₁ at hE₃,
have hξle : ∀ A, measurable_set A → ∫⁻ a in A, ξ a ∂ν ≤ μ A,
{ intros A hA, rw hξ,
simp_rw [supr_apply],
rw lintegral_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1) (supr_monotone _),
exact supr_le (λ n, (supr_mem_measurable_le _ hf₁ n).2 A hA) },
-- since `E` is positive, we have `∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E)` for all `A`
have hε₂ : ∀ A : set α, measurable_set A → ∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E),
{ intros A hA,
have := subset_le_of_restrict_le_restrict _ _ hE₁ hE₃ (inter_subset_right A E),
rwa [zero_apply, to_signed_measure_sub_apply (hA.inter hE₁),
measure.sub_apply (hA.inter hE₁) hle,
ennreal.to_real_sub_of_le _ (ne_of_lt (measure_lt_top _ _)), sub_nonneg,
le_sub_iff_add_le, ← ennreal.to_real_add, ennreal.to_real_le_to_real,
measure.coe_smul, pi.smul_apply, with_density_apply _ (hA.inter hE₁),
show ε • ν (A ∩ E) = (ε : ℝ≥0∞) * ν (A ∩ E), by refl,
← set_lintegral_const, ← lintegral_add_left measurable_const] at this,
{ rw [ne.def, ennreal.add_eq_top, not_or_distrib],
exact ⟨ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)⟩ },
{ exact ne_of_lt (measure_lt_top _ _) },
{ exact ne_of_lt (measure_lt_top _ _) },
{ exact ne_of_lt (measure_lt_top _ _) },
{ rw with_density_apply _ (hA.inter hE₁),
exact hξle (A ∩ E) (hA.inter hE₁) },
{ apply_instance } },
-- from this, we can show `ξ + ε * E.indicator` is a function in `measurable_le` with
-- integral greater than `ξ`
have hξε : ξ + E.indicator (λ _, ε) ∈ measurable_le ν μ,
{ refine ⟨measurable.add hξm (measurable.indicator measurable_const hE₁), λ A hA, _⟩,
have : ∫⁻ a in A, (ξ + E.indicator (λ _, ε)) a ∂ν =
∫⁻ a in A ∩ E, ε + ξ a ∂ν + ∫⁻ a in A \ E, ξ a ∂ν,
{ simp only [lintegral_add_left measurable_const, lintegral_add_left hξm,
set_lintegral_const, add_assoc, lintegral_inter_add_diff _ _ hE₁, pi.add_apply,
lintegral_indicator _ hE₁, restrict_apply hE₁],
rw [inter_comm, add_comm] },
rw [this, ← measure_inter_add_diff A hE₁],
exact add_le_add (hε₂ A hA) (hξle (A \ E) (hA.diff hE₁)) },
have : ∫⁻ a, ξ a + E.indicator (λ _, ε) a ∂ν ≤ Sup (measurable_le_eval ν μ) :=
le_Sup ⟨ξ + E.indicator (λ _, ε), hξε, rfl⟩,
-- but this contradicts the maximality of `∫⁻ x, ξ x ∂ν`
refine not_lt.2 this _,
rw [hξ₁, lintegral_add_left hξm, lintegral_indicator _ hE₁, set_lintegral_const],
refine ennreal.lt_add_right _ (ennreal.mul_pos_iff.2 ⟨ennreal.coe_pos.2 hε₁, hE₂⟩).ne',
have := measure_ne_top (ν.with_density ξ) univ,
rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ] at this },
-- since `ν.with_density ξ ≤ μ`, it is clear that `μ = μ₁ + ν.with_density ξ`
{ rw hμ₁, ext1 A hA,
rw [measure.coe_add, pi.add_apply, measure.sub_apply hA hle,
add_comm, add_tsub_cancel_of_le (hle A hA)] },
end⟩
local attribute [instance] have_lebesgue_decomposition_of_finite_measure
instance {S : μ.finite_spanning_sets_in {s : set α | measurable_set s}} (n : ℕ) :
is_finite_measure (μ.restrict $ S.set n) :=
⟨by { rw [restrict_apply measurable_set.univ, univ_inter], exact S.finite _ }⟩
/-- **The Lebesgue decomposition theorem**: Any pair of σ-finite measures `μ` and `ν`
`have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function
`f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` -/
@[priority 100] -- see Note [lower instance priority]
instance have_lebesgue_decomposition_of_sigma_finite
(μ ν : measure α) [sigma_finite μ] [sigma_finite ν] :
have_lebesgue_decomposition μ ν :=
⟨begin
-- Since `μ` and `ν` are both σ-finite, there exists a sequence of pairwise disjoint spanning
-- sets which are finite with respect to both `μ` and `ν`
obtain ⟨S, T, h₁, h₂⟩ := exists_eq_disjoint_finite_spanning_sets_in μ ν,
have h₃ : pairwise (disjoint on T.set) := h₁ ▸ h₂,
-- We define `μn` and `νn` as sequences of measures such that `μn n = μ ∩ S n` and
-- `νn n = ν ∩ S n` where `S` is the aforementioned finite spanning set sequence.
-- Since `S` is spanning, it is clear that `sum μn = μ` and `sum νn = ν`
set μn : ℕ → measure α := λ n, μ.restrict (S.set n) with hμn,
have hμ : μ = sum μn,
{ rw [hμn, ← restrict_Union h₂ S.set_mem, S.spanning, restrict_univ] },
set νn : ℕ → measure α := λ n, ν.restrict (T.set n) with hνn,
have hν : ν = sum νn,
{ rw [hνn, ← restrict_Union h₃ T.set_mem, T.spanning, restrict_univ] },
-- As `S` is finite with respect to both `μ` and `ν`, it is clear that `μn n` and `νn n` are
-- finite measures for all `n : ℕ`. Thus, we may apply the finite Lebesgue decomposition theorem
-- to `μn n` and `νn n`. We define `ξ` as the sum of the singular part of the Lebesgue
-- decompositions of `μn n` and `νn n`, and `f` as the sum of the Radon-Nikodym derviatives of
-- `μn n` and `νn n` restricted on `S n`
set ξ := sum (λ n, singular_part (μn n) (νn n)) with hξ,
set f := ∑' n, (S.set n).indicator (rn_deriv (μn n) (νn n)) with hf,
-- I claim `ξ` and `f` form a Lebesgue decomposition of `μ` and `ν`
refine ⟨⟨ξ, f⟩, _, _, _⟩,
{ exact measurable.ennreal_tsum' (λ n, measurable.indicator
(measurable_rn_deriv (μn n) (νn n)) (S.set_mem n)) },
-- We show that `ξ` is mutually singular with respect to `ν`
{ choose A hA₁ hA₂ hA₃ using λ n, mutually_singular_singular_part (μn n) (νn n),
simp only [hξ],
-- We use the set `B := ⋃ j, (S.set j) ∩ A j` where `A n` is the set provided as
-- `singular_part (μn n) (νn n) ⟂ₘ νn n`
refine ⟨⋃ j, (S.set j) ∩ A j,
measurable_set.Union (λ n, (S.set_mem n).inter (hA₁ n)), _, _⟩,
-- `ξ B = 0` since `ξ B = ∑ i j, singular_part (μn j) (νn j) (S.set i ∩ A i)`
-- `= ∑ i, singular_part (μn i) (νn i) (S.set i ∩ A i)`
-- `≤ ∑ i, singular_part (μn i) (νn i) (A i) = 0`
-- where the second equality follows as `singular_part (μn j) (νn j) (S.set i ∩ A i)` vanishes
-- for all `i ≠ j`
{ rw [measure_Union],
{ have : ∀ i, (sum (λ n, (μn n).singular_part (νn n))) (S.set i ∩ A i) =
(μn i).singular_part (νn i) (S.set i ∩ A i),
{ intro i, rw [sum_apply _ ((S.set_mem i).inter (hA₁ i)), tsum_eq_single i],
{ intros j hij,
rw [hμn, ← nonpos_iff_eq_zero],
refine le_trans ((singular_part_le _ _) _ ((S.set_mem i).inter (hA₁ i))) (le_of_eq _),
rw [restrict_apply ((S.set_mem i).inter (hA₁ i)), inter_comm, ← inter_assoc],
have : disjoint (S.set j) (S.set i) := h₂ hij,
rw disjoint_iff_inter_eq_empty at this,
rw [this, empty_inter, measure_empty] },
{ apply_instance } },
simp_rw [this, tsum_eq_zero_iff ennreal.summable],
intro n, exact measure_mono_null (inter_subset_right _ _) (hA₂ n) },
{ exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) },
{ exact λ n, (S.set_mem n).inter (hA₁ n) } },
-- We will now show `ν Bᶜ = 0`. This follows since `Bᶜ = ⋃ n, S.set n ∩ (A n)ᶜ` and thus,
-- `ν Bᶜ = ∑ i, ν (S.set i ∩ (A i)ᶜ) = ∑ i, (νn i) (A i)ᶜ = 0`
{ have hcompl : is_compl (⋃ n, (S.set n ∩ A n)) (⋃ n, S.set n ∩ (A n)ᶜ),
{ split,
{ rw disjoint_iff_inf_le,
rintro x ⟨hx₁, hx₂⟩, rw mem_Union at hx₁ hx₂,
obtain ⟨⟨i, hi₁, hi₂⟩, ⟨j, hj₁, hj₂⟩⟩ := ⟨hx₁, hx₂⟩,
have : i = j,
{ by_contra hij, exact (h₂ hij).le_bot ⟨hi₁, hj₁⟩ },
exact hj₂ (this ▸ hi₂) },
{ rw codisjoint_iff_le_sup,
intros x hx,
simp only [mem_Union, sup_eq_union, mem_inter_iff,
mem_union, mem_compl_iff, or_iff_not_imp_left],
intro h, push_neg at h,
rw [top_eq_univ, ← S.spanning, mem_Union] at hx,
obtain ⟨i, hi⟩ := hx,
exact ⟨i, hi, h i hi⟩ } },
rw [hcompl.compl_eq, measure_Union, tsum_eq_zero_iff ennreal.summable],
{ intro n, rw [inter_comm, ← restrict_apply (hA₁ n).compl, ← hA₃ n, hνn, h₁] },
{ exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) },
{ exact λ n, (S.set_mem n).inter (hA₁ n).compl } } },
-- Finally, it remains to show `μ = ξ + ν.with_density f`. Since `μ = sum μn`, and
-- `ξ + ν.with_density f = ∑ n, singular_part (μn n) (νn n)`
-- `+ ν.with_density (rn_deriv (μn n) (νn n)) ∩ (S.set n)`,
-- it suffices to show that the individual summands are equal. This follows by the
-- Lebesgue decomposition properties on the individual `μn n` and `νn n`
{ simp only [hξ, hf, hμ],
rw [with_density_tsum _, sum_add_sum],
{ refine sum_congr (λ n, _),
conv_lhs { rw have_lebesgue_decomposition_add (μn n) (νn n) },
suffices heq : (νn n).with_density ((μn n).rn_deriv (νn n)) =
ν.with_density ((S.set n).indicator ((μn n).rn_deriv (νn n))),
{ rw heq },
rw [hν, with_density_indicator (S.set_mem n), restrict_sum _ (S.set_mem n)],
suffices hsumeq : sum (λ (i : ℕ), (νn i).restrict (S.set n)) = νn n,
{ rw hsumeq },
ext1 s hs,
rw [sum_apply _ hs, tsum_eq_single n, hνn, h₁,
restrict_restrict (T.set_mem n), inter_self],
{ intros m hm,
rw [hνn, h₁, restrict_restrict (T.set_mem n), (h₃ hm.symm).inter_eq, restrict_empty,
coe_zero, pi.zero_apply] },
{ apply_instance } },
{ exact λ n, measurable.indicator (measurable_rn_deriv _ _) (S.set_mem n) } },
end⟩
end measure
namespace signed_measure
open measure
/-- A signed measure `s` is said to `have_lebesgue_decomposition` with respect to a measure `μ`
if the positive part and the negative part of `s` both `have_lebesgue_decomposition` with
respect to `μ`. -/
class have_lebesgue_decomposition (s : signed_measure α) (μ : measure α) : Prop :=
(pos_part : s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ)
(neg_part : s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ)
attribute [instance] have_lebesgue_decomposition.pos_part
attribute [instance] have_lebesgue_decomposition.neg_part
lemma not_have_lebesgue_decomposition_iff (s : signed_measure α)
(μ : measure α) :
¬ s.have_lebesgue_decomposition μ ↔
¬ s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ ∨
¬ s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ :=
⟨λ h, not_or_of_imp (λ hp hn, h ⟨hp, hn⟩), λ h hl, (not_and_distrib.2 h) ⟨hl.1, hl.2⟩⟩
-- `infer_instance` directly does not work
@[priority 100] -- see Note [lower instance priority]
instance have_lebesgue_decomposition_of_sigma_finite
(s : signed_measure α) (μ : measure α) [sigma_finite μ] :
s.have_lebesgue_decomposition μ :=
{ pos_part := infer_instance,
neg_part := infer_instance }
instance have_lebesgue_decomposition_neg
(s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] :
(-s).have_lebesgue_decomposition μ :=
{ pos_part :=
by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part],
apply_instance },
neg_part :=
by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part],
apply_instance } }
instance have_lebesgue_decomposition_smul
(s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ≥0) :
(r • s).have_lebesgue_decomposition μ :=
{ pos_part :=
by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part],
apply_instance },
neg_part :=
by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part],
apply_instance } }
instance have_lebesgue_decomposition_smul_real
(s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) :
(r • s).have_lebesgue_decomposition μ :=
begin
by_cases hr : 0 ≤ r,
{ lift r to ℝ≥0 using hr,
exact s.have_lebesgue_decomposition_smul μ _ },
{ rw not_le at hr,
refine
{ pos_part :=
by { rw [to_jordan_decomposition_smul_real,
jordan_decomposition.real_smul_pos_part_neg _ _ hr],
apply_instance },
neg_part :=
by { rw [to_jordan_decomposition_smul_real,
jordan_decomposition.real_smul_neg_part_neg _ _ hr],
apply_instance } } }
end
/-- Given a signed measure `s` and a measure `μ`, `s.singular_part μ` is the signed measure
such that `s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s` and
`s.singular_part μ` is mutually singular with respect to `μ`. -/
def singular_part (s : signed_measure α) (μ : measure α) : signed_measure α :=
(s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure -
(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure
section
lemma singular_part_mutually_singular (s : signed_measure α) (μ : measure α) :
s.to_jordan_decomposition.pos_part.singular_part μ ⟂ₘ
s.to_jordan_decomposition.neg_part.singular_part μ :=
begin
by_cases hl : s.have_lebesgue_decomposition μ,
{ haveI := hl,
obtain ⟨i, hi, hpos, hneg⟩ := s.to_jordan_decomposition.mutually_singular,
rw s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ at hpos,
rw s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ at hneg,
rw [add_apply, add_eq_zero_iff] at hpos hneg,
exact ⟨i, hi, hpos.1, hneg.1⟩ },
{ rw not_have_lebesgue_decomposition_iff at hl,
cases hl with hp hn,
{ rw [measure.singular_part, dif_neg hp],
exact mutually_singular.zero_left },
{ rw [measure.singular_part, measure.singular_part, dif_neg hn],
exact mutually_singular.zero_right } }
end
lemma singular_part_total_variation (s : signed_measure α) (μ : measure α) :
(s.singular_part μ).total_variation =
s.to_jordan_decomposition.pos_part.singular_part μ +
s.to_jordan_decomposition.neg_part.singular_part μ :=
begin
have : (s.singular_part μ).to_jordan_decomposition =
⟨s.to_jordan_decomposition.pos_part.singular_part μ,
s.to_jordan_decomposition.neg_part.singular_part μ, singular_part_mutually_singular s μ⟩,
{ refine jordan_decomposition.to_signed_measure_injective _,
rw to_signed_measure_to_jordan_decomposition,
refl },
{ rw [total_variation, this] },
end
lemma mutually_singular_singular_part (s : signed_measure α) (μ : measure α) :
singular_part s μ ⟂ᵥ μ.to_ennreal_vector_measure :=
begin
rw [mutually_singular_ennreal_iff, singular_part_total_variation],
change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ),
rw vector_measure.equiv_measure.right_inv μ,
exact (mutually_singular_singular_part _ _).add_left (mutually_singular_singular_part _ _)
end
end
/-- The Radon-Nikodym derivative between a signed measure and a positive measure.
`rn_deriv s μ` satisfies `μ.with_densityᵥ (s.rn_deriv μ) = s`
if and only if `s` is absolutely continuous with respect to `μ` and this fact is known as
`measure_theory.signed_measure.absolutely_continuous_iff_with_density_rn_deriv_eq`
and can be found in `measure_theory.decomposition.radon_nikodym`. -/
def rn_deriv (s : signed_measure α) (μ : measure α) : α → ℝ := λ x,
(s.to_jordan_decomposition.pos_part.rn_deriv μ x).to_real -
(s.to_jordan_decomposition.neg_part.rn_deriv μ x).to_real
variables {s t : signed_measure α}
@[measurability]
lemma measurable_rn_deriv (s : signed_measure α) (μ : measure α) :
measurable (rn_deriv s μ) :=
begin
rw [rn_deriv],
measurability,
end
lemma integrable_rn_deriv (s : signed_measure α) (μ : measure α) :
integrable (rn_deriv s μ) μ :=
begin
refine integrable.sub _ _;
{ split,
{ apply measurable.ae_strongly_measurable, measurability },
exact has_finite_integral_to_real_of_lintegral_ne_top
(lintegral_rn_deriv_lt_top _ μ).ne }
end
variables (s μ)
/-- **The Lebesgue Decomposition theorem between a signed measure and a measure**:
Given a signed measure `s` and a σ-finite measure `μ`, there exist a signed measure `t` and a
measurable and integrable function `f`, such that `t` is mutually singular with respect to `μ`
and `s = t + μ.with_densityᵥ f`. In this case `t = s.singular_part μ` and
`f = s.rn_deriv μ`. -/
theorem singular_part_add_with_density_rn_deriv_eq
[s.have_lebesgue_decomposition μ] :
s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s :=
begin
conv_rhs { rw [← to_signed_measure_to_jordan_decomposition s,
jordan_decomposition.to_signed_measure] },
rw [singular_part, rn_deriv, with_densityᵥ_sub'
(integrable_to_real_of_lintegral_ne_top _ _) (integrable_to_real_of_lintegral_ne_top _ _),
with_densityᵥ_to_real, with_densityᵥ_to_real, sub_eq_add_neg, sub_eq_add_neg,
add_comm (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, ← add_assoc,
add_assoc (-(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure),
← to_signed_measure_add, add_comm, ← add_assoc, ← neg_add, ← to_signed_measure_add,
add_comm, ← sub_eq_add_neg],
convert rfl, -- `convert rfl` much faster than `congr`
{ exact (s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ) },
{ rw add_comm,
exact (s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ) },
all_goals { exact (lintegral_rn_deriv_lt_top _ _).ne <|> measurability }
end
variables {s μ}
lemma jordan_decomposition_add_with_density_mutually_singular
{f : α → ℝ} (hf : measurable f) (htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) :
t.to_jordan_decomposition.pos_part + μ.with_density (λ (x : α), ennreal.of_real (f x)) ⟂ₘ
t.to_jordan_decomposition.neg_part + μ.with_density (λ (x : α), ennreal.of_real (-f x)) :=
begin
rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ,
change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧
_ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ,
rw [vector_measure.equiv_measure.right_inv] at htμ,
exact ((jordan_decomposition.mutually_singular _).add_right
(htμ.1.mono_ac (refl _) (with_density_absolutely_continuous _ _))).add_left
((htμ.2.symm.mono_ac (with_density_absolutely_continuous _ _) (refl _)).add_right
(with_density_of_real_mutually_singular hf))
end
lemma to_jordan_decomposition_eq_of_eq_add_with_density
{f : α → ℝ} (hf : measurable f) (hfi : integrable f μ)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
s.to_jordan_decomposition = @jordan_decomposition.mk α _
(t.to_jordan_decomposition.pos_part + μ.with_density (λ x, ennreal.of_real (f x)))
(t.to_jordan_decomposition.neg_part + μ.with_density (λ x, ennreal.of_real (- f x)))
(by { haveI := is_finite_measure_with_density_of_real hfi.2, apply_instance })
(by { haveI := is_finite_measure_with_density_of_real hfi.neg.2, apply_instance })
(jordan_decomposition_add_with_density_mutually_singular hf htμ) :=
begin
haveI := is_finite_measure_with_density_of_real hfi.2,
haveI := is_finite_measure_with_density_of_real hfi.neg.2,
refine to_jordan_decomposition_eq _,
simp_rw [jordan_decomposition.to_signed_measure, hadd],
ext i hi,
rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi,
to_signed_measure_apply_measurable hi, add_apply, add_apply,
ennreal.to_real_add, ennreal.to_real_add, add_sub_add_comm,
← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi,
← vector_measure.sub_apply, ← jordan_decomposition.to_signed_measure,
to_signed_measure_to_jordan_decomposition, vector_measure.add_apply,
← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi,
with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part hfi,
vector_measure.sub_apply];
exact (measure_lt_top _ _).ne
end
private lemma have_lebesgue_decomposition_mk' (μ : measure α)
{f : α → ℝ} (hf : measurable f) (hfi : integrable f μ)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
s.have_lebesgue_decomposition μ :=
begin
have htμ' := htμ,
rw mutually_singular_ennreal_iff at htμ,
change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ,
rw [vector_measure.equiv_measure.right_inv, total_variation_mutually_singular_iff] at htμ,
refine
{ pos_part :=
by { use ⟨t.to_jordan_decomposition.pos_part, λ x, ennreal.of_real (f x)⟩,
refine ⟨hf.ennreal_of_real, htμ.1, _⟩,
rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd },
neg_part :=
by { use ⟨t.to_jordan_decomposition.neg_part, λ x, ennreal.of_real (-f x)⟩,
refine ⟨hf.neg.ennreal_of_real, htμ.2, _⟩,
rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } }
end
lemma have_lebesgue_decomposition_mk (μ : measure α) {f : α → ℝ} (hf : measurable f)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
s.have_lebesgue_decomposition μ :=
begin
by_cases hfi : integrable f μ,
{ exact have_lebesgue_decomposition_mk' μ hf hfi htμ hadd },
{ rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd,
refine have_lebesgue_decomposition_mk' μ measurable_zero (integrable_zero _ _ μ) htμ _,
rwa [with_densityᵥ_zero, add_zero] }
end
private theorem eq_singular_part'
(t : signed_measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
t = s.singular_part μ :=
begin
have htμ' := htμ,
rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ,
change _ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧
_ ⟂ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ,
rw [vector_measure.equiv_measure.right_inv] at htμ,
{ rw [singular_part, ← t.to_signed_measure_to_jordan_decomposition,
jordan_decomposition.to_signed_measure],
congr,
{ have hfpos : measurable (λ x, ennreal.of_real (f x)), { measurability },
refine eq_singular_part hfpos htμ.1 _,
rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd },
{ have hfneg : measurable (λ x, ennreal.of_real (-f x)), { measurability },
refine eq_singular_part hfneg htμ.2 _,
rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } },
end
/-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is
mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have
`t = singular_part s μ`, i.e. `t` is the singular part of the Lebesgue decomposition between
`s` and `μ`. -/
theorem eq_singular_part (t : signed_measure α) (f : α → ℝ)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
t = s.singular_part μ :=
begin
by_cases hfi : integrable f μ,
{ refine eq_singular_part' t hfi.1.measurable_mk (hfi.congr hfi.1.ae_eq_mk) htμ _,
convert hadd using 2,
exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm },
{ rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd,
refine eq_singular_part' t measurable_zero (integrable_zero _ _ μ) htμ _,
rwa [with_densityᵥ_zero, add_zero] }
end
lemma singular_part_zero (μ : measure α) : (0 : signed_measure α).singular_part μ = 0 :=
begin
refine (eq_singular_part 0 0
vector_measure.mutually_singular.zero_left _).symm,
rw [zero_add, with_densityᵥ_zero],
end
lemma singular_part_neg (s : signed_measure α) (μ : measure α) :
(-s).singular_part μ = - s.singular_part μ :=
begin
have h₁ : ((-s).to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure =
(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure,
{ refine to_signed_measure_congr _,
rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part] },
have h₂ : ((-s).to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure =
(s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure,
{ refine to_signed_measure_congr _,
rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part] },
rw [singular_part, singular_part, neg_sub, h₁, h₂],
end
lemma singular_part_smul_nnreal (s : signed_measure α) (μ : measure α) (r : ℝ≥0) :
(r • s).singular_part μ = r • s.singular_part μ :=
begin
rw [singular_part, singular_part, smul_sub, ← to_signed_measure_smul, ← to_signed_measure_smul],
conv_lhs { congr, congr,
rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part,
singular_part_smul], skip, congr,
rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part,
singular_part_smul] }
end
lemma singular_part_smul (s : signed_measure α) (μ : measure α) (r : ℝ) :
(r • s).singular_part μ = r • s.singular_part μ :=
begin
by_cases hr : 0 ≤ r,
{ lift r to ℝ≥0 using hr,
exact singular_part_smul_nnreal s μ r },
{ rw [singular_part, singular_part],
conv_lhs { congr, congr,
rw [to_jordan_decomposition_smul_real,
jordan_decomposition.real_smul_pos_part_neg _ _ (not_le.1 hr), singular_part_smul],
skip, congr,
rw [to_jordan_decomposition_smul_real,
jordan_decomposition.real_smul_neg_part_neg _ _ (not_le.1 hr), singular_part_smul] },
rw [to_signed_measure_smul, to_signed_measure_smul, ← neg_sub, ← smul_sub],
change -(((-r).to_nnreal : ℝ) • _) = _,
rw [← neg_smul, real.coe_to_nnreal _ (le_of_lt (neg_pos.mpr (not_le.1 hr))), neg_neg] }
end
lemma singular_part_add (s t : signed_measure α) (μ : measure α)
[s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] :
(s + t).singular_part μ = s.singular_part μ + t.singular_part μ :=
begin
refine (eq_singular_part _ (s.rn_deriv μ + t.rn_deriv μ)
((mutually_singular_singular_part s μ).add_left (mutually_singular_singular_part t μ)) _).symm,
erw [with_densityᵥ_add (integrable_rn_deriv s μ) (integrable_rn_deriv t μ)],
rw [add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ),
singular_part_add_with_density_rn_deriv_eq, ← add_assoc,
singular_part_add_with_density_rn_deriv_eq],
end
lemma singular_part_sub (s t : signed_measure α) (μ : measure α)
[s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] :
(s - t).singular_part μ = s.singular_part μ - t.singular_part μ :=
by { rw [sub_eq_add_neg, sub_eq_add_neg, singular_part_add, singular_part_neg] }
/-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is
mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have
`f = rn_deriv s μ`, i.e. `f` is the Radon-Nikodym derivative of `s` and `μ`. -/
theorem eq_rn_deriv (t : signed_measure α) (f : α → ℝ) (hfi : integrable f μ)
(htμ : t ⟂ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) :
f =ᵐ[μ] s.rn_deriv μ :=
begin
set f' := hfi.1.mk f,
have hadd' : s = t + μ.with_densityᵥ f',
{ convert hadd using 2,
exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm },
haveI := have_lebesgue_decomposition_mk μ hfi.1.measurable_mk htμ hadd',
refine (integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) hfi _).symm,
rw [← add_right_inj t, ← hadd, eq_singular_part _ f htμ hadd,
singular_part_add_with_density_rn_deriv_eq],
end
lemma rn_deriv_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] :
(-s).rn_deriv μ =ᵐ[μ] - s.rn_deriv μ :=
begin
refine integrable.ae_eq_of_with_densityᵥ_eq
(integrable_rn_deriv _ _) (integrable_rn_deriv _ _).neg _,
rw [with_densityᵥ_neg, ← add_right_inj ((-s).singular_part μ),
singular_part_add_with_density_rn_deriv_eq, singular_part_neg, ← neg_add,
singular_part_add_with_density_rn_deriv_eq]
end
lemma rn_deriv_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ]
(r : ℝ) :
(r • s).rn_deriv μ =ᵐ[μ] r • s.rn_deriv μ :=
begin
refine integrable.ae_eq_of_with_densityᵥ_eq
(integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).smul r) _,
change _ = μ.with_densityᵥ ((r : ℝ) • s.rn_deriv μ),
rw [with_densityᵥ_smul (rn_deriv s μ) (r : ℝ),
← add_right_inj ((r • s).singular_part μ),
singular_part_add_with_density_rn_deriv_eq, singular_part_smul],
change _ = _ + r • _,
rw [← smul_add, singular_part_add_with_density_rn_deriv_eq],
end
lemma rn_deriv_add (s t : signed_measure α) (μ : measure α)
[s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ]
[(s + t).have_lebesgue_decomposition μ] :
(s + t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ + t.rn_deriv μ :=
begin
refine integrable.ae_eq_of_with_densityᵥ_eq
(integrable_rn_deriv _ _)
((integrable_rn_deriv _ _).add (integrable_rn_deriv _ _)) _,
rw [← add_right_inj ((s + t).singular_part μ),
singular_part_add_with_density_rn_deriv_eq,
with_densityᵥ_add (integrable_rn_deriv _ _) (integrable_rn_deriv _ _),
singular_part_add, add_assoc, add_comm (t.singular_part μ), add_assoc,
add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq,
← add_assoc, singular_part_add_with_density_rn_deriv_eq],
end
lemma rn_deriv_sub (s t : signed_measure α) (μ : measure α)
[s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ]
[hst : (s - t).have_lebesgue_decomposition μ] :
(s - t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ - t.rn_deriv μ :=
begin
rw sub_eq_add_neg at hst,
rw [sub_eq_add_neg, sub_eq_add_neg],
exactI ae_eq_trans (rn_deriv_add _ _ _)
(filter.eventually_eq.add (ae_eq_refl _) (rn_deriv_neg _ _)),
end
end signed_measure
namespace complex_measure
/-- A complex measure is said to `have_lebesgue_decomposition` with respect to a positive measure
if both its real and imaginary part `have_lebesgue_decomposition` with respect to that measure. -/
class have_lebesgue_decomposition (c : complex_measure α) (μ : measure α) : Prop :=
(re_part : c.re.have_lebesgue_decomposition μ)
(im_part : c.im.have_lebesgue_decomposition μ)
attribute [instance] have_lebesgue_decomposition.re_part
attribute [instance] have_lebesgue_decomposition.im_part
/-- The singular part between a complex measure `c` and a positive measure `μ` is the complex
measure satisfying `c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c`. This property is given
by `measure_theory.complex_measure.singular_part_add_with_density_rn_deriv_eq`. -/
def singular_part (c : complex_measure α) (μ : measure α) : complex_measure α :=
(c.re.singular_part μ).to_complex_measure (c.im.singular_part μ)
/-- The Radon-Nikodym derivative between a complex measure and a positive measure. -/
def rn_deriv (c : complex_measure α) (μ : measure α) : α → ℂ :=
λ x, ⟨c.re.rn_deriv μ x, c.im.rn_deriv μ x⟩
variable {c : complex_measure α}
lemma integrable_rn_deriv (c : complex_measure α) (μ : measure α) :
integrable (c.rn_deriv μ) μ :=
begin
rw [← mem_ℒp_one_iff_integrable, ← mem_ℒp_re_im_iff],
exact ⟨mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _),
mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _)⟩
end
theorem singular_part_add_with_density_rn_deriv_eq [c.have_lebesgue_decomposition μ] :
c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c :=
begin
conv_rhs { rw [← c.to_complex_measure_to_signed_measure] },
ext i hi : 1,
rw [vector_measure.add_apply, signed_measure.to_complex_measure_apply],
ext,
{ rw [complex.add_re, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi,
←is_R_or_C.re_eq_complex_re, ←integral_re (c.integrable_rn_deriv μ).integrable_on,
is_R_or_C.re_eq_complex_re, ← with_densityᵥ_apply _ hi],
{ change (c.re.singular_part μ + μ.with_densityᵥ (c.re.rn_deriv μ)) i = _,
rw c.re.singular_part_add_with_density_rn_deriv_eq μ },
{ exact (signed_measure.integrable_rn_deriv _ _) } },
{ rw [complex.add_im, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi,
←is_R_or_C.im_eq_complex_im, ←integral_im (c.integrable_rn_deriv μ).integrable_on,
is_R_or_C.im_eq_complex_im, ← with_densityᵥ_apply _ hi],
{ change (c.im.singular_part μ + μ.with_densityᵥ (c.im.rn_deriv μ)) i = _,
rw c.im.singular_part_add_with_density_rn_deriv_eq μ },
{ exact (signed_measure.integrable_rn_deriv _ _) } },
end
end complex_measure
end measure_theory
|
061ecc51a2ccaf357afcc9bf5172f5c16ed42ebd | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/category_theory/preadditive/schur.lean | 67119508cb93dc948ef486c646dc3e680b08cc05 | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,923 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel, Scott Morrison
-/
import category_theory.simple
import category_theory.linear
import category_theory.endomorphism
import field_theory.algebraic_closure
/-!
# Schur's lemma
We first prove the part of Schur's Lemma that holds in any preadditive category with kernels,
that any nonzero morphism between simple objects
is an isomorphism.
Second, we prove Schur's lemma for `𝕜`-linear categories with finite dimensional hom spaces,
over an algebraically closed field `𝕜`:
the hom space `X ⟶ Y` between simple objects `X` and `Y` is at most one dimensional,
and is 1-dimensional iff `X` and `Y` are isomorphic.
## Future work
It might be nice to provide a `division_ring` instance on `End X` when `X` is simple.
This is an easy consequence of the results here,
but may take some care setting up usable instances.
-/
namespace category_theory
open category_theory.limits
universes v u
variables {C : Type u} [category.{v} C]
variables [preadditive C]
/--
The part of **Schur's lemma** that holds in any preadditive category with kernels:
that a nonzero morphism between simple objects is an isomorphism.
-/
lemma is_iso_of_hom_simple [has_kernels C] {X Y : C} [simple X] [simple Y] {f : X ⟶ Y} (w : f ≠ 0) :
is_iso f :=
begin
haveI : mono f := preadditive.mono_of_kernel_zero (kernel_zero_of_nonzero_from_simple w),
exact is_iso_of_mono_of_nonzero w
end
/--
As a corollary of Schur's lemma for preadditive categories,
any morphism between simple objects is (exclusively) either an isomorphism or zero.
-/
lemma is_iso_iff_nonzero [has_kernels C] {X Y : C} [simple.{v} X] [simple.{v} Y] (f : X ⟶ Y) :
is_iso.{v} f ↔ f ≠ 0 :=
⟨λ I,
begin
introI h,
apply id_nonzero X,
simp only [←is_iso.hom_inv_id f, h, zero_comp],
end,
λ w, is_iso_of_hom_simple w⟩
open finite_dimensional
variables (𝕜 : Type*) [field 𝕜]
/--
Part of **Schur's lemma** for `𝕜`-linear categories:
the hom space between two non-isomorphic simple objects is 0-dimensional.
-/
lemma finrank_hom_simple_simple_eq_zero_of_not_iso
[has_kernels C] [linear 𝕜 C] {X Y : C} [simple.{v} X] [simple.{v} Y]
(h : (X ≅ Y) → false):
finrank 𝕜 (X ⟶ Y) = 0 :=
begin
haveI := subsingleton_of_forall_eq (0 : X ⟶ Y) (λ f, begin
have p := not_congr (is_iso_iff_nonzero f),
simp only [not_not, ne.def] at p,
refine p.mp (λ _, by exactI h (as_iso f)),
end),
exact finrank_zero_of_subsingleton,
end
variables [is_alg_closed 𝕜] [linear 𝕜 C]
-- In the proof below we have some difficulty using `I : finite_dimensional 𝕜 (X ⟶ X)`
-- where we need a `finite_dimensional 𝕜 (End X)`.
-- These are definitionally equal, but without eta reduction Lean can't see this.
-- To get around this, we use `convert I`,
-- then check the various instances agree field-by-field,
-- using `ext` equipped with the following extra lemmas:
local attribute [ext] module distrib_mul_action mul_action has_scalar
/--
An auxiliary lemma for Schur's lemma.
If `X ⟶ X` is finite dimensional, and every nonzero endomorphism is invertible,
then `X ⟶ X` is 1-dimensional.
-/
-- We prove this with the explicit `is_iso_iff_nonzero` assumption,
-- rather than just `[simple X]`, as this form is useful for
-- Müger's formulation of semisimplicity.
lemma finrank_endomorphism_eq_one
{X : C} (is_iso_iff_nonzero : ∀ f : X ⟶ X, is_iso f ↔ f ≠ 0)
[I : finite_dimensional 𝕜 (X ⟶ X)] :
finrank 𝕜 (X ⟶ X) = 1 :=
begin
have id_nonzero := (is_iso_iff_nonzero (𝟙 X)).mp (by apply_instance),
apply finrank_eq_one (𝟙 X),
{ exact id_nonzero, },
{ intro f,
haveI : nontrivial (End X) := nontrivial_of_ne _ _ id_nonzero,
obtain ⟨c, nu⟩ := @exists_spectrum_of_is_alg_closed_of_finite_dimensional 𝕜 _ _ (End X) _ _ _
(by { convert I, ext, refl, ext, refl, }) (End.of f),
use c,
rw [is_unit_iff_is_iso, is_iso_iff_nonzero, ne.def, not_not, sub_eq_zero,
algebra.algebra_map_eq_smul_one] at nu,
exact nu.symm, },
end
variables [has_kernels C]
/--
**Schur's lemma** for endomorphisms in `𝕜`-linear categories.
-/
lemma finrank_endomorphism_simple_eq_one
(X : C) [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] :
finrank 𝕜 (X ⟶ X) = 1 :=
finrank_endomorphism_eq_one 𝕜 is_iso_iff_nonzero
lemma endomorphism_simple_eq_smul_id
{X : C} [simple.{v} X] [I : finite_dimensional 𝕜 (X ⟶ X)] (f : X ⟶ X) :
∃ c : 𝕜, c • 𝟙 X = f :=
(finrank_eq_one_iff_of_nonzero' (𝟙 X) (id_nonzero X)).mp (finrank_endomorphism_simple_eq_one 𝕜 X) f
/--
**Schur's lemma** for `𝕜`-linear categories:
if hom spaces are finite dimensional, then the hom space between simples is at most 1-dimensional.
See `finrank_hom_simple_simple_eq_one_iff` and `finrank_hom_simple_simple_eq_zero_iff` below
for the refinements when we know whether or not the simples are isomorphic.
-/
-- We don't really need `[∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)]` here,
-- just at least one of `[finite_dimensional 𝕜 (X ⟶ X)]` or `[finite_dimensional 𝕜 (Y ⟶ Y)]`.
lemma finrank_hom_simple_simple_le_one
(X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] :
finrank 𝕜 (X ⟶ Y) ≤ 1 :=
begin
cases subsingleton_or_nontrivial (X ⟶ Y) with h,
{ resetI,
convert zero_le_one,
exact finrank_zero_of_subsingleton, },
{ obtain ⟨f, nz⟩ := (nontrivial_iff_exists_ne 0).mp h,
haveI fi := (is_iso_iff_nonzero f).mpr nz,
apply finrank_le_one f,
intro g,
obtain ⟨c, w⟩ := endomorphism_simple_eq_smul_id 𝕜 (g ≫ inv f),
exact ⟨c, by simpa using w =≫ f⟩, },
end
lemma finrank_hom_simple_simple_eq_one_iff
(X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] :
finrank 𝕜 (X ⟶ Y) = 1 ↔ nonempty (X ≅ Y) :=
begin
fsplit,
{ intro h,
rw finrank_eq_one_iff' at h,
obtain ⟨f, nz, -⟩ := h,
rw ←is_iso_iff_nonzero at nz,
exactI ⟨as_iso f⟩, },
{ rintro ⟨f⟩,
have le_one := finrank_hom_simple_simple_le_one 𝕜 X Y,
have zero_lt : 0 < finrank 𝕜 (X ⟶ Y) :=
finrank_pos_iff_exists_ne_zero.mpr ⟨f.hom, (is_iso_iff_nonzero f.hom).mp infer_instance⟩,
linarith, }
end
lemma finrank_hom_simple_simple_eq_zero_iff
(X Y : C) [∀ X Y : C, finite_dimensional 𝕜 (X ⟶ Y)] [simple.{v} X] [simple.{v} Y] :
finrank 𝕜 (X ⟶ Y) = 0 ↔ is_empty (X ≅ Y) :=
begin
rw [← not_nonempty_iff, ← not_congr (finrank_hom_simple_simple_eq_one_iff 𝕜 X Y)],
refine ⟨λ h, by { rw h, simp, }, λ h, _⟩,
have := finrank_hom_simple_simple_le_one 𝕜 X Y,
interval_cases finrank 𝕜 (X ⟶ Y) with h',
{ exact h', },
{ exact false.elim (h h'), },
end
end category_theory
|
277d50a936aa984b2ed765fdd17477953b630047 | 5d166a16ae129621cb54ca9dde86c275d7d2b483 | /tests/lean/tactic_state_pp.lean | f2ee7bbd6f52532e5bd8e678a41f70a8ceb1d4d6 | [
"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 | 1,062 | lean | universe variables u
inductive Vec (α : Type u) : nat → Type u
| nil : Vec 0
| cons : ∀ {n}, α → Vec n → Vec (nat.succ n)
constant f {α : Type u} {n : nat} : Vec α n → nat
axiom fax1 (α : Type u) : f (Vec.nil α) = 0
axiom fax2 {α : Type u} {n : nat} (v : Vec α (nat.succ n)) : f v = 1
open tactic
meta def pp_state_core : tactic format :=
do t ← target,
t_fmt ← pp t,
return $ to_fmt "Goal: " ++ t_fmt
meta def pp_state (s : tactic_state) : format :=
match pp_state_core s with
| result.success r _ := r
| result.exception _ _ _ := "failed to pretty print"
end
meta instance i2 : has_to_format tactic_state :=
⟨λ s, to_fmt "My custom goal visualizer" ++ format.line ++ pp_state s⟩
example {α : Type u} {n : nat} (v : Vec α n) : f v ≠ 2 :=
begin
destruct v,
intros, intro, note h := fax1 α, cc,
-- intros n1 h t, intros, intro, note h := fax2 (Vec.cons h t), cc
end
open nat
example : ∀ n, 0 < n → succ (pred n) = n :=
begin
intro n,
destruct n,
dsimp, intros, note h := lt_irrefl 0, cc,
end
|
a261aa8a988d03f0f81f796450f66b0de381c31f | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/ring_theory/noetherian.lean | 2d8a97fdb6a8b7778e6e7c3cff71c60bc1b622b9 | [] | 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 | 15,816 | lean | /-
Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Kevin Buzzard
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebraic_geometry.prime_spectrum
import Mathlib.data.multiset.finset_ops
import Mathlib.linear_algebra.linear_independent
import Mathlib.order.order_iso_nat
import Mathlib.order.compactly_generated
import Mathlib.ring_theory.ideal.operations
import Mathlib.PostPort
universes u_1 u_2 u_3 l
namespace Mathlib
/-!
# Noetherian rings and modules
The following are equivalent for a module M over a ring R:
1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises.
2. Every submodule is finitely generated.
A module satisfying these equivalent conditions is said to be a *Noetherian* R-module.
A ring is a *Noetherian ring* if it is Noetherian as a module over itself.
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module.
* `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
## Main statements
* `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form:
if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R
such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0.
* `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff
`>` is well-founded on `submodule R M`.
Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X],
is proved in `ring_theory.polynomial`.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel]
## Tags
Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module
-/
namespace submodule
/-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/
def fg {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] (N : submodule R M) :=
∃ (S : finset M), span R ↑S = N
theorem fg_def {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {N : submodule R M} : fg N ↔ ∃ (S : set M), set.finite S ∧ span R S = N := sorry
/-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/
theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type u_1} [comm_ring R] {M : Type u_2} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : fg N) (hin : N ≤ I • N) : ∃ (r : R), r - 1 ∈ I ∧ ∀ (n : M), n ∈ N → r • n = 0 := sorry
theorem fg_bot {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] : fg ⊥ :=
Exists.intro ∅
(eq.mpr (id (Eq._oldrec (Eq.refl (span R ↑∅ = ⊥)) finset.coe_empty))
(eq.mpr (id (Eq._oldrec (Eq.refl (span R ∅ = ⊥)) span_empty)) (Eq.refl ⊥)))
theorem fg_sup {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {N₁ : submodule R M} {N₂ : submodule R M} (hN₁ : fg N₁) (hN₂ : fg N₂) : fg (N₁ ⊔ N₂) := sorry
theorem fg_map {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {P : Type u_3} [add_comm_monoid P] [semimodule R P] {f : linear_map R M P} {N : submodule R M} (hs : fg N) : fg (map f N) := sorry
theorem fg_of_fg_map {R : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : linear_map R M P) (hf : linear_map.ker f = ⊥) {N : submodule R M} (hfn : fg (map f N)) : fg N := sorry
theorem fg_top {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] (N : submodule R M) : fg ⊤ ↔ fg N := sorry
theorem fg_of_linear_equiv {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {P : Type u_3} [add_comm_monoid P] [semimodule R P] (e : linear_equiv R M P) (h : fg ⊤) : fg ⊤ :=
linear_equiv.range (linear_equiv.symm e) ▸ map_top ↑(linear_equiv.symm e) ▸ fg_map h
theorem fg_prod {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] {P : Type u_3} [add_comm_monoid P] [semimodule R P] {sb : submodule R M} {sc : submodule R P} (hsb : fg sb) (hsc : fg sc) : fg (prod sb sc) := sorry
/-- 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 : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [module R M] [add_comm_group P] [module R P] (f : linear_map R M P) {s : submodule R M} (hs1 : fg (map f s)) (hs2 : fg (s ⊓ linear_map.ker f)) : fg s := sorry
theorem singleton_span_is_compact_element {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] (x : M) : complete_lattice.is_compact_element (span R (singleton x)) := sorry
/-- Finitely generated submodules are precisely compact elements in the submodule lattice -/
theorem fg_iff_compact {R : Type u_1} {M : Type u_2} [semiring R] [add_comm_monoid M] [semimodule R M] (s : submodule R M) : fg s ↔ complete_lattice.is_compact_element s := sorry
end submodule
/--
`is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module,
implemented as the predicate that all `R`-submodules of `M` are finitely generated.
-/
class is_noetherian (R : Type u_1) (M : Type u_2) [semiring R] [add_comm_monoid M] [semimodule R M]
where
noetherian : ∀ (s : submodule R M), submodule.fg s
theorem is_noetherian_submodule {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {N : submodule R M} : is_noetherian R ↥N ↔ ∀ (s : submodule R M), s ≤ N → submodule.fg s := sorry
theorem is_noetherian_submodule_left {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {N : submodule R M} : is_noetherian R ↥N ↔ ∀ (s : submodule R M), submodule.fg (N ⊓ s) := sorry
theorem is_noetherian_submodule_right {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] {N : submodule R M} : is_noetherian R ↥N ↔ ∀ (s : submodule R M), submodule.fg (s ⊓ N) := sorry
protected instance is_noetherian_submodule' {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] (N : submodule R M) : is_noetherian R ↥N :=
iff.mpr is_noetherian_submodule fun (_x : submodule R M) (_x_1 : _x ≤ N) => is_noetherian.noetherian _x
theorem is_noetherian_of_surjective {R : Type u_1} (M : Type u_2) {P : Type u_3} [ring R] [add_comm_group M] [add_comm_group P] [module R M] [module R P] (f : linear_map R M P) (hf : linear_map.range f = ⊤) [is_noetherian R M] : is_noetherian R P := sorry
theorem is_noetherian_of_linear_equiv {R : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [add_comm_group P] [module R M] [module R P] (f : linear_equiv R M P) [is_noetherian R M] : is_noetherian R P :=
is_noetherian_of_surjective M (linear_equiv.to_linear_map f) (linear_equiv.range f)
theorem is_noetherian_of_injective {R : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [add_comm_group P] [module R M] [module R P] [is_noetherian R P] (f : linear_map R M P) (hf : linear_map.ker f = ⊥) : is_noetherian R M :=
is_noetherian_of_linear_equiv (linear_equiv.symm (linear_equiv.of_injective f hf))
theorem fg_of_injective {R : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [add_comm_group P] [module R M] [module R P] [is_noetherian R P] {N : submodule R M} (f : linear_map R M P) (hf : linear_map.ker f = ⊥) : submodule.fg N :=
is_noetherian.noetherian N
protected instance is_noetherian_prod {R : Type u_1} {M : Type u_2} {P : Type u_3} [ring R] [add_comm_group M] [add_comm_group P] [module R M] [module R P] [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) :=
is_noetherian.mk
fun (s : submodule R (M × P)) =>
submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P)
(is_noetherian.noetherian (submodule.map (linear_map.snd R M P) s))
((fun (this : s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P)) =>
linear_map.map_comap_eq_self this ▸
submodule.fg_map
(is_noetherian.noetherian
(submodule.comap (linear_map.inl R M P) (s ⊓ linear_map.ker (linear_map.snd R M P)))))
fun (x : M × P) (_x : x ∈ s ⊓ linear_map.ker (linear_map.snd R M P)) => sorry)
protected instance is_noetherian_pi {R : Type u_1} {ι : Type u_2} {M : ι → Type u_3} [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) := sorry
theorem is_noetherian_iff_well_founded {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded gt := sorry
theorem well_founded_submodule_gt (R : Type u_1) (M : Type u_2) [ring R] [add_comm_group M] [module R M] [is_noetherian R M] : well_founded gt :=
iff.mp is_noetherian_iff_well_founded
theorem finite_of_linear_independent {R : Type u_1} {M : Type u_2} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R coe) : set.finite s := sorry
/-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/
theorem set_has_maximal_iff_noetherian {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] : (∀ (a : set (submodule R M)),
set.nonempty a → ∃ (M' : submodule R M), ∃ (H : M' ∈ a), ∀ (I : submodule R M), I ∈ a → M' ≤ I → I = M') ↔
is_noetherian R M := sorry
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
theorem is_noetherian.induction {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] [is_noetherian R M] {P : submodule R M → Prop} (hgt : ∀ (I : submodule R M), (∀ (J : submodule R M), J > I → P J) → P I) (I : submodule R M) : P I :=
well_founded.recursion (well_founded_submodule_gt R M) I hgt
/--
A ring is Noetherian if it is Noetherian as a module over itself,
i.e. all its ideals are finitely generated.
-/
def is_noetherian_ring (R : Type u_1) [ring R] :=
is_noetherian R R
protected instance is_noetherian_ring.to_is_noetherian {R : Type u_1} [ring R] [is_noetherian_ring R] : is_noetherian R R :=
id
protected instance ring.is_noetherian_of_fintype (R : Type u_1) (M : Type u_2) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M :=
let _inst : (p : Prop) → Decidable p := classical.dec;
is_noetherian.mk
fun (s : submodule R M) =>
Exists.intro (set.to_finset ↑s)
(eq.mpr (id (Eq._oldrec (Eq.refl (submodule.span R ↑(set.to_finset ↑s) = s)) (set.coe_to_finset ↑s)))
(eq.mpr (id (Eq._oldrec (Eq.refl (submodule.span R ↑s = s)) (submodule.span_eq s))) (Eq.refl s)))
theorem ring.is_noetherian_of_zero_eq_one {R : Type u_1} [ring R] (h01 : 0 = 1) : is_noetherian_ring R :=
ring.is_noetherian_of_fintype R R
theorem is_noetherian_of_submodule_of_noetherian (R : Type u_1) (M : Type u_2) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R ↥N :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_noetherian R ↥N)) (propext is_noetherian_iff_well_founded)))
(order_embedding.well_founded (order_embedding.dual (submodule.map_subtype.order_embedding N))
(eq.mp (Eq._oldrec (Eq.refl (is_noetherian R M)) (propext is_noetherian_iff_well_founded)) h))
theorem is_noetherian_of_quotient_of_noetherian (R : Type u_1) [ring R] (M : Type u_2) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R (submodule.quotient N) :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_noetherian R (submodule.quotient N))) (propext is_noetherian_iff_well_founded)))
(order_embedding.well_founded (order_embedding.dual (submodule.comap_mkq.order_embedding N))
(eq.mp (Eq._oldrec (Eq.refl (is_noetherian R M)) (propext is_noetherian_iff_well_founded)) h))
theorem is_noetherian_of_fg_of_noetherian {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : submodule.fg N) : is_noetherian R ↥N := sorry
theorem is_noetherian_of_fg_of_noetherian' {R : Type u_1} {M : Type u_2} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] (h : submodule.fg ⊤) : is_noetherian R M :=
(fun (this : is_noetherian R ↥⊤) => is_noetherian_of_linear_equiv (linear_equiv.of_top ⊤ rfl))
(is_noetherian_of_fg_of_noetherian ⊤ h)
/-- In a module over a noetherian ring, the submodule generated by finitely many vectors is
noetherian. -/
theorem is_noetherian_span_of_finite (R : Type u_1) {M : Type u_2} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : set.finite A) : is_noetherian R ↥(submodule.span R A) :=
is_noetherian_of_fg_of_noetherian (submodule.span R A)
(iff.mpr submodule.fg_def (Exists.intro A { left := hA, right := rfl }))
theorem is_noetherian_ring_of_surjective (R : Type u_1) [comm_ring R] (S : Type u_2) [comm_ring S] (f : R →+* S) (hf : function.surjective ⇑f) [H : is_noetherian_ring R] : is_noetherian_ring S := sorry
protected instance is_noetherian_ring_set_range {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring ↥(set.range ⇑f) :=
is_noetherian_ring_of_surjective R (↥(set.range ⇑f)) (ring_hom.cod_restrict f (set.range ⇑f) set.mem_range_self)
set.surjective_onto_range
protected instance is_noetherian_ring_range {R : Type u_1} [comm_ring R] {S : Type u_2} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring ↥(ring_hom.range f) :=
is_noetherian_ring_of_surjective R (↥(ring_hom.range f))
(ring_hom.cod_restrict' f (ring_hom.range f) (ring_hom.mem_range_self f)) (ring_hom.surjective_onto_range f)
theorem is_noetherian_ring_of_ring_equiv (R : Type u_1) [comm_ring R] {S : Type u_2} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S :=
is_noetherian_ring_of_surjective R S (ring_equiv.to_ring_hom f) (equiv.surjective (ring_equiv.to_equiv f))
namespace submodule
theorem fg_mul {R : Type u_1} {A : Type u_2} [comm_ring R] [ring A] [algebra R A] (M : submodule R A) (N : submodule R A) (hm : fg M) (hn : fg N) : fg (M * N) := sorry
theorem fg_pow {R : Type u_1} {A : Type u_2} [comm_ring R] [ring A] [algebra R A] (M : submodule R A) (h : fg M) (n : ℕ) : fg (M ^ n) := sorry
end submodule
/--In a noetherian ring, every ideal contains a product of prime ideals
([samuel, § 3.3, Lemma 3])-/
theorem exists_prime_spectrum_prod_le {R : Type u_1} [comm_ring R] [is_noetherian_ring R] (I : ideal R) : ∃ (Z : multiset (prime_spectrum R)), multiset.prod (multiset.map coe Z) ≤ I := sorry
/--In a noetherian integral domain which is not a field, every non-zero ideal contains a non-zero
product of prime ideals; in a field, the whole ring is a non-zero ideal containing only 0 as product
or prime ideals ([samuel, § 3.3, Lemma 3])
-/
theorem exists_prime_spectrum_prod_le_and_ne_bot_of_domain {A : Type u_2} [integral_domain A] [is_noetherian_ring A] (h_fA : ¬is_field A) {I : ideal A} (h_nzI : I ≠ ⊥) : ∃ (Z : multiset (prime_spectrum A)), multiset.prod (multiset.map coe Z) ≤ I ∧ multiset.prod (multiset.map coe Z) ≠ ⊥ := sorry
|
baa6e92c10ce661cdfb6faf11f6776f7e7bc3cb3 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/lambdaLiftCache.lean | b4bfceb137582f8d572253a32e4f6a15813a53b3 | [
"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 | 209 | lean | def map (f : Nat → Nat) (xs : List Nat) :=
xs.map f
set_option trace.Compiler.saveMono true
def foo (x : Nat) (xs : List Nat) :=
map (· + x) xs
def boo (x : Nat) (xs : List Nat) :=
map (· + x) xs
|
fbebf26ae9be4303d0ad788b313e42eb94eb1382 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/data/nat/div.lean | ed5f911dbfa619ef257617fc9990ea8d6c0421bf | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,365 | lean | --- Copyright (c) 2014 Jeremy Avigad. All rights reserved.
--- Released under Apache 2.0 license as described in the file LICENSE.
--- Author: Jeremy Avigad, Leonardo de Moura
-- div.lean
-- ========
--
-- This is a continuation of the development of the natural numbers, with a general way of
-- defining recursive functions, and definitions of div, mod, and gcd.
import data.nat.sub logic data.prod.wf
import algebra.relation
import tools.fake_simplifier
open eq.ops well_founded decidable fake_simplifier prod
open relation relation.iff_ops
namespace nat
-- Auxiliary lemma used to justify div
private definition div_rec_lemma {x y : nat} (H : 0 < y ∧ y ≤ x) : x - y < x :=
and.rec_on H (λ ypos ylex,
sub.lt (lt_le.trans ypos ylex) ypos)
private definition div.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat :=
dif 0 < y ∧ y ≤ x then (λ Hp, f (x - y) (div_rec_lemma Hp) y + 1) else (λ Hn, zero)
definition divide (x y : nat) :=
fix div.F x y
theorem divide_def (x y : nat) : divide x y = if 0 < y ∧ y ≤ x then divide (x - y) y + 1 else 0 :=
congr_fun (fix_eq div.F x) y
notation a div b := divide a b
theorem div_zero (a : ℕ) : a div 0 = 0 :=
divide_def a 0 ⬝ if_neg (!and.not_left (lt.irrefl 0))
theorem div_less {a b : ℕ} (h : a < b) : a div b = 0 :=
divide_def a b ⬝ if_neg (!and.not_right (lt_imp_not_ge h))
theorem zero_div (b : ℕ) : 0 div b = 0 :=
divide_def 0 b ⬝ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_le.trans l r) (lt.irrefl 0)))
theorem div_rec {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a div b = succ ((a - b) div b) :=
divide_def a b ⬝ if_pos (and.intro h₁ h₂)
theorem div_add_self_right {x z : ℕ} (H : z > 0) : (x + z) div z = succ (x div z) :=
calc (x + z) div z
= if 0 < z ∧ z ≤ x + z then divide (x + z - z) z + 1 else 0 : !divide_def
... = divide (x + z - z) z + 1 : if_pos (and.intro H (le_add_left z x))
... = succ (x div z) : sub_add_left
theorem div_add_mul_self_right {x y z : ℕ} (H : z > 0) : (x + y * z) div z = x div z + y :=
induction_on y
(calc (x + zero * z) div z = (x + zero) div z : mul.zero_left
... = x div z : add.zero_right
... = x div z + zero : add.zero_right)
(take y,
assume IH : (x + y * z) div z = x div z + y, calc
(x + succ y * z) div z = (x + y * z + z) div z : by simp
... = succ ((x + y * z) div z) : div_add_self_right H
... = x div z + succ y : by simp)
private definition mod.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat :=
dif 0 < y ∧ y ≤ x then (λh, f (x - y) (div_rec_lemma h) y) else (λh, x)
definition modulo (x y : nat) :=
fix mod.F x y
notation a mod b := modulo a b
theorem modulo_def (x y : nat) : modulo x y = if 0 < y ∧ y ≤ x then modulo (x - y) y else x :=
congr_fun (fix_eq mod.F x) y
theorem mod_zero (a : ℕ) : a mod 0 = a :=
modulo_def a 0 ⬝ if_neg (!and.not_left (lt.irrefl 0))
theorem mod_less {a b : ℕ} (h : a < b) : a mod b = a :=
modulo_def a b ⬝ if_neg (!and.not_right (lt_imp_not_ge h))
theorem zero_mod (b : ℕ) : 0 mod b = 0 :=
modulo_def 0 b ⬝ if_neg (λ h, and.rec_on h (λ l r, absurd (lt_le.trans l r) (lt.irrefl 0)))
theorem mod_rec {a b : ℕ} (h₁ : b > 0) (h₂ : a ≥ b) : a mod b = (a - b) mod b :=
modulo_def a b ⬝ if_pos (and.intro h₁ h₂)
theorem mod_add_self_right {x z : ℕ} (H : z > 0) : (x + z) mod z = x mod z :=
calc (x + z) mod z
= if 0 < z ∧ z ≤ x + z then (x + z - z) mod z else _ : modulo_def
... = (x + z - z) mod z : if_pos (and.intro H (le_add_left z x))
... = x mod z : sub_add_left
theorem mod_add_mul_self_right {x y z : ℕ} (H : z > 0) : (x + y * z) mod z = x mod z :=
induction_on y
(calc (x + zero * z) mod z = (x + zero) mod z : mul.zero_left
... = x mod z : add.zero_right)
(take y,
assume IH : (x + y * z) mod z = x mod z,
calc
(x + succ y * z) mod z = (x + (y * z + z)) mod z : mul.succ_left
... = (x + y * z + z) mod z : add.assoc
... = (x + y * z) mod z : mod_add_self_right H
... = x mod z : IH)
theorem mod_mul_self_right {m n : ℕ} : (m * n) mod n = 0 :=
case_zero_pos n (by simp)
(take n,
assume npos : n > 0,
(by simp) ▸ (@mod_add_mul_self_right 0 m _ npos))
-- add_rewrite mod_mul_self_right
theorem mod_mul_self_left {m n : ℕ} : (m * n) mod m = 0 :=
!mul.comm ▸ mod_mul_self_right
-- add_rewrite mod_mul_self_left
-- ### properties of div and mod together
theorem mod_lt {x y : ℕ} (H : y > 0) : x mod y < y :=
case_strong_induction_on x
(show 0 mod y < y, from !zero_mod⁻¹ ▸ H)
(take x,
assume IH : ∀x', x' ≤ x → x' mod y < y,
show succ x mod y < y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x mod y = succ x, from mod_less H1,
show succ x mod y < y, from H2⁻¹ ▸ H1)
(assume H1 : ¬ succ x < y,
have H2 : y ≤ succ x, from not_lt_imp_ge H1,
have H3 : succ x mod y = (succ x - y) mod y, from mod_rec H H2,
have H4 : succ x - y < succ x, from sub_lt !succ_pos H,
have H5 : succ x - y ≤ x, from lt_succ_imp_le H4,
show succ x mod y < y, from H3⁻¹ ▸ IH _ H5))
theorem div_mod_eq {x y : ℕ} : x = x div y * y + x mod y :=
case_zero_pos y
(show x = x div 0 * 0 + x mod 0, from
(calc
x div 0 * 0 + x mod 0 = 0 + x mod 0 : mul.zero_right
... = x mod 0 : add.zero_left
... = x : mod_zero)⁻¹)
(take y,
assume H : y > 0,
show x = x div y * y + x mod y, from
case_strong_induction_on x
(show 0 = (0 div y) * y + 0 mod y, by simp)
(take x,
assume IH : ∀x', x' ≤ x → x' = x' div y * y + x' mod y,
show succ x = succ x div y * y + succ x mod y, from
by_cases -- (succ x < y)
(assume H1 : succ x < y,
have H2 : succ x div y = 0, from div_less H1,
have H3 : succ x mod y = succ x, from mod_less H1,
by simp)
(assume H1 : ¬ succ x < y,
have H2 : y ≤ succ x, from not_lt_imp_ge H1,
have H3 : succ x div y = succ ((succ x - y) div y), from div_rec H H2,
have H4 : succ x mod y = (succ x - y) mod y, from mod_rec H H2,
have H5 : succ x - y < succ x, from sub_lt !succ_pos H,
have H6 : succ x - y ≤ x, from lt_succ_imp_le H5,
(calc
succ x div y * y + succ x mod y = succ ((succ x - y) div y) * y + succ x mod y : H3
... = ((succ x - y) div y) * y + y + succ x mod y : mul.succ_left
... = ((succ x - y) div y) * y + y + (succ x - y) mod y : H4
... = ((succ x - y) div y) * y + (succ x - y) mod y + y : add.right_comm
... = succ x - y + y : {!(IH _ H6)⁻¹}
... = succ x : add_sub_ge_left H2)⁻¹)))
theorem mod_le {x y : ℕ} : x mod y ≤ x :=
div_mod_eq⁻¹ ▸ !le_add_left
--- a good example where simplifying using the context causes problems
theorem remainder_unique {y : ℕ} (H : y > 0) {q1 r1 q2 r2 : ℕ} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : r1 = r2 :=
calc
r1 = r1 mod y : by simp
... = (r1 + q1 * y) mod y : (mod_add_mul_self_right H)⁻¹
... = (q1 * y + r1) mod y : add.comm
... = (r2 + q2 * y) mod y : by simp
... = r2 mod y : mod_add_mul_self_right H
... = r2 : by simp
theorem quotient_unique {y : ℕ} (H : y > 0) {q1 r1 q2 r2 : ℕ} (H1 : r1 < y) (H2 : r2 < y)
(H3 : q1 * y + r1 = q2 * y + r2) : q1 = q2 :=
have H4 : q1 * y + r2 = q2 * y + r2, from (remainder_unique H H1 H2 H3) ▸ H3,
have H5 : q1 * y = q2 * y, from add.cancel_right H4,
have H6 : y > 0, from le_lt.trans !zero_le H1,
show q1 = q2, from mul_cancel_right H6 H5
theorem div_mul_mul {z x y : ℕ} (zpos : z > 0) : (z * x) div (z * y) = x div y :=
by_cases -- (y = 0)
(assume H : y = 0, by simp)
(assume H : y ≠ 0,
have ypos : y > 0, from ne_zero_imp_pos H,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_left zpos (mod_lt ypos),
quotient_unique zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : div_mod_eq
... = z * (x div y * y + x mod y) : div_mod_eq
... = z * (x div y * y) + z * (x mod y) : mul.distr_left
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm))
--- something wrong with the term order
--- ... = (x div y) * (z * y) + z * (x mod y) : by simp))
theorem mod_mul_mul {z x y : ℕ} (zpos : z > 0) : (z * x) mod (z * y) = z * (x mod y) :=
by_cases -- (y = 0)
(assume H : y = 0, by simp)
(assume H : y ≠ 0,
have ypos : y > 0, from ne_zero_imp_pos H,
have zypos : z * y > 0, from mul_pos zpos ypos,
have H1 : (z * x) mod (z * y) < z * y, from mod_lt zypos,
have H2 : z * (x mod y) < z * y, from mul_lt_left zpos (mod_lt ypos),
remainder_unique zypos H1 H2
(calc
((z * x) div (z * y)) * (z * y) + (z * x) mod (z * y) = z * x : div_mod_eq
... = z * (x div y * y + x mod y) : div_mod_eq
... = z * (x div y * y) + z * (x mod y) : mul.distr_left
... = (x div y) * (z * y) + z * (x mod y) : mul.left_comm))
theorem mod_one (x : ℕ) : x mod 1 = 0 :=
have H1 : x mod 1 < 1, from mod_lt !succ_pos,
le_zero (lt_succ_imp_le H1)
-- add_rewrite mod_one
theorem mod_self (n : ℕ) : n mod n = 0 :=
case n (by simp)
(take n,
have H : (succ n * 1) mod (succ n * 1) = succ n * (1 mod 1),
from mod_mul_mul !succ_pos,
(by simp) ▸ H)
-- add_rewrite mod_self
theorem div_one (n : ℕ) : n div 1 = n :=
have H : n div 1 * 1 + n mod 1 = n, from div_mod_eq⁻¹,
(by simp) ▸ H
-- add_rewrite div_one
theorem pos_div_self {n : ℕ} (H : n > 0) : n div n = 1 :=
have H1 : (n * 1) div (n * 1) = 1 div 1, from div_mul_mul H,
(by simp) ▸ H1
-- add_rewrite pos_div_self
-- Divides
-- -------
definition dvd (x y : ℕ) : Prop := y mod x = 0
infix `|` := dvd
theorem dvd_iff_mod_eq_zero {x y : ℕ} : x | y ↔ y mod x = 0 :=
eq_to_iff rfl
theorem dvd_imp_div_mul_eq {x y : ℕ} (H : y | x) : x div y * y = x :=
(calc
x = x div y * y + x mod y : div_mod_eq
... = x div y * y + 0 : {mp dvd_iff_mod_eq_zero H}
... = x div y * y : !add.zero_right)⁻¹
-- add_rewrite dvd_imp_div_mul_eq
theorem mul_eq_imp_dvd {z x y : ℕ} (H : z * y = x) : y | x :=
have H1 : z * y = x mod y + x div y * y, from
H ⬝ div_mod_eq ⬝ !add.comm,
have H2 : (z - x div y) * y = x mod y, from
calc
(z - x div y) * y = z * y - x div y * y : mul_sub_distr_right
... = x mod y + x div y * y - x div y * y : H1
... = x mod y : sub_add_left,
show x mod y = 0, from
by_cases
(assume yz : y = 0,
have xz : x = 0, from
calc
x = z * y : H
... = z * 0 : yz
... = 0 : mul.zero_right,
calc
x mod y = x mod 0 : yz
... = x : mod_zero
... = 0 : xz)
(assume ynz : y ≠ 0,
have ypos : y > 0, from ne_zero_imp_pos ynz,
have H3 : (z - x div y) * y < y, from H2⁻¹ ▸ mod_lt ypos,
have H4 : (z - x div y) * y < 1 * y, from !mul.one_left⁻¹ ▸ H3,
have H5 : z - x div y < 1, from mul_lt_cancel_right H4,
have H6 : z - x div y = 0, from le_zero (lt_succ_imp_le H5),
calc
x mod y = (z - x div y) * y : H2
... = 0 * y : H6
... = 0 : mul.zero_left)
theorem dvd_iff_exists_mul (x y : ℕ) : x | y ↔ ∃z, z * x = y :=
iff.intro
(assume H : x | y,
show ∃z, z * x = y, from exists_intro _ (dvd_imp_div_mul_eq H))
(assume H : ∃z, z * x = y,
obtain (z : ℕ) (zx_eq : z * x = y), from H,
show x | y, from mul_eq_imp_dvd zx_eq)
theorem dvd_zero {n : ℕ} : n | 0 :=
zero_mod n
-- add_rewrite dvd_zero
theorem zero_dvd_eq (n : ℕ) : (0 | n) = (n = 0) :=
mod_zero n ▸ eq.refl (0 | n)
-- add_rewrite zero_dvd_iff
theorem one_dvd (n : ℕ) : 1 | n :=
mod_one n
-- add_rewrite one_dvd
theorem dvd_self (n : ℕ) : n | n :=
mod_self n
-- add_rewrite dvd_self
theorem dvd_mul_self_left (m n : ℕ) : m | (m * n) :=
!mod_mul_self_left
-- add_rewrite dvd_mul_self_left
theorem dvd_mul_self_right (m n : ℕ) : m | (n * m) :=
!mod_mul_self_right
-- add_rewrite dvd_mul_self_left
theorem dvd_trans {m n k : ℕ} (H1 : m | n) (H2 : n | k) : m | k :=
have H3 : n = n div m * m, from (dvd_imp_div_mul_eq H1)⁻¹,
have H4 : k = k div n * (n div m) * m, from calc
k = k div n * n : dvd_imp_div_mul_eq H2
... = k div n * (n div m * m) : H3
... = k div n * (n div m) * m : mul.assoc,
mp (!dvd_iff_exists_mul⁻¹) (exists_intro (k div n * (n div m)) (H4⁻¹))
theorem dvd_add {m n1 n2 : ℕ} (H1 : m | n1) (H2 : m | n2) : m | (n1 + n2) :=
have H : (n1 div m + n2 div m) * m = n1 + n2, from calc
(n1 div m + n2 div m) * m = n1 div m * m + n2 div m * m : mul.distr_right
... = n1 + n2 div m * m : dvd_imp_div_mul_eq H1
... = n1 + n2 : dvd_imp_div_mul_eq H2,
mp (!dvd_iff_exists_mul⁻¹) (exists_intro _ H)
theorem dvd_add_cancel_left {m n1 n2 : ℕ} : m | (n1 + n2) → m | n1 → m | n2 :=
case_zero_pos m
(assume (H1 : 0 | n1 + n2) (H2 : 0 | n1),
have H3 : n1 + n2 = 0, from (zero_dvd_eq (n1 + n2)) ▸ H1,
have H4 : n1 = 0, from (zero_dvd_eq n1) ▸ H2,
have H5 : n2 = 0, from calc
n2 = 0 + n2 : add.zero_left
... = n1 + n2 : H4
... = 0 : H3,
show 0 | n2, from H5 ▸ dvd_self n2)
(take m,
assume mpos : m > 0,
assume H1 : m | (n1 + n2),
assume H2 : m | n1,
have H3 : n1 + n2 = n1 + n2 div m * m, from calc
n1 + n2 = (n1 + n2) div m * m : dvd_imp_div_mul_eq H1
... = (n1 div m * m + n2) div m * m : dvd_imp_div_mul_eq H2
... = (n2 + n1 div m * m) div m * m : add.comm
... = (n2 div m + n1 div m) * m : div_add_mul_self_right mpos
... = n2 div m * m + n1 div m * m : mul.distr_right
... = n1 div m * m + n2 div m * m : add.comm
... = n1 + n2 div m * m : dvd_imp_div_mul_eq H2,
have H4 : n2 = n2 div m * m, from add.cancel_left H3,
mp (!dvd_iff_exists_mul⁻¹) (exists_intro _ (H4⁻¹)))
theorem dvd_add_cancel_right {m n1 n2 : ℕ} (H : m | (n1 + n2)) : m | n2 → m | n1 :=
dvd_add_cancel_left (!add.comm ▸ H)
theorem dvd_sub {m n1 n2 : ℕ} (H1 : m | n1) (H2 : m | n2) : m | (n1 - n2) :=
by_cases
(assume H3 : n1 ≥ n2,
have H4 : n1 = n1 - n2 + n2, from (add_sub_ge_left H3)⁻¹,
show m | n1 - n2, from dvd_add_cancel_right (H4 ▸ H1) H2)
(assume H3 : ¬ (n1 ≥ n2),
have H4 : n1 - n2 = 0, from le_imp_sub_eq_zero (lt_imp_le (not_le_imp_gt H3)),
show m | n1 - n2, from H4⁻¹ ▸ dvd_zero)
-- Gcd and lcm
-- -----------
private definition pair_nat.lt : nat × nat → nat × nat → Prop := measure pr₂
private definition pair_nat.lt.wf : well_founded pair_nat.lt :=
intro_k (measure.wf pr₂) 20 -- Remark: we use intro_k to be able to execute gcd efficiently in the kernel
instance pair_nat.lt.wf -- Remark: instance will not be saved in .olean
infixl [local] `≺`:50 := pair_nat.lt
private definition gcd.lt.dec (x y₁ : nat) : (succ y₁, x mod succ y₁) ≺ (x, succ y₁) :=
mod_lt (succ_pos y₁)
definition gcd.F (p₁ : nat × nat) : (Π p₂ : nat × nat, p₂ ≺ p₁ → nat) → nat :=
prod.cases_on p₁ (λx y, cases_on y
(λ f, x)
(λ y₁ (f : Πp₂, p₂ ≺ (x, succ y₁) → nat), f (succ y₁, x mod succ y₁) !gcd.lt.dec))
definition gcd (x y : nat) :=
fix gcd.F (pair x y)
theorem gcd_zero (x : nat) : gcd x 0 = x :=
well_founded.fix_eq gcd.F (x, 0)
theorem gcd_succ (x y : nat) : gcd x (succ y) = gcd (succ y) (x mod succ y) :=
well_founded.fix_eq gcd.F (x, succ y)
theorem gcd_one (n : ℕ) : gcd n 1 = 1 :=
calc gcd n 1 = gcd 1 (n mod 1) : gcd_succ n zero
... = gcd 1 0 : mod_one
... = 1 : gcd_zero
theorem gcd_def (x y : ℕ) : gcd x y = if y = 0 then x else gcd y (x mod y) :=
cases_on y
(calc gcd x 0 = x : gcd_zero x
... = if 0 = 0 then x else gcd zero (x mod zero) : (if_pos rfl)⁻¹)
(λy₁, calc
gcd x (succ y₁) = gcd (succ y₁) (x mod succ y₁) : gcd_succ x y₁
... = if succ y₁ = 0 then x else gcd (succ y₁) (x mod succ y₁) : (if_neg (succ_ne_zero y₁))⁻¹)
theorem gcd_pos (m : ℕ) {n : ℕ} (H : n > 0) : gcd m n = gcd n (m mod n) :=
gcd_def m n ⬝ if_neg (pos_imp_ne_zero H)
theorem gcd_self (n : ℕ) : gcd n n = n :=
cases_on n
rfl
(λn₁, calc
gcd (succ n₁) (succ n₁) = gcd (succ n₁) (succ n₁ mod succ n₁) : gcd_succ (succ n₁) n₁
... = gcd (succ n₁) 0 : mod_self (succ n₁)
... = succ n₁ : gcd_zero)
theorem gcd_zero_left (n : nat) : gcd 0 n = n :=
cases_on n
rfl
(λ n₁, calc
gcd 0 (succ n₁) = gcd (succ n₁) (0 mod succ n₁) : gcd_succ
... = gcd (succ n₁) 0 : zero_mod
... = (succ n₁) : gcd_zero)
theorem gcd_induct {P : ℕ → ℕ → Prop}
(m n : ℕ)
(H0 : ∀m, P m 0)
(H1 : ∀m n, 0 < n → P n (m mod n) → P m n)
: P m n :=
let Q : nat × nat → Prop := λ p : nat × nat, P (pr₁ p) (pr₂ p) in
have aux : Q (m, n), from
well_founded.induction (m, n) (λp, prod.cases_on p
(λm n, cases_on n
(λ ih, show P (pr₁ (m, 0)) (pr₂ (m, 0)), from H0 m)
(λ n₁ (ih : ∀p₂, p₂ ≺ (m, succ n₁) → P (pr₁ p₂) (pr₂ p₂)),
have hlt₁ : 0 < succ n₁, from succ_pos n₁,
have hlt₂ : (succ n₁, m mod succ n₁) ≺ (m, succ n₁), from gcd.lt.dec _ _,
have hp : P (succ n₁) (m mod succ n₁), from ih _ hlt₂,
show P m (succ n₁), from
H1 m (succ n₁) hlt₁ hp))),
aux
theorem gcd_dvd (m n : ℕ) : (gcd m n | m) ∧ (gcd m n | n) :=
gcd_induct m n
(take m,
show (gcd m 0 | m) ∧ (gcd m 0 | 0), by simp)
(take m n,
assume npos : 0 < n,
assume IH : (gcd n (m mod n) | n) ∧ (gcd n (m mod n) | (m mod n)),
have H : gcd n (m mod n) | (m div n * n + m mod n), from
dvd_add (dvd_trans (and.elim_left IH) !dvd_mul_self_right) (and.elim_right IH),
have H1 : gcd n (m mod n) | m, from div_mod_eq⁻¹ ▸ H,
have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_pos _ npos)⁻¹,
show (gcd m n | m) ∧ (gcd m n | n), from gcd_eq ▸ (and.intro H1 (and.elim_left IH)))
theorem gcd_dvd_left (m n : ℕ) : (gcd m n | m) := and.elim_left !gcd_dvd
theorem gcd_dvd_right (m n : ℕ) : (gcd m n | n) := and.elim_right !gcd_dvd
theorem gcd_greatest {m n k : ℕ} : k | m → k | n → k | (gcd m n) :=
gcd_induct m n
(take m, assume (h₁ : k | m) (h₂ : k | 0),
show k | gcd m 0, from !gcd_zero⁻¹ ▸ h₁)
(take m n,
assume npos : n > 0,
assume IH : k | n → k | (m mod n) → k | gcd n (m mod n),
assume H1 : k | m,
assume H2 : k | n,
have H3 : k | m div n * n + m mod n, from div_mod_eq ▸ H1,
have H4 : k | m mod n, from dvd_add_cancel_left H3 (dvd_trans H2 (by simp)),
have gcd_eq : gcd n (m mod n) = gcd m n, from (gcd_pos _ npos)⁻¹,
show k | gcd m n, from gcd_eq ▸ IH H2 H4)
end nat
|
bd29277b4c477d8be677a0c602fc50f517663cda | c777c32c8e484e195053731103c5e52af26a25d1 | /src/order/category/Frm.lean | 61e67e1efa97e97a68650d1985572d973cdefe1d | [
"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 | 2,411 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import order.category.Lat
import order.hom.complete_lattice
import topology.category.CompHaus.basic
import topology.sets.opens
/-!
# The category of frames
This file defines `Frm`, the category of frames.
## References
* [nLab, *Frm*](https://ncatlab.org/nlab/show/Frm)
-/
universes u
open category_theory opposite order topological_space
/-- The category of frames. -/
def Frm := bundled frame
namespace Frm
instance : has_coe_to_sort Frm Type* := bundled.has_coe_to_sort
instance (X : Frm) : frame X := X.str
/-- Construct a bundled `Frm` from a `frame`. -/
def of (α : Type*) [frame α] : Frm := bundled.of α
@[simp] lemma coe_of (α : Type*) [frame α] : ↥(of α) = α := rfl
instance : inhabited Frm := ⟨of punit⟩
/-- An abbreviation of `frame_hom` that assumes `frame` instead of the weaker `complete_lattice`.
Necessary for the category theory machinery. -/
abbreviation hom (α β : Type*) [frame α] [frame β] : Type* := frame_hom α β
instance bundled_hom : bundled_hom hom :=
⟨λ α β [frame α] [frame β], by exactI (coe_fn : frame_hom α β → α → β),
λ α [frame α], by exactI frame_hom.id α,
λ α β γ [frame α] [frame β] [frame γ], by exactI frame_hom.comp,
λ α β [frame α] [frame β], by exactI fun_like.coe_injective⟩
attribute [derive [large_category, concrete_category]] Frm
instance has_forget_to_Lat : has_forget₂ Frm Lat :=
{ forget₂ := { obj := λ X, ⟨X⟩, map := λ X Y, frame_hom.to_lattice_hom } }
/-- Constructs an isomorphism of frames from an order isomorphism between them. -/
@[simps] def iso.mk {α β : Frm.{u}} (e : α ≃o β) : α ≅ β :=
{ hom := e,
inv := e.symm,
hom_inv_id' := by { ext, exact e.symm_apply_apply _ },
inv_hom_id' := by { ext, exact e.apply_symm_apply _ } }
end Frm
/-- The forgetful functor from `Topᵒᵖ` to `Frm`. -/
@[simps] def Top_op_to_Frame : Topᵒᵖ ⥤ Frm :=
{ obj := λ X, Frm.of (opens (unop X : Top)),
map := λ X Y f, opens.comap $ quiver.hom.unop f,
map_id' := λ X, opens.comap_id }
-- Note, `CompHaus` is too strong. We only need `t0_space`.
instance CompHaus_op_to_Frame.faithful : faithful (CompHaus_to_Top.op ⋙ Top_op_to_Frame.{u}) :=
⟨λ X Y f g h, quiver.hom.unop_inj $ opens.comap_injective h⟩
|
3e533d1ca9db1bfb8b7b5b0368748c50a608255e | e0f9ba56b7fedc16ef8697f6caeef5898b435143 | /src/tactic/core.lean | afca69fcb5c32e5bb14f0c5d500e1bb6819ce3e6 | [
"Apache-2.0"
] | permissive | anrddh/mathlib | 6a374da53c7e3a35cb0298b0cd67824efef362b4 | a4266a01d2dcb10de19369307c986d038c7bb6a6 | refs/heads/master | 1,656,710,827,909 | 1,589,560,456,000 | 1,589,560,456,000 | 264,271,800 | 0 | 0 | Apache-2.0 | 1,589,568,062,000 | 1,589,568,061,000 | null | UTF-8 | Lean | false | false | 83,855 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek
-/
import data.dlist.basic
import control.basic
import meta.expr
import meta.rb_map
import data.bool
import tactic.lean_core_docs
universe variable u
instance : has_lt pos :=
{ lt := λ x y, (x.line, x.column) < (y.line, y.column) }
namespace expr
open tactic
/-- Given an expr `α` representing a type with numeral structure,
`of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (α : expr) : ℕ → tactic expr :=
nat.binary_rec
(tactic.mk_mapp ``has_zero.zero [some α, none])
(λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else
do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e])
/-- Given an expr `α` representing a type with numeral structure,
`of_int α n` creates the `α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (α : expr) : ℤ → tactic expr
| (n : ℕ) := expr.of_nat α n
| -[1+ n] := do
e ← expr.of_nat α (n+1),
tactic.mk_app ``has_neg.neg [e]
/-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local
constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/
meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr :=
args.mfoldr (λarg i:expr, do
t ← infer_type arg,
sort l ← infer_type t,
return $ if arg.occurs i ∨ l ≠ level.zero
then (const `Exists [l] : expr) t (i.lambdas [arg])
else (const `and [] : expr) t i)
inner
/-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/
meta def traverse {m : Type → Type u} [applicative m]
{elab elab' : bool} (f : expr elab → m (expr elab')) :
expr elab → m (expr elab')
| (var v) := pure $ var v
| (sort l) := pure $ sort l
| (const n ls) := pure $ const n ls
| (mvar n n' e) := mvar n n' <$> f e
| (local_const n n' bi e) := local_const n n' bi <$> f e
| (app e₀ e₁) := app <$> f e₀ <*> f e₁
| (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁
| (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁
| (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂
| (macro mac es) := macro mac <$> list.traverse f es
/-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`,
with initial value `a`. -/
meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α
| x e := prod.snd <$> (state_t.run (e.traverse $ λ e',
(get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _)
end expr
namespace interaction_monad
open result
variables {σ : Type} {α : Type u}
/-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.read` in core.
meta def get_state : interaction_monad σ σ :=
λ state, success state state
/-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/
-- Note that this is a generalization of `tactic.write` in core.
meta def set_state (state : σ) : interaction_monad σ unit :=
λ _, success () state
/--
`run_with_state state tac` applies `tac` to the given state `state` and returns the result,
subsequently restoring the original state.
If `tac` fails, then `run_with_state` does too.
-/
meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α :=
λ s, match tac state with
| success val _ := success val s
| exception fn pos _ := exception fn pos s
end
end interaction_monad
namespace format
/-- `join' [a,b,c]` produces the format object `abc`.
It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/
meta def join' (xs : list format) : format :=
xs.foldl compose nil
/-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`,
where `.` represents `format.join`. -/
meta def intercalate (x : format) : list format → format :=
join' ∘ list.intersperse x
/-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)`
the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z`
each line break is decided independently -/
meta def soft_break : format :=
group line
end format
section format
open format
/-- format a `list` by separating elements with `soft_break` instead of `line` -/
meta def list.to_line_wrap_format {α : Type u} [has_to_format α] : list α → format
| [] := to_fmt "[]"
| xs := to_fmt "[" ++ group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) ++ to_fmt "]"
end format
namespace tactic
open function
/-- Private work function for `add_local_consts_as_local_hyps`: given
`mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local
hypothesis created as a result and `(var :: rest) : list expr` of more local variables we
examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the
back of the queue and recurse. If it does not, then we perform replacements inside the type of
`var` using the `mappings`, create a new associate local hypothesis, add this to the list of
mappings, and recurse. We are done once all local hypotheses have been processed.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
private meta def add_local_consts_as_local_hyps_aux
: list (expr × expr) → list expr → tactic (list (expr × expr))
| mappings [] := return mappings
| mappings (var :: rest) := do
/- Determine if `var` contains any local variables in the lift `rest`. -/
let is_dependent := var.local_type.fold ff $ λ e n b,
if b then b else e ∈ rest,
/- If so, then skip it---add it to the end of the variable queue. -/
if is_dependent then
add_local_consts_as_local_hyps_aux mappings (rest ++ [var])
else do
/- Otherwise, replace all of the local constants referenced by the type of `var` with the
respective new corresponding local hypotheses as recorded in the list `mappings`. -/
let new_type := var.local_type.replace_subexprs mappings,
/- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/
hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type),
/- Process the next variable in the queue, with the mapping list updated to include the local
hypothesis which we just created. -/
add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest
/-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the
tactic state. This is harder than it sounds, since the list of local constants which we have
been passed can have dependencies between their types.
For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly
add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as
a new local hypothesis, not the old local constant `n` with the same name. Of course, these
dependencies can be nested arbitrarily deep.
If the list of passed local constants have types which depend on one another (which can only
happen by hand-crafting the `expr`s manually), this function will loop forever. -/
meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) :=
/- The `list.reverse` below is a performance optimisation since the list of available variables
reported by the system is often mostly the reverse of the order in which they are dependent. -/
add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup
/-- `mk_local_pisn e n` instantiates the first `n` variables of a pi expression `e`,
and returns the new local constants along with the instantiated expression. Fails if `e` does
not begin with at least `n` pi binders. -/
meta def mk_local_pisn : expr → nat → tactic (list expr × expr)
| (expr.pi n bi d b) (c + 1) := do
p ← mk_local' n bi d,
(ps, r) ← mk_local_pisn (b.instantiate_var p) c,
return ((p :: ps), r)
| e 0 := return ([], e)
| _ _ := failed
-- TODO: move to `declaration` namespace in `meta/expr.lean`
/-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named
`ls`, type `t`, and body `e`. -/
meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration :=
declaration.thm n ls t (task.pure e)
/-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this
to the environment as a theorem with name `n` and universe parameters `ls`. -/
meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) :
tactic expr :=
do ((), body) ← solve_aux type tac,
body ← instantiate_mvars body,
add_decl $ mk_theorem n ls type body,
return $ expr.const n $ ls.map level.param
/-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`.
This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare
situations the latter will fail but the former will succeed. -/
meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α :=
mk_app ``id [e] >>= eval_expr α
/-- `mk_fresh_name` returns identifiers starting with underscores,
which are not legal when emitted by tactic programs. `mk_user_fresh_name`
turns the useful source of random names provided by `mk_fresh_name` into
names which are usable by tactic programs.
The returned name has four components which are all strings. -/
meta def mk_user_fresh_name : tactic name :=
do nm ← mk_fresh_name,
return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__
/-- `has_attribute' attr_name decl_name` checks whether `decl_name` has attribute `attr_name`. -/
meta def has_attribute' (attr_name decl_name : name) : tactic bool :=
succeeds (has_attribute attr_name decl_name)
/-- Checks whether the name is a simp lemma -/
meta def is_simp_lemma : name → tactic bool :=
has_attribute' `simp
/-- Checks whether the name is an instance. -/
meta def is_instance : name → tactic bool :=
has_attribute' `instance
/-- `local_decls` returns a dictionary mapping names to their corresponding declarations.
Covers all declarations from the current file. -/
meta def local_decls : tactic (name_map declaration) :=
do e ← tactic.get_env,
let xs := e.fold native.mk_rb_map
(λ d s, if environment.in_current_file' e d.to_name
then s.insert d.to_name d else s),
pure xs
/-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/
meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n :=
let nm' := nm.append_suffix ("_" ++ to_string n) in
if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm'
/-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it
returns that, otherwise it tries `nm_2`, `nm_3`, ... -/
meta def get_unused_decl_name (nm : name) : tactic name :=
get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm
/--
Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type`
but with universe params updated to match the fresh universe metavariables in `e`.
This should have the same effect as just
```lean
do e ← mk_const d.to_name,
t ← infer_type e,
return (e, t)
```
but is hopefully faster.
-/
meta def decl_mk_const (d : declaration) : tactic (expr × expr) :=
do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ,
let e : expr := expr.const d.to_name (prod.snd <$> subst),
return (e, d.type.instantiate_univ_params subst)
/--
Replace every universe metavariable in an expression with a universe parameter.
(This is useful when making new declarations.)
-/
meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr :=
do
e.list_univ_meta_vars.enum.mmap (λ n, do
let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)),
unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))),
instantiate_mvars e
/-- `mk_local n` creates a dummy local variable with name `n`.
The type of this local constant is a constant with name `n`, so it is very unlikely to be
a meaningful expression. -/
meta def mk_local (n : name) : expr :=
expr.local_const n n binder_info.default (expr.const n [])
/-- `pis loc_consts f` is used to create a pi expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with pi binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``pis [a, b] `(f a b)`` will return the expression
`Π (a : Ta) (b : Tb), f a b`. -/
meta def pis : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← pis es f,
pure $ expr.pi pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`.
`loc_consts` should be a list of local constants. The function will abstract these local
constants from `f` and bind them with lambda binders.
For example, if `a, b` are local constants with types `Ta, Tb`,
``lambdas [a, b] `(f a b)`` will return the expression
`λ (a : Ta) (b : Tb), f a b`. -/
meta def lambdas : list expr → expr → tactic expr
| (e@(expr.local_const uniq pp info _) :: es) f := do
t ← infer_type e,
f' ← lambdas es f,
pure $ expr.lam pp info t (expr.abstract_local f' uniq)
| _ f := pure f
/-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`,
`y : ty x` and `z : tz x y`, creates an expression of sigma type:
`⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`.
-/
meta def mk_psigma : list expr → tactic expr
| [] := mk_const ``punit
| [x@(expr.local_const _ _ _ _)] := pure x
| (x@(expr.local_const _ _ _ _) :: xs) :=
do y ← mk_psigma xs,
α ← infer_type x,
β ← infer_type y,
t ← lambdas [x] β >>= instantiate_mvars,
r ← mk_mapp ``psigma.mk [α,t],
pure $ r x y
| _ := fail "mk_psigma expects a list of local constants"
/-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n`
times and uses `ns` to name the resulting variables. Returns a triple: list of new variables,
remaining term and unused variable names.
-/
meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name)
| 0 e hs ns := return (hs.reverse, e, ns)
| (n + 1) e hs ns := do
t ← infer_type e,
if t.is_app_of `eq then return (hs.reverse, e, ns)
else do
[(_, [h, h'], _)] ← cases_core e (ns.take 1),
elim_gen_prod n h' (h :: hs) (ns.drop 1)
private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr)
| 0 e hs := return (hs, e)
| (n + 1) e hs := do
[(_, [h], _), (_, [h'], _)] ← induction e [],
swap,
elim_gen_sum_aux n h' (h::hs)
/-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose
type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`.
-/
meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do
(hs, h') ← elim_gen_sum_aux n e [],
gs ← get_goals,
set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1),
return $ hs.reverse ++ [h']
/-- Given `elab_def`, a tactic to solve the current goal,
`extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it
to close the goal. If `trusted` is false, it will be a meta definition. -/
meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit :=
do cxt ← list.map expr.to_implicit_local_const <$> local_context,
t ← target,
(eqns,d) ← solve_aux t elab_def,
d ← instantiate_mvars d,
t' ← pis cxt t,
d' ← lambdas cxt d,
let univ := t'.collect_univ_params,
add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted,
applyc n
/-- Attempts to close the goal with `dec_trivial`. -/
meta def exact_dec_trivial : tactic unit := `[exact dec_trivial]
/-- Runs a tactic for a result, reverting the state after completion. -/
meta def retrieve {α} (tac : tactic α) : tactic α :=
λ s, result.cases_on (tac s)
(λ a s', result.success a s)
result.exception
/-- Repeat a tactic at least once, calling it recursively on all subgoals,
until it fails. This tactic fails if the first invocation fails. -/
meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t
/-- `iterate_range m n t`: Repeat the given tactic at least `m` times and
at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/
meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit
| 0 0 t := skip
| 0 (n+1) t := try (t >> iterate_range 0 n t)
| (m+1) n t := t >> iterate_range m (n-1) t
/--
Given a tactic `tac` that takes an expression
and returns a new expression and a proof of equality,
use that tactic to change the type of the hypotheses listed in `hs`,
as well as the goal if `tgt = tt`.
Returns `tt` if any types were successfully changed.
-/
meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) :
tactic bool :=
do to_remove ← hs.mfilter $ λ h, do {
h_type ← infer_type h,
succeeds $ do
(new_h_type, pr) ← tac h_type,
assert h.local_pp_name new_h_type,
mk_eq_mp pr h >>= tactic.exact },
goal_simplified ← succeeds $ do {
guard tgt,
(new_t, pr) ← target >>= tac,
replace_target new_t pr },
to_remove.mmap' (λ h, try (clear h)),
return (¬ to_remove.empty ∨ goal_simplified)
/-- `revert_after e` reverts all local constants after local constant `e`. -/
meta def revert_after (e : expr) : tactic ℕ := do
l ← local_context,
[pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}",
let l := l.drop pos.succ, -- all local hypotheses after `e`
revert_lst l
/-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant
with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`.
`generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the
goal, in which case it just calls `assert`.
In contrast to `generalize` it already introduces the generalized variable. -/
meta def generalize' (e : expr) (n : name) : tactic expr :=
(generalize e n >> intro1) <|> note n none e
/-! ### Various tactics related to local definitions (local constants of the form `x : α := t`)
We call `t` the value of `x`. -/
/-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined
locally using a `let` expression. Otherwise it fails. -/
meta def local_def_value (e : expr) : tactic expr :=
pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad.
tactic.unsafe.type_context.run $ do
lctx <- tactic.unsafe.type_context.get_local_context,
some ldecl <- return $ lctx.get_local_decl e.local_uniq_name |
tactic.unsafe.type_context.fail format!"No such hypothesis {s}.",
some let_val <- return ldecl.value |
tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.",
return let_val
/-- `revert_deps e` reverts all the hypotheses that depend on one of the local
constants `e`, including the local definitions that have `e` in their definition.
This fixes a bug in `revert_kdeps` that does not revert local definitions for which `e` only
appears in the definition. -/
/- We cannot implement it as `revert e >> intro1`, because that would change the local constant in
the context. -/
meta def revert_deps (e : expr) : tactic ℕ := do
n ← revert_kdeps e,
l ← local_context,
[pos] ← return $ l.indexes_of e,
let l := l.drop pos.succ, -- local hypotheses after `e`
ls ← l.mfilter $ λ e', try_core (local_def_value e') >>= λ o, return $ o.elim ff $ λ e'',
e''.has_local_constant e,
n' ← revert_lst ls,
return $ n + n'
/-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form
`e : α := t`) and otherwise fails. -/
meta def is_local_def (e : expr) : tactic unit :=
retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip
/-- `clear_value e` clears the body of the local definition `e`, changing it into a regular
hypothesis. A hypothesis `e : α := t` is changed to `e : α`.
This tactic is called `clearbody` in Coq. -/
meta def clear_value (e : expr) : tactic unit := do
n ← revert_after e,
is_local_def e <|>
pp e >>= λ s, fail format!"Cannot clear the body of {s}. It is not a local definition.",
let nm := e.local_pp_name,
(generalize' e nm >> clear e) <|>
fail format!"Cannot clear the body of {nm}. The resulting goal is not type correct.",
intron n
/-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions,
`simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting
expression and a proof of equality. -/
meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) :
tactic (expr × expr) :=
prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg
/-- Caches unary type classes on a type `α : Type.{univ}`. -/
meta structure instance_cache :=
(α : expr)
(univ : level)
(inst : name_map expr)
/-- Creates an `instance_cache` for the type `α`. -/
meta def mk_instance_cache (α : expr) : tactic instance_cache :=
do u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
return ⟨α, u, mk_name_map⟩
namespace instance_cache
/-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of
`n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance
via type class resolution, and updates the cache. -/
meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) :=
match c.inst.find n with
| some i := return (c, i)
| none := do e ← mk_app n [c.α] >>= mk_instance,
return (⟨c.α, c.univ, c.inst.insert n e⟩, e)
end
open expr
/-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`,
`append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/
meta def append_typeclasses : expr → instance_cache → list expr →
tactic (instance_cache × list expr)
| (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l :=
do (c, p) ← c.get n, return (c, p :: l)
| _ c l := return (c, l)
/-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`.
-/
meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) :=
do d ← get_decl n,
(c, l) ← append_typeclasses d.type.binding_body c l,
return (c, (expr.const n [c.univ]).mk_app (c.α :: l))
/-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/
protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) :=
if n = 0 then c.mk_app ``has_zero.zero [] else do
(c, ai) ← c.get ``has_add,
(c, oi) ← c.get ``has_one,
(c, one) ← c.mk_app ``has_one.one [],
return (c, n.binary_rec one $ λ b n e,
if n = 0 then one else
cond b
((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e])
((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e]))
/-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`.
The output is either a numeral or the negation of a numeral. -/
protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr)
| (n : ℕ) := c.of_nat n
| -[1+ n] := do
(c, e) ← c.of_nat (n+1),
c.mk_app ``has_neg.neg [e]
end instance_cache
private meta def get_expl_pi_arity_aux : expr → tactic nat
| (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
new_b ← whnf (expr.instantiate_var b l),
r ← get_expl_pi_arity_aux new_b,
if bi = binder_info.default then
return (r + 1)
else
return r
| e := return 0
/-- Compute the arity of explicit arguments of the given (Pi-)type. -/
meta def get_expl_pi_arity (type : expr) : tactic nat :=
whnf type >>= get_expl_pi_arity_aux
/-- Compute the arity of explicit arguments of the given function. -/
meta def get_expl_arity (fn : expr) : tactic nat :=
infer_type fn >>= get_expl_pi_arity
/-- Auxilliary defintion for `get_pi_binders`. -/
meta def get_pi_binders_aux : list binder → expr → tactic (list binder × expr)
| es (expr.pi n bi d b) :=
do m ← mk_fresh_name,
let l := expr.local_const m n bi d,
let new_b := expr.instantiate_var b l,
get_pi_binders_aux (⟨n, bi, d⟩::es) new_b
| es e := return (es, e)
/-- Get the binders and target of a pi-type. Instantiates bound variables by
local constants. Cf. `pi_binders` in `meta.expr` (which produces open terms).
See also `mk_local_pis` in `init.core.tactic` which does almost the same. -/
meta def get_pi_binders : expr → tactic (list binder × expr) | e :=
do (es, e) ← get_pi_binders_aux [] e, return (es.reverse, e)
/-- Auxilliary definition for `get_pi_binders_dep`. -/
meta def get_pi_binders_dep_aux : ℕ → expr → tactic (list (ℕ × binder) × expr)
| n (expr.pi nm bi d b) :=
do l ← mk_local' nm bi d,
(ls, r) ← get_pi_binders_dep_aux (n+1) (expr.instantiate_var b l),
return (if b.has_var then ls else (n, ⟨nm, bi, d⟩)::ls, r)
| n e := return ([], e)
/-- A variant of `get_pi_binders` that only returns the binders that do not occur in later
arguments or in the target. Also returns the argument position of each returned binder. -/
meta def get_pi_binders_dep : expr → tactic (list (ℕ × binder) × expr) :=
get_pi_binders_dep_aux 0
/-- A variation on `assert` where a (possibly incomplete)
proof of the assertion is provided as a parameter.
``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and
use `tac` to (partially) construct a proof for it. `gs` is the
list of remaining goals in the proof of `h`.
The benefits over assert are:
- unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`;
- when `tac` does not complete the proof of `h`, returning the list
of goals allows one to write a tactic using `h` and with the confidence
that a proof will not boil over to goals left over from the proof of `h`,
unlike what would be the case when using `tactic.swap`.
-/
meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) :
tactic (expr × list expr) :=
focus1 $
do h' ← assert h p,
[g₀,g₁] ← get_goals,
set_goals [g₀], tac₀,
gs ← get_goals,
set_goals [g₁],
return (h', gs)
/-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/
meta def var_names : expr → list name
| (expr.pi n _ _ b) := n :: var_names b
| _ := []
/-- When `struct_n` is the name of a structure type,
`subobject_names struct_n` returns two lists of names `(instances, fields)`.
The names in `instances` are the projections from `struct_n` to the structures that it extends
(assuming it was defined with `old_structure_cmd false`).
The names in `fields` are the standard fields of `struct_n`. -/
meta def subobject_names (struct_n : name) : tactic (list name × list name) :=
do env ← get_env,
[c] ← pure $ env.constructors_of struct_n | fail "too many constructors",
vs ← var_names <$> (mk_const c >>= infer_type),
fields ← env.structure_fields struct_n,
return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs)
private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n :=
do (so,fs) ← subobject_names struct_n,
ts ← so.mmap (λ n, do
(_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= mk_local_pis,
expanded_field_list' $ e.get_app_fn.const_name),
return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n)
open functor function
/-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure
named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name
of the projection is `prefix.name`. -/
meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) :=
dlist.to_list <$> expanded_field_list' struct_n
/--
Return a list of all type classes which can be instantiated
for the given expression.
-/
meta def get_classes (e : expr) : tactic (list name) :=
attribute.get_instances `class >>= list.mfilter (λ n,
succeeds $ mk_app n [e] >>= mk_instance)
open nat
/-- Create a list of `n` fresh metavariables. -/
meta def mk_mvar_list : ℕ → tactic (list expr)
| 0 := pure []
| (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n
/-- Returns the only goal, or fails if there isn't just one goal. -/
meta def get_goal : tactic expr :=
do gs ← get_goals,
match gs with
| [a] := return a
| [] := fail "there are no goals"
| _ := fail "there are too many goals"
end
/-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals,
or until it fails. Always succeeds. -/
meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := tactic.all_goals $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip
/-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first
goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on
current goal. -/
meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit
| 0 tac := trace "maximal iterations reached"
| (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac)
/-- `apply_list l`: try to apply the tactics in the list `l` on the first goal, and
fail if none succeeds -/
meta def apply_list_expr : list expr → tactic unit
| [] := fail "no matching rule"
| (h::t) := do interactive.concat_tags (apply h) <|> apply_list_expr t
/-- constructs a list of expressions given a list of p-expressions, as follows:
- if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it
- if the p-expression is a user attribute, add all the theorems with this attribute
to the list.-/
meta def build_list_expr_for_apply : list pexpr → tactic (list expr)
| [] := return []
| (h::t) := do
tail ← build_list_expr_for_apply t,
a ← i_to_expr_for_apply h,
(do l ← attribute.get_instances (expr.const_name a),
m ← list.mmap mk_const l,
return (m.append tail))
<|> return (a::tail)
/--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the
first goal and the resulting subgoals, iteratively, at most `n` times -/
meta def apply_rules (hs : list pexpr) (n : nat) : tactic unit :=
do l ← build_list_expr_for_apply hs,
iterate_at_most_on_subgoals n (assumption <|> apply_list_expr l)
/-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local
context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`.
Fails if there is nothing named `h` in the local context. -/
meta def replace (h : name) (p : pexpr) : tactic unit :=
do h' ← get_local h,
p ← to_expr p,
note h none p,
clear h'
/-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp``
or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an
`iff`, returns an expression with the `iff` converted to either the forwards or backwards
implication, as requested. -/
meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr
| (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n))
| `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0)
| _ f := none
/-- `iff_mp_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/
meta def iff_mp_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mp ty (λ_, e)
/-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`.
If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/
meta def iff_mpr_core (e ty: expr) : option expr :=
mk_iff_mp_app `iff.mpr ty (λ_, e)
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the forward implication. -/
meta def iff_mp (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/-- Given an expression whose type is (a possibly iterated function producing) an `iff`,
create the expression which is the reverse implication. -/
meta def iff_mpr (e : expr) : tactic expr :=
do t ← infer_type e,
iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`"
/--
Attempts to apply `e`, and if that fails, if `e` is an `iff`,
try applying both directions separately.
-/
meta def apply_iff (e : expr) : tactic (list (name × expr)) :=
let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in
ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap)
/--
Configuration options for `apply_any`:
* `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again.
* `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again.
* `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`.
-/
meta structure apply_any_opt :=
(use_symmetry : bool := tt)
(use_exfalso : bool := tt)
(apply : expr → tactic (list (name × expr)) := tactic.apply)
/--
This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s,
and evaluates these as thunks before trying to apply them.
We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`.
-/
meta def apply_any_thunk
(lemmas : list (tactic expr))
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
do
let modes := [skip]
++ (if opt.use_symmetry then [symmetry] else [])
++ (if opt.use_exfalso then [exfalso] else []),
modes.any_of (λ m, do m,
lemmas.any_of (λ H, H >>= opt.apply >> tac)) <|>
fail "apply_any tactic failed; no lemma could be applied"
/--
`apply_any lemmas` tries to apply one of the list `lemmas` to the current goal.
`apply_any lemmas opt` allows control over how lemmas are applied.
`opt` has fields:
* `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.)
* `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.)
* `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`).
`apply_any lemmas tac` calls the tactic `tac` after a successful application.
Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange
recursive invocations of `apply_any`.
-/
meta def apply_any
(lemmas : list expr)
(opt : apply_any_opt := {})
(tac : tactic unit := skip) : tactic unit :=
apply_any_thunk (lemmas.map pure) opt tac
/-- Try to apply a hypothesis from the local context to the goal. -/
meta def apply_assumption : tactic unit :=
local_context >>= apply_any
/-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails
if this is not a definitional equality.
`change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e`
by reverting `h`, changing the goal, and reintroducing hypotheses. -/
meta def change_core (e : expr) : option expr → tactic unit
| none := tactic.change e
| (some h) :=
do num_reverted : ℕ ← revert h,
expr.pi n bi d b ← target,
tactic.change $ expr.pi n bi e b,
intron num_reverted
/--
`change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`,
assuming `olde` and `newe` are defeq when elaborated.
-/
meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit :=
do h ← get_local hyp,
tp ← infer_type h,
olde ← to_expr olde, newe ← to_expr newe,
let repl_tp := tp.replace (λ a n, if a = olde then some newe else none),
change_core repl_tp (some h)
/-- Returns a list of all metavariables in the current partial proof. This can differ from
the list of goals, since the goals can be manually edited. -/
meta def metavariables : tactic (list expr) :=
expr.list_meta_vars <$> result
/-- Fail if the target contains a metavariable. -/
meta def no_mvars_in_target : tactic unit :=
expr.has_meta_var <$> target >>= guardb ∘ bnot
/-- Succeeds only if the current goal is a proposition. -/
meta def propositional_goal : tactic unit :=
do g :: _ ← get_goals,
is_proof g >>= guardb
/-- Succeeds only if we can construct an instance showing the
current goal is a subsingleton type. -/
meta def subsingleton_goal : tactic unit :=
do g :: _ ← get_goals,
ty ← infer_type g >>= instantiate_mvars,
to_expr ``(subsingleton %%ty) >>= mk_instance >> skip
/--
Succeeds only if the current goal is "terminal",
in the sense that no other goals depend on it
(except possibly through shared metavariables; see `independent_goal`).
-/
meta def terminal_goal : tactic unit :=
propositional_goal <|> subsingleton_goal <|>
do g₀ :: _ ← get_goals,
mvars ← (λ L, list.erase L g₀) <$> metavariables,
mvars.mmap' $ λ g, do
t ← infer_type g >>= instantiate_mvars,
d ← kdepends_on t g₀,
monad.whenb d $
pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.")
/--
Succeeds only if the current goal is "independent", in the sense
that no other goals depend on it, even through shared meta-variables.
-/
meta def independent_goal : tactic unit :=
no_mvars_in_target >> terminal_goal
/-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`,
it only unfolds reducible definitions, so it sometimes fails faster. -/
meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible
variable {α : Type}
private meta def iterate_aux (t : tactic α) : list α → tactic (list α)
| L := (do r ← t, iterate_aux (r :: L)) <|> return L
/-- Apply a tactic as many times as possible, collecting the results in a list. -/
meta def iterate' (t : tactic α) : tactic (list α) :=
list.reverse <$> iterate_aux t []
/-- Apply a tactic as many times as possible, collecting the results in a list.
Fail if the tactic does not succeed at least once. -/
meta def iterate1 (t : tactic α) : tactic (α × list α) :=
do r ← decorate_ex "iterate1 failed: tactic did not succeed" t,
L ← iterate' t,
return (r, L)
/-- Introduces one or more variables and returns the new local constants.
Fails if `intro` cannot be applied. -/
meta def intros1 : tactic (list expr) :=
iterate1 intro1 >>= λ p, return (p.1 :: p.2)
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders {α : Type} (t : tactic α) : tactic α :=
do
v ← intros,
r ← t,
revert_lst v,
return r
namespace interactive
/-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/
meta def under_binders (i : itactic) : itactic := tactic.under_binders i
end interactive
/-- `successes` invokes each tactic in turn, returning the list of successful results. -/
meta def successes (tactics : list (tactic α)) : tactic (list α) :=
list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t))
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results,
and reverting to the original `tactic_state`.
-/
-- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`.
meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) :=
λ s, result.success
(tactics.map $
λ t : tactic α,
match t s with
| result.success a s' := [a]
| _ := []
end).join s
/--
Try all the tactics in a list, each time starting at the original `tactic_state`,
returning the list of successful results sorted by
the value produced by a subsequent execution of the `sort_by` tactic,
and reverting to the original `tactic_state`.
-/
meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) :
tactic (list (α × ℕ)) :=
λ s, result.success
((tactics.map $
λ t : tactic α,
match (do a ← t, n ← sort_by, return (a, n)) s with
| result.success a s' := [a]
| _ := []
end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s
/-- Return target after instantiating metavars and whnf. -/
private meta def target' : tactic expr :=
target >>= instantiate_mvars >>= whnf
/--
Just like `split`, `fsplit` applies the constructor when the type of the target is
an inductive data type with one constructor.
However it does not reorder goals or invoke `auto_param` tactics.
-/
-- FIXME check if we can remove `auto_param := ff`
meta def fsplit : tactic unit :=
do [c] ← target' >>= get_constructors_for |
fail "fsplit tactic failed, target is not an inductive datatype with only one constructor",
mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip
run_cmd add_interactive [`fsplit]
add_tactic_doc
{ name := "fsplit",
category := doc_category.tactic,
decl_names := [`tactic.interactive.fsplit],
tags := ["logic", "goal management"] }
/-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection`
succeeds, clears the old hypothesis. -/
meta def injections_and_clear : tactic unit :=
do l ← local_context,
results ← successes $ l.map $ λ e, injection e >> clear e,
when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis")
run_cmd add_interactive [`injections_and_clear]
add_tactic_doc
{ name := "injections_and_clear",
category := doc_category.tactic,
decl_names := [`tactic.interactive.injections_and_clear],
tags := ["context management"] }
/-- Calls `cases` on every local hypothesis, succeeding if
it succeeds on at least one hypothesis. -/
meta def case_bash : tactic unit :=
do l ← local_context,
r ← successes (l.reverse.map (λ h, cases h >> skip)),
when (r.empty) failed
/--
`note_anon t v`, given a proof `v : t`,
adds `h : t` to the current context, where the name `h` is fresh.
`note_anon none v` will infer the type `t` from `v`.
-/
-- While `note` provides a default value for `t`, it doesn't seem this could ever be used.
meta def note_anon (t : option expr) (v : expr) : tactic expr :=
do h ← get_unused_name `h none,
note h t v
/-- `find_local t` returns a local constant with type t, or fails if none exists. -/
meta def find_local (t : pexpr) : tactic expr :=
do t' ← to_expr t,
(prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|>
fail format!"No hypothesis found of the form: {t'}"
/-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values
of the previous local constants. `l` is a list of local constants and their values. -/
meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do
let lc := l.map prod.fst,
let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)),
t ← target,
new_goal ← mk_meta_var (t.pis lc),
old::other_goals ← get_goals,
set_goals (old :: new_goal :: other_goals),
exact ((new_goal.mk_app lc).instantiate_locals lm),
return ()
/-- Like `mk_local_pis` but translating into weak head normal form before checking if it is a `Π`.
-/
meta def mk_local_pis_whnf : expr → tactic (list expr × expr) | e := do
(expr.pi n bi d b) ← whnf e | return ([], e),
p ← mk_local' n bi d,
(ps, r) ← mk_local_pis (expr.instantiate_var b p),
return ((p :: ps), r)
/-- Changes `(h : ∀xs, ∃a:α, p a) ⊢ g` to `(d : ∀xs, a) (s : ∀xs, p (d xs) ⊢ g`. -/
meta def choose1 (h : expr) (data : name) (spec : name) : tactic expr := do
t ← infer_type h,
(ctxt, t) ← mk_local_pis_whnf t,
`(@Exists %%α %%p) ← whnf t transparency.all |
fail "expected a term of the shape ∀xs, ∃a, p xs a",
α_t ← infer_type α,
expr.sort u ← whnf α_t transparency.all,
value ← mk_local_def data (α.pis ctxt),
t' ← head_beta (p.app (value.mk_app ctxt)),
spec ← mk_local_def spec (t'.pis ctxt),
dependent_pose_core [
(value, ((((expr.const `classical.some [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt),
(spec, ((((expr.const `classical.some_spec [u]).app α).app p).app (h.mk_app ctxt)).lambdas ctxt)],
try (tactic.clear h),
intro1,
intro1
/-- Changes `(h : ∀xs, ∃as, p as) ⊢ g` to a list of functions `as`,
and a final hypothesis on `p as`. -/
meta def choose : expr → list name → tactic unit
| h [] := fail "expect list of variables"
| h [n] := do
cnt ← revert h,
intro n,
intron (cnt - 1),
return ()
| h (n::ns) := do
v ← get_unused_name >>= choose1 h n,
choose v ns
/--
Instantiates metavariables that appear in the current goal.
-/
meta def instantiate_mvars_in_target : tactic unit :=
target >>= instantiate_mvars >>= change
/--
Instantiates metavariables in all goals.
-/
meta def instantiate_mvars_in_goals : tactic unit :=
all_goals $ instantiate_mvars_in_target
/-- This makes sure that the execution of the tactic does not change the tactic state.
This can be helpful while using rewrite, apply, or expr munging.
Remember to instantiate your metavariables before you're done! -/
meta def lock_tactic_state {α} (t : tactic α) : tactic α
| s := match t s with
| result.success a s' := result.success a s
| result.exception msg pos s' := result.exception msg pos s
end
/-- Similar to `mk_local_pis` but make meta variables instead of
local constants. -/
meta def mk_meta_pis : expr → tactic (list expr × expr)
| (expr.pi n bi d b) := do
p ← mk_meta_var d,
(ps, r) ← mk_meta_pis (expr.instantiate_var b p),
return ((p :: ps), r)
| e := return ([], e)
end tactic
namespace lean.parser
open tactic interaction_monad
/-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the
current line. -/
meta def emit_command_here (str : string) : lean.parser string :=
do (_, left) ← with_input command_like str,
return left
/-- `emit_code_here str` behaves as if the string `str` were placed at the current location in
source code. -/
meta def emit_code_here : string → lean.parser unit
| str := do left ← emit_command_here str,
if left.length = 0 then return ()
else emit_code_here left
/-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`).
This function deserves a C++ implementation in core lean, and will fail if it is not called from
the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/
meta def get_current_namespace : lean.parser name :=
do n ← tactic.mk_user_fresh_name,
emit_code_here $ sformat!"def {n} := ()",
nfull ← tactic.resolve_constant n,
return $ nfull.get_nth_prefix n.components.length
/-- `get_variables` returns a list of existing variable names, along with their types and binder
info. -/
meta def get_variables : lean.parser (list (name × binder_info × expr)) :=
list.map expr.get_local_const_kind <$> list_available_include_vars
/-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been
"included" by an `include v` statement and are not (yet) `omit`ed. -/
meta def get_included_variables : lean.parser (list (name × binder_info × expr)) :=
do ns ← list_include_var_names,
list.filter (λ v, v.1 ∈ ns) <$> get_variables
/-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local
variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the
local context---precisely those variables which would be ambiently accessible if we were in a
tactic-mode block where the goals had types `es.mmap to_expr`, for example.
Returns a new `ts : tactic_state` with these local variables added, and
`mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable
`var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/
meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr)
: lean.parser (tactic_state × list (expr × expr)) :=
do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the
declared variables to a fake `tactic_state`, and perform the resolution. At the end,
`to_expr e` has done the work of determining which variables were actually referenced, which
we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for
`pexpr`s). -/
vars ← list_available_include_vars,
fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do {
/- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard
them on this first pass. (We return the mappings generated by our second invocation of this
function below.) -/
add_local_consts_as_local_hyps vars,
es.mmap to_expr
},
/- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were
referenced in `e` when it was resolved to `fake_e`.
It is important that we include variables of the kind a) because we want `simp` to have access
to declared local instances, and it is important that we only restrict to variables of kind a)
and b) together since we do not to recognise a hypothesis which is posited as a `variable`
in the environment but not referenced in the `pexpr` we were passed.
One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want
simp to use arbitrary hypotheses which were declared as `variables` in the local environment
but not referenced in the expression to simplify (as one would be expect generally in tactic
mode). -/
included_vars ← list_include_var_names,
let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name,
/- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the
`pexpr` list which we were passed.) -/
let directly_included_vars := vars.filter $ λ var,
(var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars),
/- Inflate the list `directly_included_vars` to include those variables which are "implicitly
included" by virtue of reference to one or multiple others. 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. -/
let all_implicitly_included_vars :=
expr.all_implicitly_included_variables vars directly_included_vars,
/- Capture a tactic state where both of these kinds of variables have been added as local
hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/
lean.parser.of_tactic $ do {
mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars,
ts ← get_state,
return (ts, mappings)
}
end lean.parser
namespace tactic
variables {α : Type}
/--
Hole command used to fill in a structure's field when specifying an instance.
In the following:
```lean
instance : monad id :=
{! !}
```
invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under
construction.") produces:
```lean
instance : monad id :=
{ map := _,
map_const := _,
pure := _,
seq := _,
seq_left := _,
seq_right := _,
bind := _ }
```
-/
@[hole_command] meta def instance_stub : hole_command :=
{ name := "Instance Stub",
descr := "Generate a skeleton for the structure under construction.",
action := λ _,
do tgt ← target >>= whnf,
let cl := tgt.get_app_fn.const_name,
env ← get_env,
fs ← expanded_field_list cl,
let fs := fs.map prod.snd,
let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"),
let out := format.to_string format!"{{ {fs} }",
return [(out,"")] }
add_tactic_doc
{ name := "instance_stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.instance_stub],
tags := ["instances"] }
/-- Like `resolve_name` except when the list of goals is
empty. In that situation `resolve_name` fails whereas
`resolve_name'` simply proceeds on a dummy goal -/
meta def resolve_name' (n : name) : tactic pexpr :=
do [] ← get_goals | resolve_name n,
g ← mk_mvar,
set_goals [g],
resolve_name n <* set_goals []
private meta def strip_prefix' (n : name) : list string → name → tactic name
| s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous
| s (name.mk_string a p) :=
do let n' := s.foldl (flip name.mk_string) name.anonymous,
do { n'' ← tactic.resolve_constant n',
if n'' = n
then pure n'
else strip_prefix' (a :: s) p }
<|> strip_prefix' (a :: s) p
| s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n
/-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/
meta def strip_prefix : name → tactic name
| n@(name.mk_string a a_1) :=
if (`_private).is_prefix_of n
then let n' := n.update_prefix name.anonymous in
n' <$ resolve_name' n' <|> pure n
else strip_prefix' n [a] a_1
| n := pure n
/-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/
meta def mk_patterns (t : expr) : tactic (list format) :=
do let cl := t.get_app_fn.const_name,
env ← get_env,
let fs := env.constructors_of cl,
fs.mmap $ λ f,
do { (vs,_) ← mk_const f >>= infer_type >>= mk_local_pis,
let vs := vs.filter (λ v, v.is_default_local),
vs ← vs.mmap (λ v,
do v' ← get_unused_name v.local_pp_name,
pose v' none `(()),
pure v' ),
vs.mmap' $ λ v, get_local v >>= clear,
let args := list.intersperse (" " : format) $ vs.map to_fmt,
f ← strip_prefix f,
if args.empty
then pure $ format!"| {f} := _\n"
else pure format!"| ({f} {format.join args}) := _\n" }
/--
Hole command used to generate a `match` expression.
In the following:
```lean
meta def foo (e : expr) : tactic unit :=
{! e !}
```
invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression")
produces:
```lean
meta def foo (e : expr) : tactic unit :=
match e with
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
end
```
-/
@[hole_command] meta def match_stub : hole_command :=
{ name := "Match Stub",
descr := "Generate a list of equations for a `match` expression.",
action := λ es,
do [e] ← pure es | fail "expecting one expression",
e ← to_expr e,
t ← infer_type e >>= whnf,
fs ← mk_patterns t,
e ← pp e,
let out := format.to_string format!"match {e} with\n{format.join fs}end\n",
return [(out,"")] }
add_tactic_doc
{ name := "Match Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.match_stub],
tags := ["pattern matching"] }
/--
Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition")
in the following:
```lean
meta def foo : {! expr → tactic unit !} -- `:=` is omitted
```
produces:
```lean
meta def foo : expr → tactic unit
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
A similar result can be obtained by invoking "Equations Stub" on the following:
```lean
meta def foo : expr → tactic unit := -- do not forget to write `:=`!!
{! !}
```
```lean
meta def foo : expr → tactic unit := -- don't forget to erase `:=`!!
| (expr.var a) := _
| (expr.sort a) := _
| (expr.const a a_1) := _
| (expr.mvar a a_1 a_2) := _
| (expr.local_const a a_1 a_2 a_3) := _
| (expr.app a a_1) := _
| (expr.lam a a_1 a_2 a_3) := _
| (expr.pi a a_1 a_2 a_3) := _
| (expr.elet a a_1 a_2 a_3) := _
| (expr.macro a a_1) := _
```
-/
@[hole_command] meta def eqn_stub : hole_command :=
{ name := "Equations Stub",
descr := "Generate a list of equations for a recursive definition.",
action := λ es,
do t ← match es with
| [t] := to_expr t
| [] := target
| _ := fail "expecting one type"
end,
e ← whnf t,
(v :: _,_) ← mk_local_pis e | fail "expecting a Pi-type",
t' ← infer_type v,
fs ← mk_patterns t',
t ← pp t,
let out :=
if es.empty then
format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}"
else format.to_string format!"{t}\n{format.join fs}",
return [(out,"")] }
add_tactic_doc
{ name := "Equations Stub",
category := doc_category.hole_cmd,
decl_names := [`tactic.eqn_stub],
tags := ["pattern matching"] }
/--
This command lists the constructors that can be used to satisfy the expected type.
Invoking "List Constructors" ("Show the list of constructors of the expected type")
in the following hole:
```lean
def foo : ℤ ⊕ ℕ :=
{! !}
```
produces:
```lean
def foo : ℤ ⊕ ℕ :=
{! sum.inl, sum.inr !}
```
and will display:
```lean
sum.inl : ℤ → ℤ ⊕ ℕ
sum.inr : ℕ → ℤ ⊕ ℕ
```
-/
@[hole_command] meta def list_constructors_hole : hole_command :=
{ name := "List Constructors",
descr := "Show the list of constructors of the expected type.",
action := λ es,
do t ← target >>= whnf,
(_,t) ← mk_local_pis t,
let cl := t.get_app_fn.const_name,
let args := t.get_app_args,
env ← get_env,
let cs := env.constructors_of cl,
ts ← cs.mmap $ λ c,
do { e ← mk_const c,
t ← infer_type (e.mk_app args) >>= pp,
c ← strip_prefix c,
pure format!"\n{c} : {t}\n" },
fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt),
let out := format.to_string format!"{{! {fs} !}",
trace (format.join ts).to_string,
return [(out,"")] }
add_tactic_doc
{ name := "List Constructors",
category := doc_category.hole_cmd,
decl_names := [`tactic.list_constructors_hole],
tags := ["goal information"] }
/-- Makes the declaration `classical.prop_decidable` available to type class inference.
This asserts that all propositions are decidable, but does not have computational content. -/
meta def classical : tactic unit :=
do h ← get_unused_name `_inst,
mk_const `classical.prop_decidable >>= note h none,
reset_instance_cache
open expr
/-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so,
returns the expression `f ∘ g ∘ h`. -/
meta def mk_comp (v : expr) : expr → tactic expr
| (app f e) :=
if e = v then pure f
else do
guard (¬ v.occurs f) <|> fail "bad guard",
e' ← mk_comp e >>= instantiate_mvars,
f ← instantiate_mvars f,
mk_mapp ``function.comp [none,none,none,f,e']
| e :=
do guard (e = v),
t ← infer_type e,
mk_mapp ``id [t]
/--
From a lemma of the shape `∀ x, f (g x) = h x`
derive an auxiliary lemma of the form `f ∘ g = h`
for reasoning about higher-order functions.
-/
meta def mk_higher_order_type : expr → tactic expr
| (pi n bi d b@(pi _ _ _ _)) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b'
| (pi n bi d b) :=
do v ← mk_local_def n d,
let b' := (b.instantiate_var v),
(l,r) ← match_eq b' <|> fail format!"not an equality {b'}",
l' ← mk_comp v l,
r' ← mk_comp v r,
mk_app ``eq [l',r']
| e := failed
open lean.parser interactive.types
/-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`.
It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.
-/
@[user_attribute]
meta def higher_order_attr : user_attribute unit (option name) :=
{ name := `higher_order,
parser := optional ident,
descr :=
"From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the
form `f ∘ g = h` for reasoning about higher-order functions.",
after_set := some $ λ lmm _ _,
do env ← get_env,
decl ← env.get lmm,
let num := decl.univ_params.length,
let lvls := (list.iota num).map (`l).append_after,
let l : expr := expr.const lmm $ lvls.map level.param,
t ← infer_type l >>= instantiate_mvars,
t' ← mk_higher_order_type t,
(_,pr) ← solve_aux t' $ do {
intros, applyc ``_root_.funext, intro1, applyc lmm; assumption },
pr ← instantiate_mvars pr,
lmm' ← higher_order_attr.get_param lmm,
lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime,
add_decl $ declaration.thm lmm' lvls t' (pure pr),
copy_attribute `simp lmm lmm',
copy_attribute `functor_norm lmm lmm' }
add_tactic_doc
{ name := "higher_order",
category := doc_category.attr,
decl_names := [`tactic.higher_order_attr],
tags := ["lemma derivation"] }
attribute [higher_order map_comp_pure] map_pure
/--
Use `refine` to partially discharge the goal,
or call `fconstructor` and try again.
-/
private meta def use_aux (h : pexpr) : tactic unit :=
(focus1 (refine h >> done)) <|> (fconstructor >> use_aux)
/-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations
at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to
the expected type.
```lean
example : ∃ x : ℤ, x = x :=
by tactic.use ``(42)
```
See the doc string for `tactic.interactive.use` for more information.
-/
protected meta def use (l : list pexpr) : tactic unit :=
focus1 $ seq (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}")
instantiate_mvars_in_target
/-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the
local context. -/
meta def clear_aux_decl_aux : list expr → tactic unit
| [] := skip
| (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l
/-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/
meta def clear_aux_decl : tactic unit :=
local_context >>= clear_aux_decl_aux
/-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`)
finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/
meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr)
| vs e (pi n bi d b) :=
do { v ← mk_meta_var d,
apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|>
(e arg, vs) <$ unify d t
| vs e _ := failed
/-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/
meta def apply_at (e h : expr) : tactic unit :=
do ht ← infer_type h,
et ← infer_type e,
(h', gs') ← apply_at_aux h ht [] e et,
note h.local_pp_name none h',
clear h,
gs' ← gs'.mfilter is_assigned,
(g :: gs) ← get_goals,
set_goals (g :: gs' ++ gs)
/-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/
meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit :=
do tgt ← infer_type h,
env ← get_env,
let r := get_app_fn tgt,
match env.symm_for (const_name r) with
| (some symm) := do s ← mk_const symm,
apply_at s h
| none := fail "symmetry tactic failed, target is not a relation application with the expected property."
end
precedence `setup_tactic_parser`:0
/-- `setup_tactic_parser` is a user command that opens the namespaces used in writing
interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`.
It does *not* use the `namespace` command, so it will typically be used after
`namespace tactic.interactive`.
-/
@[user_command]
meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") :
lean.parser unit :=
emit_code_here "
open lean
open lean.parser
open interactive interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many .
"
/-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if
`tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/
meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α :=
λ s, match tac s with
| (result.success r s') := (finalizer >> pure r) s'
| (result.exception msg p s') := (finalizer >> result.exception msg p) s'
end
/--
`on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed.
-/
meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s' := (handler *> result.exception msg p) s'
| ok := ok
end
/-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/
meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s :=
match tac s with
| result.exception msg p s :=
let msg (_ : unit) : format := match msg with
| some msg := add_msg ++ format.line ++ msg ()
| none := add_msg
end in
result.exception msg p s
| ok := ok
end
/-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails,
returns the error message. -/
meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) :=
λ s, match t s with
| (interaction_monad.result.success a s') := result.success (sum.inl a) s
| (interaction_monad.result.exception msg' _ s') :=
result.success (sum.inr (msg'.iget ()).to_string) s
end
/-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`.
-/
meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit :=
do x ← retrieve_or_report_error t,
match x with
| (sum.inl _) := skip
| (sum.inr msg) := if p msg then skip else fail msg
end
add_tactic_doc
{ name := "setup_tactic_parser",
category := doc_category.cmd,
decl_names := [`tactic.setup_tactic_parser_cmd],
tags := ["parsing", "notation"] }
/-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message
of `t`. -/
meta def trace_error (msg : string) (t : tactic α) : tactic α
| s := match t s with
| (result.success r s') := result.success r s'
| (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s'
| (result.exception none p s') := result.exception none p s'
end
/--
``trace_if_enabled `n msg`` traces the message `msg`
only if tracing is enabled for the name `n`.
Create new names registered for tracing with `declare_trace n`.
Then use `set_option trace.n true/false` to enable or disable tracing for `n`.
-/
meta def trace_if_enabled
(n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit :=
when_tracing n (trace msg)
/--
``trace_state_if_enabled `n msg`` prints the tactic state,
preceded by the optional string `msg`,
only if tracing is enabled for the name `n`.
-/
meta def trace_state_if_enabled
(n : name) (msg : string := "") : tactic unit :=
when_tracing n ((if msg = "" then skip else trace msg) >> trace_state)
/--
This combinator is for testing purposes. It succeeds if `t` fails with message `msg`,
and fails otherwise.
-/
meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit :=
λ s, match t s with
| (interaction_monad.result.exception msg' _ s') :=
let expected_msg := (msg'.iget ()).to_string in
if msg = expected_msg then result.success () s
else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s
| (interaction_monad.result.success a s) :=
mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s
end
/-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the
initial goals and returns the goals `tac` ended on. -/
meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) :=
do gs' ← get_goals,
set_goals gs,
finally (prod.mk <$> tac <*> get_goals) (set_goals gs')
/-- like `with_local_goals` but discards the resulting goals -/
meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α :=
prod.fst <$> with_local_goals gs tac
/-- Representation of a proof goal that lends itself to comparison. The
following goal:
```lean
l₀ : T,
l₁ : T
⊢ ∀ v : T, foo
```
is represented as
```
(2, ∀ l₀ l₁ v : T, foo)
```
The number 2 indicates that first the two bound variables of the
`∀` are actually local constant. Comparing two such goals with `=`
rather than `=ₐ` or `is_def_eq` tells us that proof script should
not see the difference between the two.
-/
meta def packaged_goal := ℕ × expr
/-- proof state made of multiple `goal` meant for comparing
the result of running different tactics -/
meta def proof_state := list packaged_goal
meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩
meta instance proof_state.inhabited : inhabited proof_state :=
(infer_instance : inhabited (list packaged_goal))
/-- create a `packaged_goal` corresponding to the current goal -/
meta def get_packaged_goal : tactic packaged_goal := do
ls ← local_context,
tgt ← target >>= instantiate_mvars,
tgt ← pis ls tgt,
pure (ls.length, tgt)
/-- `goal_of_mvar g`, with `g` a meta variable, creates a
`packaged_goal` corresponding to `g` interpretted as a proof goal -/
meta def goal_of_mvar (g : expr) : tactic packaged_goal :=
with_local_goals' [g] get_packaged_goal
/-- `get_proof_state` lists the user visible goal for each goal
of the current state and for each goal, abstracts all of the
meta variables of the other gaols.
This produces a list of goals in the form of `ℕ × expr` where
the `expr` encodes the following proof state:
```lean
2 goals
l₁ : t₁,
l₂ : t₂,
l₃ : t₃
⊢ tgt₁
⊢ tgt₂
```
as
```lean
[ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁),
(0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ]
```
with 2 goals, the first 2 bound variables encode the meta variable
of all the goals, the next 3 (in the first goal) and 0 (in the second goal)
are the local constants.
This representation allows us to compare goals and proof states while
ignoring information like the unique name of local constants and
the equality or difference of meta variables that encode the same goal.
-/
meta def get_proof_state : tactic proof_state :=
do gs ← get_goals,
gs.mmap $ λ g, do
⟨n,g⟩ ← goal_of_mvar g,
g ← gs.mfoldl (λ g v, do
g ← kabstract g v reducible ff,
pure $ pi `goal binder_info.default `(true) g ) g,
pure (n,g)
/--
Run `tac` in a disposable proof state and return the state.
See `proof_state`, `goal` and `get_proof_state`.
-/
meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) :=
try_core $ retrieve $ tac >> get_proof_state
open lean interactive
/-- A type alias for `tactic format`, standing for "pretty print format". -/
meta def pformat := tactic format
/-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/
meta def pformat.mk (fmt : format) : pformat := pure fmt
/-- an alias for `pp`. -/
meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat :=
pp x
meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat :=
⟨ id ⟩
meta instance : has_append pformat :=
⟨ λ x y, (++) <$> x <*> y ⟩
meta instance tactic.has_to_tactic_format [has_to_tactic_format α] :
has_to_tactic_format (tactic α) :=
⟨ λ x, x >>= to_pfmt ⟩
private meta def parse_pformat : string → list char → parser pexpr
| acc [] := pure ``(to_pfmt %%(reflect acc))
| acc ('\n'::s) :=
do f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f)
| acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s
| acc ('{'::s) :=
do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string,
'}'::s ← return s.to_list | fail "'}' expected",
f ← parse_pformat "" s,
pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f)
| acc (c::s) := parse_pformat (acc.str c) s
reserve prefix `pformat! `:100
/-- See `format!` in `init/meta/interactive_base.lean`.
The main differences are that `pp` is called instead of `to_fmt` and that we can use
arguments of type `tactic α` in the quotations.
Now, consider the following:
```lean
e ← to_expr ``(3 + 7),
trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...`
trace pformat!"{e}" -- outputs `3 + 7`
```
The difference is significant. And now, the following is expressible:
```lean
e ← to_expr ``(3 + 7),
trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ`
```
See also: `trace!` and `fail!`
-/
@[user_notation]
meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr :=
do e ← parse_pformat "" s.to_list,
return ``(%%e : pformat)
reserve prefix `fail! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= fail)
reserve prefix `trace! `:100
/--
The combination of `pformat` and `fail`.
-/
@[user_notation]
meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr :=
do e ← pformat_macro () s,
pure ``((%%e : pformat) >>= trace)
/-- A hackish way to get the `src` directory of mathlib. -/
meta def get_mathlib_dir : tactic string :=
do e ← get_env,
s ← e.decl_olean `tactic.reset_instance_cache,
return $ s.popn_back 17
/-- Checks whether a declaration with the given name is declared in mathlib.
If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead,
since it is expensive to execute `get_mathlib_dir` many times. -/
meta def is_in_mathlib (n : name) : tactic bool :=
do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n
/--
Runs a tactic by name.
If it is a `tactic string`, return whatever string it returns.
If it is a `tactic unit`, return the name.
(This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.)
-/
meta def name_to_tactic (n : name) : tactic string :=
do d ← get_decl n,
e ← mk_const n,
let t := d.type,
if (t =ₐ `(tactic unit)) then
(eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n))
else if (t =ₐ `(tactic string)) then
(eval_expr (tactic string) e) >>= (λ t, t)
else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`"
/-- auxiliary function for `apply_under_n_pis` -/
private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr
| n 0 _ :=
let vars := ((list.range n).reverse.map (@expr.var ff)),
bd := vars.foldl expr.app arg.mk_explicit in
func bd
| n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd)
| n (k+1) t := apply_under_n_pis_aux n 0 t
/--
Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr :=
apply_under_n_pis_aux func arg 0 n pi_expr
/--
Assumes `pi_expr` is of the form `Π x1 ... xn, _`.
Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`.
All arguments (implicit and explicit) to `arg` should be supplied. -/
meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr :=
apply_under_n_pis func arg pi_expr pi_expr.pi_arity
/--
If `func` is a `pexpr` representing a function that takes an argument `a`,
`get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`.
When `tgt` is a `pi` expr, `func` is elaborated in a context
with the domain of `tgt`.
Examples:
* ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument.
* ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`.
* ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0
-/
private meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ :=
lock_tactic_state $ do
mv ← mk_mvar,
solve_aux tgt $ intros >> to_expr ``(%%func %%mv),
expr.pi_arity <$> (instantiate_mvars mv >>= infer_type)
/--
Tries to derive instances by unfolding the newly introduced type and applying type class resolution.
For example,
```lean
@[derive ring] def new_int : Type := ℤ
```
adds an instance `ring new_int`, defined to be the instance of `ring ℤ` found by `apply_instance`.
Multiple instances can be added with `@[derive [ring, module ℝ]]`.
This derive handler applies only to declarations made using `def`, and will fail on such a
declaration if it is unable to derive an instance. It is run with higher priority than the built-in
handlers, which will fail on `def`s.
-/
@[derive_handler, priority 2000] meta def delta_instance : derive_handler :=
λ cls new_decl_name,
do env ← get_env,
if env.is_inductive new_decl_name then return ff else
do new_decl ← get_decl new_decl_name,
new_decl_pexpr ← resolve_name new_decl_name,
arity ← get_pexpr_arg_arity_with_tgt cls new_decl.type,
tgt ← to_expr $ apply_under_n_pis cls new_decl_pexpr new_decl.type (new_decl.type.pi_arity - arity),
(_, inst) ← solve_aux tgt
(intros >> reset_instance_cache >> delta_target [new_decl_name] >> apply_instance >> done),
inst ← instantiate_mvars inst,
inst ← replace_univ_metas_with_univ_params inst,
tgt ← instantiate_mvars tgt,
nm ← get_unused_decl_name $ new_decl_name <.>
match cls with
| (expr.const nm _) := nm.last
| _ := "inst"
end,
add_protected_decl $ declaration.defn nm inst.collect_univ_params tgt inst new_decl.reducibility_hints new_decl.is_trusted,
set_basic_attribute `instance nm tt,
return tt
/-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files.
`find_private_decl n (some m)` finds a private declaration named `n` in the same file where a
declaration named `m` can be found. -/
meta def find_private_decl (n : name) (fr : option name) : tactic name :=
do env ← get_env,
fn ← option_t.run (do
fr ← option_t.mk (return fr),
d ← monad_lift $ get_decl fr,
option_t.mk (return $ env.decl_olean d.to_name) ),
let p : string → bool :=
match fn with
| (some fn) := λ x, fn = x
| none := λ _, tt
end,
let xs := env.decl_filter_map (λ d,
do fn ← env.decl_olean d.to_name,
guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n),
pure d.to_name),
match xs with
| [n] := pure n
| [] := fail "no such private found"
| _ := fail "many matches found"
end
open lean.parser interactive
/-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar`
and creates a local notation to refer to it.
`import_private foo` looks for `foo` in all imported files.
When possible, make `foo` non-private rather than using this feature.
-/
@[user_command]
meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit :=
do n ← ident,
fr ← optional (tk "from" *> ident),
n ← find_private_decl n fr,
c ← resolve_constant n,
d ← get_decl n,
let c := @expr.const tt c d.univ_levels,
new_n ← new_aux_decl_name,
add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted,
let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}",
emit_command_here $ new_not,
skip .
add_tactic_doc
{ name := "import_private",
category := doc_category.cmd,
decl_names := [`tactic.import_private_cmd],
tags := ["renaming"] }
/--
The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`.
Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called.
`mk_simp_attribute simp_name none` will use a default description.
Appending the command with `with attr1 attr2 ...` will include all declarations tagged with
`attr1`, `attr2`, ... in the new simp set.
This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string
to the attribute that is defined. If you need to create a simp set in a file where this command is
not available, you should use
```lean
run_cmd mk_simp_attr `simp_name
run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here"
```
-/
@[user_command]
meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit :=
do n ← ident,
d ← parser.pexpr,
d ← to_expr ``(%%d : option string),
descr ← eval_expr (option string) d,
with_list ← types.with_ident_list <|> return [],
mk_simp_attr n with_list,
add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n
add_tactic_doc
{ name := "mk_simp_attribute",
category := doc_category.cmd,
decl_names := [`tactic.mk_simp_attribute_cmd],
tags := ["simplification"] }
end tactic
|
5c6f77f478294fc9f56cc6f1042e489c3d15e409 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/linear_algebra/finsupp.lean | 9845106e0b2dc695e9b5e25027ae5ce2bf5e6473 | [
"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 | 19,348 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
Linear structures on function with finite support `α →₀ M`.
-/
import data.monoid_algebra
noncomputable theory
open set linear_map submodule
open_locale classical
namespace finsupp
variables {α : Type*} {M : Type*} {N : Type*} {R : Type*}
variables [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
def lsingle (a : α) : M →ₗ[R] (α →₀ M) :=
⟨single a, assume a b, single_add, assume c b, (smul_single _ _ _).symm⟩
def lapply (a : α) : (α →₀ M) →ₗ[R] M := ⟨λg, g a, assume a b, rfl, assume a b, rfl⟩
section lsubtype_domain
variables (s : set α)
def lsubtype_domain : (α →₀ M) →ₗ[R] (s →₀ M) :=
⟨subtype_domain (λx, x ∈ s), assume a b, subtype_domain_add, assume c a, ext $ assume a, rfl⟩
lemma lsubtype_domain_apply (f : α →₀ M) :
(lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)) f = subtype_domain (λx, x ∈ s) f := rfl
end lsubtype_domain
@[simp] lemma lsingle_apply (a : α) (b : M) : (lsingle a : M →ₗ[R] (α →₀ M)) b = single a b :=
rfl
@[simp] lemma lapply_apply (a : α) (f : α →₀ M) : (lapply a : (α →₀ M) →ₗ[R] M) f = f a :=
rfl
@[simp] lemma ker_lsingle (a : α) : (lsingle a : M →ₗ[R] (α →₀ M)).ker = ⊥ :=
ker_eq_bot.2 (single_injective a)
lemma lsingle_range_le_ker_lapply (s t : set α) (h : disjoint s t) :
(⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) ≤ (⨅a∈t, ker (lapply a)) :=
begin
refine supr_le (assume a₁, supr_le $ assume h₁, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb a₂ h₂,
have : a₁ ≠ a₂ := assume eq, h ⟨h₁, eq.symm ▸ h₂⟩,
exact single_eq_of_ne this
end
lemma infi_ker_lapply_le_bot : (⨅a, ker (lapply a : (α →₀ M) →ₗ[R] M)) ≤ ⊥ :=
begin
simp only [le_def', mem_infi, mem_ker, mem_bot, lapply_apply],
exact assume a h, finsupp.ext h
end
lemma supr_lsingle_range : (⨆a, (lsingle a : M →ₗ[R] (α →₀ M)).range) = ⊤ :=
begin
refine (eq_top_iff.2 $ le_def'.2 $ assume f _, _),
rw [← sum_single f],
refine sum_mem _ (assume a ha, submodule.mem_supr_of_mem a $ set.mem_image_of_mem _ trivial)
end
lemma disjoint_lsingle_lsingle (s t : set α) (hs : disjoint s t) :
disjoint (⨆a∈s, (lsingle a : M →ₗ[R] (α →₀ M)).range) (⨆a∈t, (lsingle a).range) :=
begin
refine disjoint.mono
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl s)
(lsingle_range_le_ker_lapply _ _ $ disjoint_compl t)
(le_trans (le_infi $ assume i, _) infi_ker_lapply_le_bot),
classical,
by_cases his : i ∈ s,
{ by_cases hit : i ∈ t,
{ exact (hs ⟨his, hit⟩).elim },
exact inf_le_right_of_le (infi_le_of_le i $ infi_le _ hit) },
exact inf_le_left_of_le (infi_le_of_le i $ infi_le _ his)
end
lemma span_single_image (s : set M) (a : α) :
submodule.span R (single a '' s) = (submodule.span R s).map (lsingle a) :=
by rw ← span_image; refl
variables (M R)
def supported (s : set α) : submodule R (α →₀ M) :=
begin
refine ⟨ {p | ↑p.support ⊆ s }, _, _, _ ⟩,
{ simp only [subset_def, finset.mem_coe, set.mem_set_of_eq, mem_support_iff, zero_apply],
assume h ha, exact (ha rfl).elim },
{ assume p q hp hq,
refine subset.trans
(subset.trans (finset.coe_subset.2 support_add) _) (union_subset hp hq),
rw [finset.coe_union] },
{ assume a p hp,
refine subset.trans (finset.coe_subset.2 support_smul) hp }
end
variables {M}
lemma mem_supported {s : set α} (p : α →₀ M) : p ∈ (supported M R s) ↔ ↑p.support ⊆ s :=
iff.rfl
lemma mem_supported' {s : set α} (p : α →₀ M) :
p ∈ supported M R s ↔ ∀ x ∉ s, p x = 0 :=
by haveI := classical.dec_pred (λ (x : α), x ∈ s);
simp [mem_supported, set.subset_def, not_imp_comm]
lemma single_mem_supported {s : set α} {a : α} (b : M) (h : a ∈ s) :
single a b ∈ supported M R s :=
set.subset.trans support_single_subset (finset.singleton_subset_set_iff.2 h)
lemma supported_eq_span_single (s : set α) :
supported R R s = span R ((λ i, single i 1) '' s) :=
begin
refine (span_eq_of_le _ _ (le_def'.2 $ λ l hl, _)).symm,
{ rintro _ ⟨_, hp, rfl ⟩ , exact single_mem_supported R 1 hp },
{ rw ← l.sum_single,
refine sum_mem _ (λ i il, _),
convert @smul_mem R (α →₀ R) _ _ _ _ (single i 1) (l i) _,
{ simp },
apply subset_span,
apply set.mem_image_of_mem _ (hl il) }
end
variables (M R)
def restrict_dom (s : set α) : (α →₀ M) →ₗ supported M R s :=
linear_map.cod_restrict _
{ to_fun := filter (∈ s),
map_add' := λ l₁ l₂, filter_add,
map_smul' := λ a l, filter_smul }
(λ l, (mem_supported' _ _).2 $ λ x, filter_apply_neg (∈ s) l)
variables {M R}
section
@[simp] theorem restrict_dom_apply (s : set α) (l : α →₀ M) :
((restrict_dom M R s : (α →₀ M) →ₗ supported M R s) l : α →₀ M) = finsupp.filter (∈ s) l := rfl
end
theorem restrict_dom_comp_subtype (s : set α) :
(restrict_dom M R s).comp (submodule.subtype _) = linear_map.id :=
begin
ext l a,
by_cases a ∈ s; simp [h],
exact ((mem_supported' R l.1).1 l.2 a h).symm
end
theorem range_restrict_dom (s : set α) :
(restrict_dom M R s).range = ⊤ :=
begin
have := linear_map.range_comp (submodule.subtype _) (restrict_dom M R s),
rw [restrict_dom_comp_subtype, linear_map.range_id] at this,
exact eq_top_mono (submodule.map_mono le_top) this.symm
end
theorem supported_mono {s t : set α} (st : s ⊆ t) :
supported M R s ≤ supported M R t :=
λ l h, set.subset.trans h st
@[simp] theorem supported_empty : supported M R (∅ : set α) = ⊥ :=
eq_bot_iff.2 $ λ l h, (submodule.mem_bot R).2 $
by ext; simp [*, mem_supported'] at *
@[simp] theorem supported_univ : supported M R (set.univ : set α) = ⊤ :=
eq_top_iff.2 $ λ l _, set.subset_univ _
theorem supported_Union {δ : Type*} (s : δ → set α) :
supported M R (⋃ i, s i) = ⨆ i, supported M R (s i) :=
begin
refine le_antisymm _ (supr_le $ λ i, supported_mono $ set.subset_Union _ _),
haveI := classical.dec_pred (λ x, x ∈ (⋃ i, s i)),
suffices : ((submodule.subtype _).comp (restrict_dom M R (⋃ i, s i))).range ≤ ⨆ i, supported M R (s i),
{ rwa [linear_map.range_comp, range_restrict_dom, map_top, range_subtype] at this },
rw [range_le_iff_comap, eq_top_iff],
rintro l ⟨⟩,
apply finsupp.induction l, {exact zero_mem _},
refine λ x a l hl a0, add_mem _ _,
by_cases (∃ i, x ∈ s i); simp [h],
{ cases h with i hi,
exact le_supr (λ i, supported M R (s i)) i (single_mem_supported R _ hi) }
end
theorem supported_union (s t : set α) :
supported M R (s ∪ t) = supported M R s ⊔ supported M R t :=
by erw [set.union_eq_Union, supported_Union, supr_bool_eq]; refl
theorem supported_Inter {ι : Type*} (s : ι → set α) :
supported M R (⋂ i, s i) = ⨅ i, supported M R (s i) :=
begin
refine le_antisymm (le_infi $ λ i, supported_mono $ set.Inter_subset _ _) _,
simp [le_def, infi_coe, set.subset_def],
exact λ l, set.subset_Inter
end
def supported_equiv_finsupp (s : set α) : (supported M R s) ≃ₗ[R] (s →₀ M) :=
begin
let F : (supported M R s) ≃ (s →₀ M) := restrict_support_equiv s M,
refine F.to_linear_equiv _,
have : (F : (supported M R s) → (↥s →₀ M)) = ((lsubtype_domain s : (α →₀ M) →ₗ[R] (s →₀ M)).comp
(submodule.subtype (supported M R s))) := rfl,
rw this,
exact linear_map.is_linear _
end
/-- finsupp.sum as a linear map. -/
def lsum (f : α → M →ₗ[R] N) : (α →₀ M) →ₗ[R] N :=
⟨λ d, d.sum (λ i, f i),
assume d₁ d₂, by simp [sum_add_index],
assume a d, by simp [sum_smul_index', smul_sum]⟩
@[simp] lemma coe_lsum (f : α → M →ₗ[R] N) : (lsum f : (α →₀ M) → N) = λ d, d.sum (λ i, f i) := rfl
theorem lsum_apply (f : α → M →ₗ[R] N) (l : α →₀ M) :
finsupp.lsum f l = l.sum (λ b, f b) := rfl
theorem lsum_single (f : α → M →ₗ[R] N) (i : α) (m : M) :
finsupp.lsum f (finsupp.single i m) = f i m :=
finsupp.sum_single_index (f i).map_zero
section lmap_domain
variables {α' : Type*} {α'' : Type*} (M R)
def lmap_domain (f : α → α') : (α →₀ M) →ₗ[R] (α' →₀ M) :=
⟨map_domain f, assume a b, map_domain_add, map_domain_smul⟩
@[simp] theorem lmap_domain_apply (f : α → α') (l : α →₀ M) :
(lmap_domain M R f : (α →₀ M) →ₗ[R] (α' →₀ M)) l = map_domain f l := rfl
@[simp] theorem lmap_domain_id : (lmap_domain M R id : (α →₀ M) →ₗ[R] α →₀ M) = linear_map.id :=
linear_map.ext $ λ l, map_domain_id
theorem lmap_domain_comp (f : α → α') (g : α' → α'') :
lmap_domain M R (g ∘ f) = (lmap_domain M R g).comp (lmap_domain M R f) :=
linear_map.ext $ λ l, map_domain_comp
theorem supported_comap_lmap_domain (f : α → α') (s : set α') :
supported M R (f ⁻¹' s) ≤ (supported M R s).comap (lmap_domain M R f) :=
λ l (hl : ↑l.support ⊆ f ⁻¹' s),
show ↑(map_domain f l).support ⊆ s, begin
rw [← set.image_subset_iff, ← finset.coe_image] at hl,
exact set.subset.trans map_domain_support hl
end
theorem lmap_domain_supported [nonempty α] (f : α → α') (s : set α) :
(supported M R s).map (lmap_domain M R f) = supported M R (f '' s) :=
begin
inhabit α,
refine le_antisymm (map_le_iff_le_comap.2 $
le_trans (supported_mono $ set.subset_preimage_image _ _)
(supported_comap_lmap_domain _ _ _ _)) _,
intros l hl,
refine ⟨(lmap_domain M R (function.inv_fun_on f s) : (α' →₀ M) →ₗ α →₀ M) l, λ x hx, _, _⟩,
{ rcases finset.mem_image.1 (map_domain_support hx) with ⟨c, hc, rfl⟩,
exact function.inv_fun_on_mem (by simpa using hl hc) },
{ rw [← linear_map.comp_apply, ← lmap_domain_comp],
refine (map_domain_congr $ λ c hc, _).trans map_domain_id,
exact function.inv_fun_on_eq (by simpa using hl hc) }
end
theorem lmap_domain_disjoint_ker (f : α → α') {s : set α}
(H : ∀ a b ∈ s, f a = f b → a = b) :
disjoint (supported M R s) (lmap_domain M R f).ker :=
begin
rintro l ⟨h₁, h₂⟩,
rw [mem_coe, mem_ker, lmap_domain_apply, map_domain] at h₂,
simp, ext x,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases xs : x ∈ s,
{ have : finsupp.sum l (λ a, finsupp.single (f a)) (f x) = 0, {rw h₂, refl},
rw [finsupp.sum_apply, finsupp.sum, finset.sum_eq_single x] at this,
{ simpa [finsupp.single_apply] },
{ intros y hy xy, simp [mt (H _ _ (h₁ hy) xs) xy] },
{ simp {contextual := tt} } },
{ by_contra h, exact xs (h₁ $ finsupp.mem_support_iff.2 h) }
end
end lmap_domain
section total
variables (α) {α' : Type*} (M) {M' : Type*} (R)
[add_comm_group M'] [module R M']
(v : α → M) {v' : α' → M'}
/-- Interprets (l : α →₀ R) as linear combination of the elements in the family (v : α → M) and
evaluates this linear combination. -/
protected def total : (α →₀ R) →ₗ M := finsupp.lsum (λ i, linear_map.id.smul_right (v i))
variables {α M v}
theorem total_apply (l : α →₀ R) :
finsupp.total α M R v l = l.sum (λ i a, a • v i) := rfl
@[simp] theorem total_single (c : R) (a : α) :
finsupp.total α M R v (single a c) = c • (v a) :=
by simp [total_apply, sum_single_index]
theorem total_range (h : function.surjective v) : (finsupp.total α M R v).range = ⊤ :=
begin
apply range_eq_top.2,
intros x,
apply exists.elim (h x),
exact λ i hi, ⟨single i 1, by simp [hi]⟩
end
lemma range_total : (finsupp.total α M R v).range = span R (range v) :=
begin
ext x,
split,
{ intros hx,
rw [linear_map.mem_range] at hx,
rcases hx with ⟨l, hl⟩,
rw ← hl,
rw finsupp.total_apply,
unfold finsupp.sum,
apply sum_mem (span R (range v)),
exact λ i hi, submodule.smul_mem _ _ (subset_span (mem_range_self i)) },
{ apply span_le.2,
intros x hx,
rcases hx with ⟨i, hi⟩,
rw [mem_coe, linear_map.mem_range],
use finsupp.single i 1,
simp [hi] }
end
theorem lmap_domain_total (f : α → α') (g : M →ₗ[R] M') (h : ∀ i, g (v i) = v' (f i)) :
(finsupp.total α' M' R v').comp (lmap_domain R R f) = g.comp (finsupp.total α M R v) :=
by ext l; simp [total_apply, finsupp.sum_map_domain_index, add_smul, h]
theorem total_emb_domain (f : α ↪ α') (l : α →₀ R) :
(finsupp.total α' M' R v') (emb_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
by simp [total_apply, finsupp.sum, support_emb_domain, emb_domain_apply]
theorem total_map_domain (f : α → α') (hf : function.injective f) (l : α →₀ R) :
(finsupp.total α' M' R v') (map_domain f l) = (finsupp.total α M' R (v' ∘ f)) l :=
begin
have : map_domain f l = emb_domain ⟨f, hf⟩ l,
{ rw emb_domain_eq_map_domain ⟨f, hf⟩,
refl },
rw this,
apply total_emb_domain R ⟨f, hf⟩ l
end
theorem span_eq_map_total (s : set α):
span R (v '' s) = submodule.map (finsupp.total α M R v) (supported R R s) :=
begin
apply span_eq_of_le,
{ intros x hx,
rw set.mem_image at hx,
apply exists.elim hx,
intros i hi,
exact ⟨_, finsupp.single_mem_supported R 1 hi.1, by simp [hi.2]⟩ },
{ refine map_le_iff_le_comap.2 (λ z hz, _),
have : ∀i, z i • v i ∈ span R (v '' s),
{ intro c,
haveI := classical.dec_pred (λ x, x ∈ s),
by_cases c ∈ s,
{ exact smul_mem _ _ (subset_span (set.mem_image_of_mem _ h)) },
{ simp [(finsupp.mem_supported' R _).1 hz _ h] } },
refine sum_mem _ _, simp [this] }
end
theorem mem_span_iff_total {s : set α} {x : M} :
x ∈ span R (v '' s) ↔ ∃ l ∈ supported R R s, finsupp.total α M R v l = x :=
by rw span_eq_map_total; simp
variables (α) (M) (v)
protected def total_on (s : set α) : supported R R s →ₗ[R] span R (v '' s) :=
linear_map.cod_restrict _ ((finsupp.total _ _ _ v).comp (submodule.subtype (supported R R s))) $
λ ⟨l, hl⟩, (mem_span_iff_total _).2 ⟨l, hl, rfl⟩
variables {α} {M} {v}
theorem total_on_range (s : set α) : (finsupp.total_on α M R v s).range = ⊤ :=
by rw [finsupp.total_on, linear_map.range, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap,
range_subtype, map_top, linear_map.range_comp, range_subtype]; exact le_of_eq (span_eq_map_total _ _)
theorem total_comp (f : α' → α) :
(finsupp.total α' M R (v ∘ f)) = (finsupp.total α M R v).comp (lmap_domain R R f) :=
begin
ext l,
simp [total_apply],
rw sum_map_domain_index; simp [add_smul],
end
lemma total_comap_domain
(f : α → α') (l : α' →₀ R) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
finsupp.total α M R v (finsupp.comap_domain f l hf) =
(l.support.preimage f hf).sum (λ i, (l (f i)) • (v i)) :=
by rw finsupp.total_apply; refl
lemma total_on_finset
{s : finset α} {f : α → R} (g : α → M) (hf : ∀ a, f a ≠ 0 → a ∈ s):
finsupp.total α M R g (finsupp.on_finset s f hf) =
finset.sum s (λ (x : α), f x • g x) :=
begin
simp only [finsupp.total_apply, finsupp.sum, finsupp.on_finset_apply, finsupp.support_on_finset],
rw finset.sum_filter_of_ne,
intros x hx h,
contrapose! h,
simp [h],
end
end total
/-- An equivalence of domains induces a linear equivalence of finitely supported functions. -/
protected def dom_lcongr
{α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) :
(α₁ →₀ M) ≃ₗ[R] (α₂ →₀ M) :=
(finsupp.dom_congr e).to_linear_equiv
begin
change is_linear_map R (lmap_domain M R e : (α₁ →₀ M) →ₗ[R] (α₂ →₀ M)),
exact linear_map.is_linear _
end
@[simp] theorem dom_lcongr_single {α₁ : Type*} {α₂ : Type*} (e : α₁ ≃ α₂) (i : α₁) (m : M) :
(finsupp.dom_lcongr e : _ ≃ₗ[R] _) (finsupp.single i m) = finsupp.single (e i) m :=
by simp [finsupp.dom_lcongr, equiv.to_linear_equiv, finsupp.dom_congr, map_domain_single]
noncomputable def congr {α' : Type*} (s : set α) (t : set α') (e : s ≃ t) :
supported M R s ≃ₗ[R] supported M R t :=
begin
haveI := classical.dec_pred (λ x, x ∈ s),
haveI := classical.dec_pred (λ x, x ∈ t),
refine linear_equiv.trans (finsupp.supported_equiv_finsupp s)
(linear_equiv.trans _ (finsupp.supported_equiv_finsupp t).symm),
exact finsupp.dom_lcongr e
end
/-- An equivalence of domain and a linear equivalence of codomain induce a linear equivalence of the
corresponding finitely supported functions. -/
def lcongr {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N) : (ι →₀ M) ≃ₗ[R] (κ →₀ N) :=
(finsupp.dom_lcongr e₁).trans
{ to_fun := map_range e₂ e₂.map_zero,
inv_fun := map_range e₂.symm e₂.symm.map_zero,
left_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih,
by rw [map_range_add e₂.map_add, map_range_add e₂.symm.map_add,
map_range_single, map_range_single, e₂.symm_apply_apply, ih],
right_inv := λ f, finsupp.induction f (by simp_rw map_range_zero) $ λ a b f ha hb ih,
by rw [map_range_add e₂.symm.map_add, map_range_add e₂.map_add,
map_range_single, map_range_single, e₂.apply_symm_apply, ih],
map_add' := map_range_add e₂.map_add,
map_smul' := λ c f, finsupp.induction f
(by rw [smul_zero, map_range_zero, smul_zero]) $ λ a b f ha hb ih,
by rw [smul_add, smul_single, map_range_add e₂.map_add, map_range_single, e₂.map_smul, ih,
map_range_add e₂.map_add, smul_add, map_range_single, smul_single] }
@[simp] theorem lcongr_single {ι κ : Sort*} (e₁ : ι ≃ κ) (e₂ : M ≃ₗ[R] N)
(i : ι) (m : M) : lcongr e₁ e₂ (finsupp.single i m) = finsupp.single (e₁ i) (e₂ m) :=
by simp [lcongr]
end finsupp
variables {R : Type*} {M : Type*} {N : Type*}
variables [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N]
lemma linear_map.map_finsupp_total
(f : M →ₗ[R] N) {ι : Type*} {g : ι → M} (l : ι →₀ R) :
f (finsupp.total ι M R g l) = finsupp.total ι N R (f ∘ g) l :=
by simp only [finsupp.total_apply, finsupp.total_apply, finsupp.sum, f.map_sum, f.map_smul]
lemma submodule.exists_finset_of_mem_supr
{ι : Sort*} (p : ι → submodule R M) {m : M} (hm : m ∈ ⨆ i, p i) :
∃ s : finset ι, m ∈ ⨆ i ∈ s, p i :=
begin
obtain ⟨f, hf, rfl⟩ : ∃ f ∈ finsupp.supported R R (⋃ i, ↑(p i)), finsupp.total M M R id f = m,
{ have aux : (id : M → M) '' (⋃ (i : ι), ↑(p i)) = (⋃ (i : ι), ↑(p i)) := set.image_id _,
rwa [supr_eq_span, ← aux, finsupp.mem_span_iff_total R] at hm },
let t : finset M := f.support,
have ht : ∀ x : {x // x ∈ t}, ∃ i, ↑x ∈ p i,
{ intros x,
rw finsupp.mem_supported at hf,
specialize hf x.2,
rwa set.mem_Union at hf },
choose g hg using ht,
let s : finset ι := finset.univ.image g,
use s,
simp only [mem_supr, supr_le_iff],
assume N hN,
rw [finsupp.total_apply, finsupp.sum, ← submodule.mem_coe],
apply N.sum_mem,
assume x hx,
apply submodule.smul_mem,
let i : ι := g ⟨x, hx⟩,
have hi : i ∈ s, { rw finset.mem_image, exact ⟨⟨x, hx⟩, finset.mem_univ _, rfl⟩ },
exact hN i hi (hg _),
end
|
f17cf2a9c12c75cdebec6156b18c98d979a703b4 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/measure_theory/function/ae_eq_fun.lean | 9e969f4c8068e0d612562321bed687d51fd287a1 | [
"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 | 31,854 | lean | /-
Copyright (c) 2019 Johannes Hölzl, Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Zhouhang Zhou
-/
import measure_theory.integral.lebesgue
import order.filter.germ
import topology.continuous_function.algebra
import measure_theory.function.strongly_measurable.basic
/-!
# Almost everywhere equal functions
We build a space of equivalence classes of functions, where two functions are treated as identical
if they are almost everywhere equal. We form the set of equivalence classes under the relation of
being almost everywhere equal, which is sometimes known as the `L⁰` space.
To use this space as a basis for the `L^p` spaces and for the Bochner integral, we consider
equivalence classes of strongly measurable functions (or, equivalently, of almost everywhere
strongly measurable functions.)
See `l1_space.lean` for `L¹` space.
## Notation
* `α →ₘ[μ] β` is the type of `L⁰` space, where `α` is a measurable space, `β` is a topological
space, and `μ` is a measure on `α`. `f : α →ₘ β` is a "function" in `L⁰`.
In comments, `[f]` is also used to denote an `L⁰` function.
`ₘ` can be typed as `\_m`. Sometimes it is shown as a box if font is missing.
## Main statements
* The linear structure of `L⁰` :
Addition and scalar multiplication are defined on `L⁰` in the natural way, i.e.,
`[f] + [g] := [f + g]`, `c • [f] := [c • f]`. So defined, `α →ₘ β` inherits the linear structure
of `β`. For example, if `β` is a module, then `α →ₘ β` is a module over the same ring.
See `mk_add_mk`, `neg_mk`, `mk_sub_mk`, `smul_mk`,
`add_to_fun`, `neg_to_fun`, `sub_to_fun`, `smul_to_fun`
* The order structure of `L⁰` :
`≤` can be defined in a similar way: `[f] ≤ [g]` if `f a ≤ g a` for almost all `a` in domain.
And `α →ₘ β` inherits the preorder and partial order of `β`.
TODO: Define `sup` and `inf` on `L⁰` so that it forms a lattice. It seems that `β` must be a
linear order, since otherwise `f ⊔ g` may not be a measurable function.
## Implementation notes
* `f.to_fun` : To find a representative of `f : α →ₘ β`, use the coercion `(f : α → β)`, which
is implemented as `f.to_fun`.
For each operation `op` in `L⁰`, there is a lemma called `coe_fn_op`,
characterizing, say, `(f op g : α → β)`.
* `ae_eq_fun.mk` : To constructs an `L⁰` function `α →ₘ β` from an almost everywhere strongly
measurable function `f : α → β`, use `ae_eq_fun.mk`
* `comp` : Use `comp g f` to get `[g ∘ f]` from `g : β → γ` and `[f] : α →ₘ γ` when `g` is
continuous. Use `comp_measurable` if `g` is only measurable (this requires the
target space to be second countable).
* `comp₂` : Use `comp₂ g f₁ f₂ to get `[λ a, g (f₁ a) (f₂ a)]`.
For example, `[f + g]` is `comp₂ (+)`
## Tags
function space, almost everywhere equal, `L⁰`, ae_eq_fun
-/
noncomputable theory
open_locale classical ennreal topological_space
open set filter topological_space ennreal emetric measure_theory function
variables {α β γ δ : Type*} [measurable_space α] {μ ν : measure α}
namespace measure_theory
section measurable_space
variables [topological_space β]
variable (β)
/-- The equivalence relation of being almost everywhere equal for almost everywhere strongly
measurable functions. -/
def measure.ae_eq_setoid (μ : measure α) : setoid { f : α → β // ae_strongly_measurable f μ } :=
⟨λ f g, (f : α → β) =ᵐ[μ] g, λ f, ae_eq_refl f, λ f g, ae_eq_symm, λ f g h, ae_eq_trans⟩
variable (α)
/-- The space of equivalence classes of almost everywhere strongly measurable functions, where two
strongly measurable functions are equivalent if they agree almost everywhere, i.e.,
they differ on a set of measure `0`. -/
def ae_eq_fun (μ : measure α) : Type* := quotient (μ.ae_eq_setoid β)
variables {α β}
notation α ` →ₘ[`:25 μ `] ` β := ae_eq_fun α β μ
end measurable_space
namespace ae_eq_fun
variables [topological_space β] [topological_space γ] [topological_space δ]
/-- Construct the equivalence class `[f]` of an almost everywhere measurable function `f`, based
on the equivalence relation of being almost everywhere equal. -/
def mk {β : Type*} [topological_space β]
(f : α → β) (hf : ae_strongly_measurable f μ) : α →ₘ[μ] β := quotient.mk' ⟨f, hf⟩
/-- A measurable representative of an `ae_eq_fun` [f] -/
instance : has_coe_to_fun (α →ₘ[μ] β) (λ _, α → β) :=
⟨λ f, ae_strongly_measurable.mk _ (quotient.out' f : {f : α → β // ae_strongly_measurable f μ}).2⟩
protected lemma strongly_measurable (f : α →ₘ[μ] β) : strongly_measurable f :=
ae_strongly_measurable.strongly_measurable_mk _
protected lemma ae_strongly_measurable (f : α →ₘ[μ] β) : ae_strongly_measurable f μ :=
f.strongly_measurable.ae_strongly_measurable
protected lemma measurable [pseudo_metrizable_space β] [measurable_space β] [borel_space β]
(f : α →ₘ[μ] β) : measurable f :=
ae_strongly_measurable.measurable_mk _
protected lemma ae_measurable [pseudo_metrizable_space β] [measurable_space β] [borel_space β]
(f : α →ₘ[μ] β) :
ae_measurable f μ :=
f.measurable.ae_measurable
@[simp] lemma quot_mk_eq_mk (f : α → β) (hf) :
(quot.mk (@setoid.r _ $ μ.ae_eq_setoid β) ⟨f, hf⟩ : α →ₘ[μ] β) = mk f hf :=
rfl
@[simp] lemma mk_eq_mk {f g : α → β} {hf hg} :
(mk f hf : α →ₘ[μ] β) = mk g hg ↔ f =ᵐ[μ] g :=
quotient.eq'
@[simp] lemma mk_coe_fn (f : α →ₘ[μ] β) : mk f f.ae_strongly_measurable = f :=
begin
conv_rhs { rw ← quotient.out_eq' f },
set g : {f : α → β // ae_strongly_measurable f μ} := quotient.out' f with hg,
have : g = ⟨g.1, g.2⟩ := subtype.eq rfl,
rw [this, ← mk, mk_eq_mk],
exact (ae_strongly_measurable.ae_eq_mk _).symm,
end
@[ext] lemma ext {f g : α →ₘ[μ] β} (h : f =ᵐ[μ] g) : f = g :=
by rwa [← f.mk_coe_fn, ← g.mk_coe_fn, mk_eq_mk]
lemma ext_iff {f g : α →ₘ[μ] β} : f = g ↔ f =ᵐ[μ] g :=
⟨λ h, by rw h, λ h, ext h⟩
lemma coe_fn_mk (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β) =ᵐ[μ] f :=
begin
apply (ae_strongly_measurable.ae_eq_mk _).symm.trans,
exact @quotient.mk_out' _ (μ.ae_eq_setoid β) (⟨f, hf⟩ : {f // ae_strongly_measurable f μ})
end
@[elab_as_eliminator]
lemma induction_on (f : α →ₘ[μ] β) {p : (α →ₘ[μ] β) → Prop} (H : ∀ f hf, p (mk f hf)) : p f :=
quotient.induction_on' f $ subtype.forall.2 H
@[elab_as_eliminator]
lemma induction_on₂ {α' β' : Type*} [measurable_space α'] [topological_space β']
{μ' : measure α'}
(f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') {p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → Prop}
(H : ∀ f hf f' hf', p (mk f hf) (mk f' hf')) :
p f f' :=
induction_on f $ λ f hf, induction_on f' $ H f hf
@[elab_as_eliminator]
lemma induction_on₃ {α' β' : Type*} [measurable_space α'] [topological_space β']
{μ' : measure α'}
{α'' β'' : Type*} [measurable_space α''] [topological_space β'']
{μ'' : measure α''}
(f : α →ₘ[μ] β) (f' : α' →ₘ[μ'] β') (f'' : α'' →ₘ[μ''] β'')
{p : (α →ₘ[μ] β) → (α' →ₘ[μ'] β') → (α'' →ₘ[μ''] β'') → Prop}
(H : ∀ f hf f' hf' f'' hf'', p (mk f hf) (mk f' hf') (mk f'' hf'')) :
p f f' f'' :=
induction_on f $ λ f hf, induction_on₂ f' f'' $ H f hf
/-- Given a continuous function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`,
return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function
`[g ∘ f] : α →ₘ γ`. -/
def comp (g : β → γ) (hg : continuous g) (f : α →ₘ[μ] β) : α →ₘ[μ] γ :=
quotient.lift_on' f (λ f, mk (g ∘ (f : α → β)) (hg.comp_ae_strongly_measurable f.2)) $
λ f f' H, mk_eq_mk.2 $ H.fun_comp g
@[simp] lemma comp_mk (g : β → γ) (hg : continuous g)
(f : α → β) (hf) :
comp g hg (mk f hf : α →ₘ[μ] β) = mk (g ∘ f) (hg.comp_ae_strongly_measurable hf) :=
rfl
lemma comp_eq_mk (g : β → γ) (hg : continuous g) (f : α →ₘ[μ] β) :
comp g hg f = mk (g ∘ f) (hg.comp_ae_strongly_measurable f.ae_strongly_measurable) :=
by rw [← comp_mk g hg f f.ae_strongly_measurable, mk_coe_fn]
lemma coe_fn_comp (g : β → γ) (hg : continuous g) (f : α →ₘ[μ] β) :
comp g hg f =ᵐ[μ] g ∘ f :=
by { rw [comp_eq_mk], apply coe_fn_mk }
section comp_measurable
variables [measurable_space β] [pseudo_metrizable_space β] [borel_space β]
[measurable_space γ] [pseudo_metrizable_space γ] [opens_measurable_space γ]
[second_countable_topology γ]
/-- Given a measurable function `g : β → γ`, and an almost everywhere equal function `[f] : α →ₘ β`,
return the equivalence class of `g ∘ f`, i.e., the almost everywhere equal function
`[g ∘ f] : α →ₘ γ`. This requires that `γ` has a second countable topology. -/
def comp_measurable
(g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) : α →ₘ[μ] γ :=
quotient.lift_on' f (λ f', mk (g ∘ (f' : α → β))
(hg.comp_ae_measurable f'.2.ae_measurable).ae_strongly_measurable) $
λ f f' H, mk_eq_mk.2 $ H.fun_comp g
@[simp] lemma comp_measurable_mk (g : β → γ) (hg : measurable g)
(f : α → β) (hf : ae_strongly_measurable f μ) :
comp_measurable g hg (mk f hf : α →ₘ[μ] β) =
mk (g ∘ f) (hg.comp_ae_measurable hf.ae_measurable).ae_strongly_measurable :=
rfl
lemma comp_measurable_eq_mk (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
comp_measurable g hg f =
mk (g ∘ f) (hg.comp_ae_measurable f.ae_measurable).ae_strongly_measurable :=
by rw [← comp_measurable_mk g hg f f.ae_strongly_measurable, mk_coe_fn]
lemma coe_fn_comp_measurable (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
comp_measurable g hg f =ᵐ[μ] g ∘ f :=
by { rw [comp_measurable_eq_mk], apply coe_fn_mk }
end comp_measurable
/-- The class of `x ↦ (f x, g x)`. -/
def pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : α →ₘ[μ] β × γ :=
quotient.lift_on₂' f g (λ f g, mk (λ x, (f.1 x, g.1 x)) (f.2.prod_mk g.2)) $
λ f g f' g' Hf Hg, mk_eq_mk.2 $ Hf.prod_mk Hg
@[simp] lemma pair_mk_mk (f : α → β) (hf) (g : α → γ) (hg) :
(mk f hf : α →ₘ[μ] β).pair (mk g hg) = mk (λ x, (f x, g x)) (hf.prod_mk hg) :=
rfl
lemma pair_eq_mk (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) :
f.pair g = mk (λ x, (f x, g x)) (f.ae_strongly_measurable.prod_mk g.ae_strongly_measurable) :=
by simp only [← pair_mk_mk, mk_coe_fn]
lemma coe_fn_pair (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) :
f.pair g =ᵐ[μ] (λ x, (f x, g x)) :=
by { rw pair_eq_mk, apply coe_fn_mk }
/-- Given a continuous function `g : β → γ → δ`, and almost everywhere equal functions
`[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function
`λ a, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function
`[λ a, g (f₁ a) (f₂ a)] : α →ₘ γ` -/
def comp₂ (g : β → γ → δ)
(hg : continuous (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : α →ₘ[μ] δ :=
comp _ hg (f₁.pair f₂)
@[simp] lemma comp₂_mk_mk
(g : β → γ → δ) (hg : continuous (uncurry g)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) :
comp₂ g hg (mk f₁ hf₁ : α →ₘ[μ] β) (mk f₂ hf₂) =
mk (λ a, g (f₁ a) (f₂ a)) (hg.comp_ae_strongly_measurable (hf₁.prod_mk hf₂)) :=
rfl
lemma comp₂_eq_pair
(g : β → γ → δ) (hg : continuous (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ = comp _ hg (f₁.pair f₂) :=
rfl
lemma comp₂_eq_mk
(g : β → γ → δ) (hg : continuous (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ = mk (λ a, g (f₁ a) (f₂ a)) (hg.comp_ae_strongly_measurable
(f₁.ae_strongly_measurable.prod_mk f₂.ae_strongly_measurable)) :=
by rw [comp₂_eq_pair, pair_eq_mk, comp_mk]; refl
lemma coe_fn_comp₂
(g : β → γ → δ) (hg : continuous (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂ g hg f₁ f₂ =ᵐ[μ] λ a, g (f₁ a) (f₂ a) :=
by { rw comp₂_eq_mk, apply coe_fn_mk }
section
variables
[measurable_space β] [pseudo_metrizable_space β] [borel_space β] [second_countable_topology β]
[measurable_space γ] [pseudo_metrizable_space γ] [borel_space γ] [second_countable_topology γ]
[measurable_space δ] [pseudo_metrizable_space δ] [opens_measurable_space δ]
[second_countable_topology δ]
/-- Given a measurable function `g : β → γ → δ`, and almost everywhere equal functions
`[f₁] : α →ₘ β` and `[f₂] : α →ₘ γ`, return the equivalence class of the function
`λ a, g (f₁ a) (f₂ a)`, i.e., the almost everywhere equal function
`[λ a, g (f₁ a) (f₂ a)] : α →ₘ γ`. This requires `δ` to have second-countable topology. -/
def comp₂_measurable (g : β → γ → δ)
(hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) : α →ₘ[μ] δ :=
comp_measurable _ hg (f₁.pair f₂)
@[simp] lemma comp₂_measurable_mk_mk
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α → β) (f₂ : α → γ) (hf₁ hf₂) :
comp₂_measurable g hg (mk f₁ hf₁ : α →ₘ[μ] β) (mk f₂ hf₂) =
mk (λ a, g (f₁ a) (f₂ a))
(hg.comp_ae_measurable (hf₁.ae_measurable.prod_mk hf₂.ae_measurable)).ae_strongly_measurable :=
rfl
lemma comp₂_measurable_eq_pair
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂_measurable g hg f₁ f₂ = comp_measurable _ hg (f₁.pair f₂) :=
rfl
lemma comp₂_measurable_eq_mk
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂_measurable g hg f₁ f₂ = mk (λ a, g (f₁ a) (f₂ a)) (hg.comp_ae_measurable
(f₁.ae_measurable.prod_mk f₂.ae_measurable)).ae_strongly_measurable :=
by rw [comp₂_measurable_eq_pair, pair_eq_mk, comp_measurable_mk]; refl
lemma coe_fn_comp₂_measurable
(g : β → γ → δ) (hg : measurable (uncurry g)) (f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
comp₂_measurable g hg f₁ f₂ =ᵐ[μ] λ a, g (f₁ a) (f₂ a) :=
by { rw comp₂_measurable_eq_mk, apply coe_fn_mk }
end
/-- Interpret `f : α →ₘ[μ] β` as a germ at `μ.ae` forgetting that `f` is almost everywhere
strongly measurable. -/
def to_germ (f : α →ₘ[μ] β) : germ μ.ae β :=
quotient.lift_on' f (λ f, ((f : α → β) : germ μ.ae β)) $ λ f g H, germ.coe_eq.2 H
@[simp] lemma mk_to_germ (f : α → β) (hf) : (mk f hf : α →ₘ[μ] β).to_germ = f := rfl
lemma to_germ_eq (f : α →ₘ[μ] β) : f.to_germ = (f : α → β) :=
by rw [← mk_to_germ, mk_coe_fn]
lemma to_germ_injective : injective (to_germ : (α →ₘ[μ] β) → germ μ.ae β) :=
λ f g H, ext $ germ.coe_eq.1 $ by rwa [← to_germ_eq, ← to_germ_eq]
lemma comp_to_germ (g : β → γ) (hg : continuous g) (f : α →ₘ[μ] β) :
(comp g hg f).to_germ = f.to_germ.map g :=
induction_on f $ λ f hf, by simp
lemma comp_measurable_to_germ [measurable_space β] [borel_space β] [pseudo_metrizable_space β]
[pseudo_metrizable_space γ] [second_countable_topology γ] [measurable_space γ]
[opens_measurable_space γ] (g : β → γ) (hg : measurable g) (f : α →ₘ[μ] β) :
(comp_measurable g hg f).to_germ = f.to_germ.map g :=
induction_on f $ λ f hf, by simp
lemma comp₂_to_germ (g : β → γ → δ) (hg : continuous (uncurry g))
(f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
(comp₂ g hg f₁ f₂).to_germ = f₁.to_germ.map₂ g f₂.to_germ :=
induction_on₂ f₁ f₂ $ λ f₁ hf₁ f₂ hf₂, by simp
lemma comp₂_measurable_to_germ
[pseudo_metrizable_space β] [second_countable_topology β] [measurable_space β] [borel_space β]
[pseudo_metrizable_space γ] [second_countable_topology γ] [measurable_space γ] [borel_space γ]
[pseudo_metrizable_space δ] [second_countable_topology δ] [measurable_space δ]
[opens_measurable_space δ] (g : β → γ → δ) (hg : measurable (uncurry g))
(f₁ : α →ₘ[μ] β) (f₂ : α →ₘ[μ] γ) :
(comp₂_measurable g hg f₁ f₂).to_germ = f₁.to_germ.map₂ g f₂.to_germ :=
induction_on₂ f₁ f₂ $ λ f₁ hf₁ f₂ hf₂, by simp
/-- Given a predicate `p` and an equivalence class `[f]`, return true if `p` holds of `f a`
for almost all `a` -/
def lift_pred (p : β → Prop) (f : α →ₘ[μ] β) : Prop := f.to_germ.lift_pred p
/-- Given a relation `r` and equivalence class `[f]` and `[g]`, return true if `r` holds of
`(f a, g a)` for almost all `a` -/
def lift_rel (r : β → γ → Prop) (f : α →ₘ[μ] β) (g : α →ₘ[μ] γ) : Prop :=
f.to_germ.lift_rel r g.to_germ
lemma lift_rel_mk_mk {r : β → γ → Prop} {f : α → β} {g : α → γ} {hf hg} :
lift_rel r (mk f hf : α →ₘ[μ] β) (mk g hg) ↔ ∀ᵐ a ∂μ, r (f a) (g a) :=
iff.rfl
lemma lift_rel_iff_coe_fn {r : β → γ → Prop} {f : α →ₘ[μ] β} {g : α →ₘ[μ] γ} :
lift_rel r f g ↔ ∀ᵐ a ∂μ, r (f a) (g a) :=
by rw [← lift_rel_mk_mk, mk_coe_fn, mk_coe_fn]
section order
instance [preorder β] : preorder (α →ₘ[μ] β) := preorder.lift to_germ
@[simp] lemma mk_le_mk [preorder β] {f g : α → β} (hf hg) :
(mk f hf : α →ₘ[μ] β) ≤ mk g hg ↔ f ≤ᵐ[μ] g :=
iff.rfl
@[simp, norm_cast] lemma coe_fn_le [preorder β] {f g : α →ₘ[μ] β} :
(f : α → β) ≤ᵐ[μ] g ↔ f ≤ g :=
lift_rel_iff_coe_fn.symm
instance [partial_order β] : partial_order (α →ₘ[μ] β) :=
partial_order.lift to_germ to_germ_injective
section lattice
section sup
variables [semilattice_sup β] [has_continuous_sup β]
instance : has_sup (α →ₘ[μ] β) :=
{ sup := λ f g, ae_eq_fun.comp₂ (⊔) continuous_sup f g }
lemma coe_fn_sup (f g : α →ₘ[μ] β) : ⇑(f ⊔ g) =ᵐ[μ] λ x, f x ⊔ g x :=
coe_fn_comp₂ _ _ _ _
protected lemma le_sup_left (f g : α →ₘ[μ] β) : f ≤ f ⊔ g :=
by { rw ← coe_fn_le, filter_upwards [coe_fn_sup f g] with _ ha, rw ha, exact le_sup_left, }
protected lemma le_sup_right (f g : α →ₘ[μ] β) : g ≤ f ⊔ g :=
by { rw ← coe_fn_le, filter_upwards [coe_fn_sup f g] with _ ha, rw ha, exact le_sup_right, }
protected lemma sup_le (f g f' : α →ₘ[μ] β) (hf : f ≤ f') (hg : g ≤ f') : f ⊔ g ≤ f' :=
begin
rw ← coe_fn_le at hf hg ⊢,
filter_upwards [hf, hg, coe_fn_sup f g] with _ haf hag ha_sup,
rw ha_sup,
exact sup_le haf hag,
end
end sup
section inf
variables [semilattice_inf β] [has_continuous_inf β]
instance : has_inf (α →ₘ[μ] β) :=
{ inf := λ f g, ae_eq_fun.comp₂ (⊓) continuous_inf f g }
lemma coe_fn_inf (f g : α →ₘ[μ] β) : ⇑(f ⊓ g) =ᵐ[μ] λ x, f x ⊓ g x :=
coe_fn_comp₂ _ _ _ _
protected lemma inf_le_left (f g : α →ₘ[μ] β) : f ⊓ g ≤ f :=
by { rw ← coe_fn_le, filter_upwards [coe_fn_inf f g] with _ ha, rw ha, exact inf_le_left, }
protected lemma inf_le_right (f g : α →ₘ[μ] β) : f ⊓ g ≤ g :=
by { rw ← coe_fn_le, filter_upwards [coe_fn_inf f g] with _ ha, rw ha, exact inf_le_right, }
protected lemma le_inf (f' f g : α →ₘ[μ] β) (hf : f' ≤ f) (hg : f' ≤ g) : f' ≤ f ⊓ g :=
begin
rw ← coe_fn_le at hf hg ⊢,
filter_upwards [hf, hg, coe_fn_inf f g] with _ haf hag ha_inf,
rw ha_inf,
exact le_inf haf hag,
end
end inf
instance [lattice β] [topological_lattice β] : lattice (α →ₘ[μ] β) :=
{ sup := has_sup.sup,
le_sup_left := ae_eq_fun.le_sup_left,
le_sup_right := ae_eq_fun.le_sup_right,
sup_le := ae_eq_fun.sup_le,
inf := has_inf.inf,
inf_le_left := ae_eq_fun.inf_le_left,
inf_le_right := ae_eq_fun.inf_le_right,
le_inf := ae_eq_fun.le_inf,
..ae_eq_fun.partial_order}
end lattice
end order
variable (α)
/-- The equivalence class of a constant function: `[λ a:α, b]`, based on the equivalence relation of
being almost everywhere equal -/
def const (b : β) : α →ₘ[μ] β := mk (λ a:α, b) ae_strongly_measurable_const
lemma coe_fn_const (b : β) : (const α b : α →ₘ[μ] β) =ᵐ[μ] function.const α b :=
coe_fn_mk _ _
variable {α}
instance [inhabited β] : inhabited (α →ₘ[μ] β) := ⟨const α default⟩
@[to_additive] instance [has_one β] : has_one (α →ₘ[μ] β) := ⟨const α 1⟩
@[to_additive] lemma one_def [has_one β] :
(1 : α →ₘ[μ] β) = mk (λ a:α, 1) ae_strongly_measurable_const := rfl
@[to_additive] lemma coe_fn_one [has_one β] : ⇑(1 : α →ₘ[μ] β) =ᵐ[μ] 1 := coe_fn_const _ _
@[simp, to_additive] lemma one_to_germ [has_one β] : (1 : α →ₘ[μ] β).to_germ = 1 := rfl
-- Note we set up the scalar actions before the `monoid` structures in case we want to
-- try to override the `nsmul` or `zsmul` fields in future.
section has_smul
variables {𝕜 𝕜' : Type*}
variables [has_smul 𝕜 γ] [has_continuous_const_smul 𝕜 γ]
variables [has_smul 𝕜' γ] [has_continuous_const_smul 𝕜' γ]
instance : has_smul 𝕜 (α →ₘ[μ] γ) :=
⟨λ c f, comp ((•) c) (continuous_id.const_smul c) f⟩
@[simp] lemma smul_mk (c : 𝕜) (f : α → γ) (hf : ae_strongly_measurable f μ) :
c • (mk f hf : α →ₘ[μ] γ) = mk (c • f) (hf.const_smul _) :=
rfl
lemma coe_fn_smul (c : 𝕜) (f : α →ₘ[μ] γ) : ⇑(c • f) =ᵐ[μ] c • f := coe_fn_comp _ _ _
lemma smul_to_germ (c : 𝕜) (f : α →ₘ[μ] γ) : (c • f).to_germ = c • f.to_germ :=
comp_to_germ _ _ _
instance [smul_comm_class 𝕜 𝕜' γ] : smul_comm_class 𝕜 𝕜' (α →ₘ[μ] γ) :=
⟨λ a b f, induction_on f $ λ f hf, by simp_rw [smul_mk, smul_comm]⟩
instance [has_smul 𝕜 𝕜'] [is_scalar_tower 𝕜 𝕜' γ] : is_scalar_tower 𝕜 𝕜' (α →ₘ[μ] γ) :=
⟨λ a b f, induction_on f $ λ f hf, by simp_rw [smul_mk, smul_assoc]⟩
instance [has_smul 𝕜ᵐᵒᵖ γ] [is_central_scalar 𝕜 γ] : is_central_scalar 𝕜 (α →ₘ[μ] γ) :=
⟨λ a f, induction_on f $ λ f hf, by simp_rw [smul_mk, op_smul_eq_smul]⟩
end has_smul
section has_mul
variables [has_mul γ] [has_continuous_mul γ]
@[to_additive]
instance : has_mul (α →ₘ[μ] γ) := ⟨comp₂ (*) continuous_mul⟩
@[simp, to_additive] lemma mk_mul_mk (f g : α → γ) (hf : ae_strongly_measurable f μ)
(hg : ae_strongly_measurable g μ) :
(mk f hf : α →ₘ[μ] γ) * (mk g hg) = mk (f * g) (hf.mul hg) :=
rfl
@[to_additive] lemma coe_fn_mul (f g : α →ₘ[μ] γ) : ⇑(f * g) =ᵐ[μ] f * g := coe_fn_comp₂ _ _ _ _
@[simp, to_additive] lemma mul_to_germ (f g : α →ₘ[μ] γ) :
(f * g).to_germ = f.to_germ * g.to_germ :=
comp₂_to_germ _ _ _ _
end has_mul
instance [add_monoid γ] [has_continuous_add γ] : add_monoid (α →ₘ[μ] γ) :=
to_germ_injective.add_monoid to_germ zero_to_germ add_to_germ (λ _ _, smul_to_germ _ _)
instance [add_comm_monoid γ] [has_continuous_add γ] : add_comm_monoid (α →ₘ[μ] γ) :=
to_germ_injective.add_comm_monoid to_germ zero_to_germ add_to_germ (λ _ _, smul_to_germ _ _)
section monoid
variables [monoid γ] [has_continuous_mul γ]
instance : has_pow (α →ₘ[μ] γ) ℕ := ⟨λ f n, comp _ (continuous_pow n) f⟩
@[simp] lemma mk_pow (f : α → γ) (hf) (n : ℕ) :
(mk f hf : α →ₘ[μ] γ) ^ n =
mk (f ^ n) ((_root_.continuous_pow n).comp_ae_strongly_measurable hf) :=
rfl
lemma coe_fn_pow (f : α →ₘ[μ] γ) (n : ℕ) : ⇑(f ^ n) =ᵐ[μ] f ^ n :=
coe_fn_comp _ _ _
@[simp] lemma pow_to_germ (f : α →ₘ[μ] γ) (n : ℕ) :
(f ^ n).to_germ = f.to_germ ^ n :=
comp_to_germ _ _ _
@[to_additive]
instance : monoid (α →ₘ[μ] γ) :=
to_germ_injective.monoid to_germ one_to_germ mul_to_germ pow_to_germ
/-- `ae_eq_fun.to_germ` as a `monoid_hom`. -/
@[to_additive "`ae_eq_fun.to_germ` as an `add_monoid_hom`.", simps]
def to_germ_monoid_hom : (α →ₘ[μ] γ) →* μ.ae.germ γ :=
{ to_fun := to_germ,
map_one' := one_to_germ,
map_mul' := mul_to_germ }
end monoid
@[to_additive]
instance [comm_monoid γ] [has_continuous_mul γ] : comm_monoid (α →ₘ[μ] γ) :=
to_germ_injective.comm_monoid to_germ one_to_germ mul_to_germ pow_to_germ
section group
variables [group γ] [topological_group γ]
section inv
@[to_additive] instance : has_inv (α →ₘ[μ] γ) := ⟨comp has_inv.inv continuous_inv⟩
@[simp, to_additive] lemma inv_mk (f : α → γ) (hf) : (mk f hf : α →ₘ[μ] γ)⁻¹ = mk f⁻¹ hf.inv := rfl
@[to_additive] lemma coe_fn_inv (f : α →ₘ[μ] γ) : ⇑(f⁻¹) =ᵐ[μ] f⁻¹ := coe_fn_comp _ _ _
@[to_additive] lemma inv_to_germ (f : α →ₘ[μ] γ) : (f⁻¹).to_germ = f.to_germ⁻¹ := comp_to_germ _ _ _
end inv
section div
@[to_additive] instance : has_div (α →ₘ[μ] γ) := ⟨comp₂ has_div.div continuous_div'⟩
@[simp, to_additive] lemma mk_div (f g : α → γ)
(hf : ae_strongly_measurable f μ) (hg : ae_strongly_measurable g μ) :
mk (f / g) (hf.div hg) = (mk f hf : α →ₘ[μ] γ) / (mk g hg) :=
rfl
@[to_additive] lemma coe_fn_div (f g : α →ₘ[μ] γ) : ⇑(f / g) =ᵐ[μ] f / g := coe_fn_comp₂ _ _ _ _
@[to_additive] lemma div_to_germ (f g : α →ₘ[μ] γ) : (f / g).to_germ = f.to_germ / g.to_germ :=
comp₂_to_germ _ _ _ _
end div
section zpow
instance has_int_pow : has_pow (α →ₘ[μ] γ) ℤ :=
⟨λ f n, comp _ (continuous_zpow n) f⟩
@[simp] lemma mk_zpow (f : α → γ) (hf) (n : ℤ) :
(mk f hf : α →ₘ[μ] γ) ^ n = mk (f ^ n) ((continuous_zpow n).comp_ae_strongly_measurable hf) :=
rfl
lemma coe_fn_zpow (f : α →ₘ[μ] γ) (n : ℤ) : ⇑(f ^ n) =ᵐ[μ] f ^ n :=
coe_fn_comp _ _ _
@[simp] lemma zpow_to_germ (f : α →ₘ[μ] γ) (n : ℤ) :
(f ^ n).to_germ = f.to_germ ^ n :=
comp_to_germ _ _ _
end zpow
end group
instance [add_group γ] [topological_add_group γ] :
add_group (α →ₘ[μ] γ) :=
to_germ_injective.add_group to_germ zero_to_germ add_to_germ neg_to_germ sub_to_germ
(λ _ _, smul_to_germ _ _) (λ _ _, smul_to_germ _ _)
instance [add_comm_group γ] [topological_add_group γ] :
add_comm_group (α →ₘ[μ] γ) :=
to_germ_injective.add_comm_group to_germ zero_to_germ add_to_germ neg_to_germ sub_to_germ
(λ _ _, smul_to_germ _ _) (λ _ _, smul_to_germ _ _)
@[to_additive]
instance [group γ] [topological_group γ] : group (α →ₘ[μ] γ) :=
to_germ_injective.group _ one_to_germ mul_to_germ inv_to_germ div_to_germ pow_to_germ zpow_to_germ
@[to_additive]
instance [comm_group γ] [topological_group γ] : comm_group (α →ₘ[μ] γ) :=
to_germ_injective.comm_group _
one_to_germ mul_to_germ inv_to_germ div_to_germ pow_to_germ zpow_to_germ
section module
variables {𝕜 : Type*}
instance [monoid 𝕜] [mul_action 𝕜 γ] [has_continuous_const_smul 𝕜 γ] :
mul_action 𝕜 (α →ₘ[μ] γ) :=
to_germ_injective.mul_action to_germ smul_to_germ
instance [monoid 𝕜] [add_monoid γ] [has_continuous_add γ]
[distrib_mul_action 𝕜 γ] [has_continuous_const_smul 𝕜 γ] :
distrib_mul_action 𝕜 (α →ₘ[μ] γ) :=
to_germ_injective.distrib_mul_action (to_germ_add_monoid_hom : (α →ₘ[μ] γ) →+ _)
(λ c : 𝕜, smul_to_germ c)
instance [semiring 𝕜] [add_comm_monoid γ] [has_continuous_add γ] [module 𝕜 γ]
[has_continuous_const_smul 𝕜 γ] :
module 𝕜 (α →ₘ[μ] γ) :=
to_germ_injective.module 𝕜 (to_germ_add_monoid_hom : (α →ₘ[μ] γ) →+ _) smul_to_germ
end module
open ennreal
/-- For `f : α → ℝ≥0∞`, define `∫ [f]` to be `∫ f` -/
def lintegral (f : α →ₘ[μ] ℝ≥0∞) : ℝ≥0∞ :=
quotient.lift_on' f (λ f, ∫⁻ a, (f : α → ℝ≥0∞) a ∂μ) (assume f g, lintegral_congr_ae)
@[simp] lemma lintegral_mk (f : α → ℝ≥0∞) (hf) :
(mk f hf : α →ₘ[μ] ℝ≥0∞).lintegral = ∫⁻ a, f a ∂μ := rfl
lemma lintegral_coe_fn (f : α →ₘ[μ] ℝ≥0∞) : ∫⁻ a, f a ∂μ = f.lintegral :=
by rw [← lintegral_mk, mk_coe_fn]
@[simp] lemma lintegral_zero : lintegral (0 : α →ₘ[μ] ℝ≥0∞) = 0 := lintegral_zero
@[simp] lemma lintegral_eq_zero_iff {f : α →ₘ[μ] ℝ≥0∞} : lintegral f = 0 ↔ f = 0 :=
induction_on f $ λ f hf, (lintegral_eq_zero_iff' hf.ae_measurable).trans mk_eq_mk.symm
lemma lintegral_add (f g : α →ₘ[μ] ℝ≥0∞) : lintegral (f + g) = lintegral f + lintegral g :=
induction_on₂ f g $ λ f hf g hg, by simp [lintegral_add_left' hf.ae_measurable]
lemma lintegral_mono {f g : α →ₘ[μ] ℝ≥0∞} : f ≤ g → lintegral f ≤ lintegral g :=
induction_on₂ f g $ λ f hf g hg hfg, lintegral_mono_ae hfg
section abs
lemma coe_fn_abs {β} [topological_space β] [lattice β] [topological_lattice β]
[add_group β] [topological_add_group β]
(f : α →ₘ[μ] β) :
⇑|f| =ᵐ[μ] λ x, |f x| :=
begin
simp_rw abs_eq_sup_neg,
filter_upwards [ae_eq_fun.coe_fn_sup f (-f), ae_eq_fun.coe_fn_neg f] with x hx_sup hx_neg,
rw [hx_sup, hx_neg, pi.neg_apply],
end
end abs
section pos_part
variables [linear_order γ] [order_closed_topology γ] [has_zero γ]
/-- Positive part of an `ae_eq_fun`. -/
def pos_part (f : α →ₘ[μ] γ) : α →ₘ[μ] γ :=
comp (λ x, max x 0) (continuous_id.max continuous_const) f
@[simp] lemma pos_part_mk (f : α → γ) (hf) :
pos_part (mk f hf : α →ₘ[μ] γ) =
mk (λ x, max (f x) 0) ((continuous_id.max continuous_const).comp_ae_strongly_measurable hf) :=
rfl
lemma coe_fn_pos_part (f : α →ₘ[μ] γ) : ⇑(pos_part f) =ᵐ[μ] (λ a, max (f a) 0) :=
coe_fn_comp _ _ _
end pos_part
end ae_eq_fun
end measure_theory
namespace continuous_map
open measure_theory
variables [topological_space α] [borel_space α] (μ)
variables [topological_space β] [second_countable_topology_either α β] [pseudo_metrizable_space β]
/-- The equivalence class of `μ`-almost-everywhere measurable functions associated to a continuous
map. -/
def to_ae_eq_fun (f : C(α, β)) : α →ₘ[μ] β :=
ae_eq_fun.mk f f.continuous.ae_strongly_measurable
lemma coe_fn_to_ae_eq_fun (f : C(α, β)) : f.to_ae_eq_fun μ =ᵐ[μ] f :=
ae_eq_fun.coe_fn_mk f _
variables [group β] [topological_group β]
/-- The `mul_hom` from the group of continuous maps from `α` to `β` to the group of equivalence
classes of `μ`-almost-everywhere measurable functions. -/
@[to_additive "The `add_hom` from the group of continuous maps from `α` to `β` to the group of
equivalence classes of `μ`-almost-everywhere measurable functions."]
def to_ae_eq_fun_mul_hom : C(α, β) →* α →ₘ[μ] β :=
{ to_fun := continuous_map.to_ae_eq_fun μ,
map_one' := rfl,
map_mul' := λ f g, ae_eq_fun.mk_mul_mk _ _
f.continuous.ae_strongly_measurable g.continuous.ae_strongly_measurable }
variables {𝕜 : Type*} [semiring 𝕜]
variables [topological_space γ] [pseudo_metrizable_space γ] [add_comm_group γ]
[module 𝕜 γ] [topological_add_group γ] [has_continuous_const_smul 𝕜 γ]
[second_countable_topology_either α γ]
/-- The linear map from the group of continuous maps from `α` to `β` to the group of equivalence
classes of `μ`-almost-everywhere measurable functions. -/
def to_ae_eq_fun_linear_map : C(α, γ) →ₗ[𝕜] α →ₘ[μ] γ :=
{ map_smul' := λ c f, ae_eq_fun.smul_mk c f f.continuous.ae_strongly_measurable,
.. to_ae_eq_fun_add_hom μ }
end continuous_map
-- Guard against import creep
assert_not_exists inner_product_space
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.