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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
70ac6ff53e55a240dd8d2559468315f0e79e2bb3 | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /tests/lean/run/proofIrrelFVar.lean | 36b74fefcb30dcc1915ef425ad4e51920c4ba1e5 | [
"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 | 170 | lean |
universes u
variable {α : Type u} {p : α → Prop}
theorem ex (a : α) (h1 h2 : p a) (h : Subtype.mk a h1 = Subtype.mk a h1) : Subtype.mk a h1 = Subtype.mk a h2 :=
h
|
292c9973b7ef038b0609b41b7bc064677f37b9d4 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/topology/sets/closeds.lean | 53ddad5525cad55ef8376041c7eef57680b81b9f | [
"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 | 5,276 | 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, Yaël Dillies
-/
import topology.sets.opens
/-!
# Closed sets
We define a few types of closed sets in a topological space.
## Main Definitions
For a topological space `α`,
* `closeds α`: The type of closed sets.
* `clopens α`: The type of clopen sets.
-/
open set
variables {ι α β : Type*} [topological_space α] [topological_space β]
namespace topological_space
/-! ### Closed sets -/
/-- The type of closed subsets of a topological space. -/
structure closeds (α : Type*) [topological_space α] :=
(carrier : set α)
(closed' : is_closed carrier)
namespace closeds
variables {α}
instance : set_like (closeds α) α :=
{ coe := closeds.carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
lemma closed (s : closeds α) : is_closed (s : set α) := s.closed'
@[ext] protected lemma ext {s t : closeds α} (h : (s : set α) = t) : s = t := set_like.ext' h
@[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl
instance : has_sup (closeds α) := ⟨λ s t, ⟨s ∪ t, s.closed.union t.closed⟩⟩
instance : has_inf (closeds α) := ⟨λ s t, ⟨s ∩ t, s.closed.inter t.closed⟩⟩
instance : has_top (closeds α) := ⟨⟨univ, is_closed_univ⟩⟩
instance : has_bot (closeds α) := ⟨⟨∅, is_closed_empty⟩⟩
instance : distrib_lattice (closeds α) :=
set_like.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl)
instance : bounded_order (closeds α) := bounded_order.lift (coe : _ → set α) (λ _ _, id) rfl rfl
/-- The type of closed sets is inhabited, with default element the empty set. -/
instance : inhabited (closeds α) := ⟨⊥⟩
@[simp, norm_cast] lemma coe_sup (s t : closeds α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp, norm_cast] lemma coe_inf (s t : closeds α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp, norm_cast] lemma coe_top : (↑(⊤ : closeds α) : set α) = univ := rfl
@[simp, norm_cast] lemma coe_bot : (↑(⊥ : closeds α) : set α) = ∅ := rfl
@[simp, norm_cast] lemma coe_finset_sup (f : ι → closeds α) (s : finset ι) :
(↑(s.sup f) : set α) = s.sup (coe ∘ f) :=
map_finset_sup (⟨⟨coe, coe_sup⟩, coe_bot⟩ : sup_bot_hom (closeds α) (set α)) _ _
@[simp, norm_cast] lemma coe_finset_inf (f : ι → closeds α) (s : finset ι) :
(↑(s.inf f) : set α) = s.inf (coe ∘ f) :=
map_finset_inf (⟨⟨coe, coe_inf⟩, coe_top⟩ : inf_top_hom (closeds α) (set α)) _ _
end closeds
/-- The complement of a closed set as an open set. -/
@[simps] def closeds.compl (s : closeds α) : opens α := ⟨sᶜ, s.2.is_open_compl⟩
/-- The complement of an open set as a closed set. -/
@[simps] def opens.compl (s : opens α) : closeds α := ⟨sᶜ, s.2.is_closed_compl⟩
lemma closeds.compl_compl (s : closeds α) : s.compl.compl = s := closeds.ext (compl_compl s)
lemma opens.compl_compl (s : opens α) : s.compl.compl = s := opens.ext (compl_compl s)
lemma closeds.compl_bijective : function.bijective (@closeds.compl α _) :=
function.bijective_iff_has_inverse.mpr ⟨opens.compl, closeds.compl_compl, opens.compl_compl⟩
lemma opens.compl_bijective : function.bijective (@opens.compl α _) :=
function.bijective_iff_has_inverse.mpr ⟨closeds.compl, opens.compl_compl, closeds.compl_compl⟩
/-! ### Clopen sets -/
/-- The type of clopen sets of a topological space. -/
structure clopens (α : Type*) [topological_space α] :=
(carrier : set α)
(clopen' : is_clopen carrier)
namespace clopens
instance : set_like (clopens α) α :=
{ coe := λ s, s.carrier,
coe_injective' := λ s t h, by { cases s, cases t, congr' } }
lemma clopen (s : clopens α) : is_clopen (s : set α) := s.clopen'
/-- Reinterpret a compact open as an open. -/
@[simps] def to_opens (s : clopens α) : opens α := ⟨s, s.clopen.is_open⟩
@[ext] protected lemma ext {s t : clopens α} (h : (s : set α) = t) : s = t := set_like.ext' h
@[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl
instance : has_sup (clopens α) := ⟨λ s t, ⟨s ∪ t, s.clopen.union t.clopen⟩⟩
instance : has_inf (clopens α) := ⟨λ s t, ⟨s ∩ t, s.clopen.inter t.clopen⟩⟩
instance : has_top (clopens α) := ⟨⟨⊤, is_clopen_univ⟩⟩
instance : has_bot (clopens α) := ⟨⟨⊥, is_clopen_empty⟩⟩
instance : has_sdiff (clopens α) := ⟨λ s t, ⟨s \ t, s.clopen.diff t.clopen⟩⟩
instance : has_compl (clopens α) := ⟨λ s, ⟨sᶜ, s.clopen.compl⟩⟩
instance : boolean_algebra (clopens α) :=
set_like.coe_injective.boolean_algebra _ (λ _ _, rfl) (λ _ _, rfl) rfl rfl (λ _, rfl) (λ _ _, rfl)
@[simp] lemma coe_sup (s t : clopens α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl
@[simp] lemma coe_inf (s t : clopens α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl
@[simp] lemma coe_top : (↑(⊤ : clopens α) : set α) = univ := rfl
@[simp] lemma coe_bot : (↑(⊥ : clopens α) : set α) = ∅ := rfl
@[simp] lemma coe_sdiff (s t : clopens α) : (↑(s \ t) : set α) = s \ t := rfl
@[simp] lemma coe_compl (s : clopens α) : (↑sᶜ : set α) = sᶜ := rfl
instance : inhabited (clopens α) := ⟨⊥⟩
end clopens
end topological_space
|
b279bb7f9c41f7e682b443140f01180bec847451 | 4fa161becb8ce7378a709f5992a594764699e268 | /src/topology/metric_space/isometry.lean | ad16eda6a8088375f1b51297be25a08264b7dbe5 | [
"Apache-2.0"
] | permissive | laughinggas/mathlib | e4aa4565ae34e46e834434284cb26bd9d67bc373 | 86dcd5cda7a5017c8b3c8876c89a510a19d49aad | refs/heads/master | 1,669,496,232,688 | 1,592,831,995,000 | 1,592,831,995,000 | 274,155,979 | 0 | 0 | Apache-2.0 | 1,592,835,190,000 | 1,592,835,189,000 | null | UTF-8 | Lean | false | false | 16,812 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Isometries of emetric and metric spaces
Authors: Sébastien Gouëzel
-/
import topology.bounded_continuous_function
import topology.opens
/-!
# Isometries
We define isometries, i.e., maps between emetric spaces that preserve
the edistance (on metric spaces, these are exactly the maps that preserve distances),
and prove their basic properties. We also introduce isometric bijections.
-/
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open function set
/-- An isometry (also known as isometric embedding) is a map preserving the edistance
between emetric spaces, or equivalently the distance between metric space. -/
def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop :=
∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2
/-- On metric spaces, a map is an isometry if and only if it preserves distances. -/
lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} :
isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) :=
⟨assume H x y, by simp [dist_edist, H x y],
assume H x y, by simp [edist_dist, H x y]⟩
/-- An isometry preserves edistances. -/
theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} (hf : isometry f)
(x y : α) :
edist (f x) (f y) = edist x y :=
hf x y
/-- An isometry preserves distances. -/
theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) (x y : α) :
dist (f x) (f y) = dist x y :=
by rw [dist_edist, dist_edist, hf]
section emetric_isometry
variables [emetric_space α] [emetric_space β] [emetric_space γ]
variables {f : α → β} {x y z : α} {s : set α}
lemma isometry.lipschitz (h : isometry f) : lipschitz_with 1 f :=
lipschitz_with.of_edist_le $ λ x y, le_of_eq (h x y)
lemma isometry.antilipschitz (h : isometry f) : antilipschitz_with 1 f :=
λ x y, by simp only [h x y, ennreal.coe_one, one_mul, le_refl]
/-- An isometry is injective -/
lemma isometry.injective (h : isometry f) : injective f := h.antilipschitz.injective
/-- Any map on a subsingleton is an isometry -/
theorem isometry_subsingleton [subsingleton α] : isometry f :=
λx y, by rw subsingleton.elim x y; simp
/-- The identity is an isometry -/
lemma isometry_id : isometry (id : α → α) :=
λx y, rfl
/-- The composition of isometries is an isometry -/
theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) :=
assume x y, calc
edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _
... = edist x y : hf _ _
/-- An isometry is an embedding -/
theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f :=
hf.antilipschitz.uniform_embedding hf.lipschitz.uniform_continuous
/-- An isometry is continuous. -/
lemma isometry.continuous (hf : isometry f) : continuous f :=
hf.lipschitz.continuous
/-- The right inverse of an isometry is an isometry. -/
lemma isometry.right_inv {f : α → β} {g : β → α} (h : isometry f) (hg : right_inverse g f) :
isometry g :=
λ x y, by rw [← h, hg _, hg _]
/-- Isometries preserve the diameter in emetric spaces. -/
lemma isometry.ediam_image (hf : isometry f) (s : set α) :
emetric.diam (f '' s) = emetric.diam s :=
eq_of_forall_ge_iff $ λ d,
by simp only [emetric.diam_le_iff_forall_edist_le, ball_image_iff, hf.edist_eq]
lemma isometry.ediam_range (hf : isometry f) :
emetric.diam (range f) = emetric.diam (univ : set α) :=
by { rw ← image_univ, exact hf.ediam_image univ }
/-- The injection from a subtype is an isometry -/
lemma isometry_subtype_val {s : set α} : isometry (subtype.val : s → α) :=
λx y, rfl
end emetric_isometry --section
/-- An isometry preserves the diameter in metric spaces. -/
lemma isometry.diam_image [metric_space α] [metric_space β]
{f : α → β} (hf : isometry f) (s : set α) : metric.diam (f '' s) = metric.diam s :=
by rw [metric.diam, metric.diam, hf.ediam_image]
lemma isometry.diam_range [metric_space α] [metric_space β] {f : α → β} (hf : isometry f) :
metric.diam (range f) = metric.diam (univ : set α) :=
by { rw ← image_univ, exact hf.diam_image univ }
/-- `α` and `β` are isometric if there is an isometric bijection between them. -/
structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β]
extends α ≃ β :=
(isometry_to_fun : isometry to_fun)
infix ` ≃ᵢ `:25 := isometric
namespace isometric
variables [emetric_space α] [emetric_space β] [emetric_space γ]
instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl
protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun
protected lemma edist_eq (h : α ≃ᵢ β) (x y : α) : edist (h x) (h y) = edist x y :=
h.isometry.edist_eq x y
protected lemma dist_eq {α β : Type*} [metric_space α] [metric_space β] (h : α ≃ᵢ β) (x y : α) :
dist (h x) (h y) = dist x y :=
h.isometry.dist_eq x y
protected lemma continuous (h : α ≃ᵢ β) : continuous h := h.isometry.continuous
lemma to_equiv_inj : ∀ ⦃h₁ h₂ : α ≃ᵢ β⦄, (h₁.to_equiv = h₂.to_equiv) → h₁ = h₂
| ⟨e₁, h₁⟩ ⟨e₂, h₂⟩ H := by { dsimp at H, subst e₁ }
@[ext] lemma ext ⦃h₁ h₂ : α ≃ᵢ β⦄ (H : ∀ x, h₁ x = h₂ x) : h₁ = h₂ :=
to_equiv_inj $ equiv.ext H
/-- Alternative constructor for isometric bijections,
taking as input an isometry, and a right inverse. -/
def mk' (f : α → β) (g : β → α) (hfg : ∀ x, f (g x) = x) (hf : isometry f) : α ≃ᵢ β :=
{ to_fun := f,
inv_fun := g,
left_inv := λ x, hf.injective $ hfg _,
right_inv := hfg,
isometry_to_fun := hf }
/-- The identity isometry of a space. -/
protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α :=
{ isometry_to_fun := isometry_id, .. equiv.refl α }
/-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/
protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ :=
{ isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
@[simp] lemma trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : α) : h₁.trans h₂ x = h₂ (h₁ x) := rfl
/-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/
protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α :=
{ isometry_to_fun := h.isometry.right_inv h.right_inv,
to_equiv := h.to_equiv.symm }
@[simp] lemma symm_symm (h : α ≃ᵢ β) : h.symm.symm = h := to_equiv_inj h.to_equiv.symm_symm
@[simp] lemma apply_symm_apply (h : α ≃ᵢ β) (y : β) : h (h.symm y) = y :=
h.to_equiv.apply_symm_apply y
@[simp] lemma symm_apply_apply (h : α ≃ᵢ β) (x : α) : h.symm (h x) = x :=
h.to_equiv.symm_apply_apply x
lemma symm_apply_eq (h : α ≃ᵢ β) {x : α} {y : β} :
h.symm y = x ↔ y = h x :=
h.to_equiv.symm_apply_eq
lemma eq_symm_apply (h : α ≃ᵢ β) {x : α} {y : β} :
x = h.symm y ↔ h x = y :=
h.to_equiv.eq_symm_apply
lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ᵢ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
@[simp] lemma symm_trans_apply (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) (x : γ) :
(h₁.trans h₂).symm x = h₁.symm (h₂.symm x) := rfl
/-- The (bundled) homeomorphism associated to an isometric isomorphism. -/
protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β :=
{ continuous_to_fun := h.continuous,
continuous_inv_fun := h.symm.continuous,
.. h }
@[simp] lemma coe_to_homeomorph (h : α ≃ᵢ β) : ⇑(h.to_homeomorph) = h := rfl
@[simp] lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) :
h.to_homeomorph.to_equiv = h.to_equiv :=
rfl
/-- The group of isometries. -/
instance : group (α ≃ᵢ α) :=
{ one := isometric.refl _,
mul := λ e₁ e₂, e₁.trans e₂,
inv := isometric.symm,
mul_assoc := λ e₁ e₂ e₃, rfl,
one_mul := λ e, ext $ λ _, rfl,
mul_one := λ e, ext $ λ _, rfl,
mul_left_inv := λ e, ext e.apply_symm_apply }
@[simp] lemma coe_one : ⇑(1 : α ≃ᵢ α) = id := rfl
@[simp] lemma coe_mul (e₁ e₂ : α ≃ᵢ α) : ⇑(e₁ * e₂) = e₂ ∘ e₁ := rfl
lemma mul_apply (e₁ e₂ : α ≃ᵢ α) (x : α) : (e₁ * e₂) x = e₂ (e₁ x) := rfl
@[simp] lemma inv_apply_self (e : α ≃ᵢ α) (x: α) : e⁻¹ (e x) = x := e.symm_apply_apply x
@[simp] lemma apply_inv_self (e : α ≃ᵢ α) (x: α) : e (e⁻¹ x) = x := e.apply_symm_apply x
section normed_group
variables {G : Type*} [normed_group G]
/-- Addition `y ↦ y + x` as an `isometry`. -/
protected def add_right (x : G) : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_right _ _ _,
.. equiv.add_right x }
@[simp] lemma add_right_to_equiv (x : G) :
(isometric.add_right x).to_equiv = equiv.add_right x := rfl
@[simp] lemma coe_add_right (x : G) : (isometric.add_right x : G → G) = λ y, y + x := rfl
lemma add_right_apply (x y : G) : (isometric.add_right x : G → G) y = y + x := rfl
@[simp] lemma add_right_symm (x : G) :
(isometric.add_right x).symm = isometric.add_right (-x) :=
ext $ λ y, rfl
/-- Addition `y ↦ x + y` as an `isometry`. -/
protected def add_left (x : G) : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ y z, dist_add_left _ _ _,
to_equiv := equiv.add_left x }
@[simp] lemma add_left_to_equiv (x : G) :
(isometric.add_left x).to_equiv = equiv.add_left x := rfl
@[simp] lemma coe_add_left (x : G) : ⇑(isometric.add_left x) = (+) x := rfl
@[simp] lemma add_left_symm (x : G) :
(isometric.add_left x).symm = isometric.add_left (-x) :=
ext $ λ y, rfl
variable (G)
/-- Negation `x ↦ -x` as an `isometry`. -/
protected def neg : G ≃ᵢ G :=
{ isometry_to_fun := isometry_emetric_iff_metric.2 $ λ x y, dist_neg_neg _ _,
to_equiv := equiv.neg G }
variable {G}
@[simp] lemma neg_symm : (isometric.neg G).symm = isometric.neg G := rfl
@[simp] lemma neg_to_equiv : (isometric.neg G).to_equiv = equiv.neg G := rfl
@[simp] lemma coe_neg : ⇑(isometric.neg G) = has_neg.neg := rfl
end normed_group
end isometric
/-- An isometry induces an isometric isomorphism between the source space and the
range of the isometry. -/
def isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) :
α ≃ᵢ range f :=
{ isometry_to_fun := λx y, by simpa [subtype.edist_eq] using h x y,
.. equiv.set.range f h.injective }
@[simp] lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β]
{f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ :=
rfl
/-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/
lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[normed_algebra 𝕜 𝕜'] : isometry (algebra_map 𝕜 𝕜') :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
rw [dist_eq_norm, dist_eq_norm, ← ring_hom.map_sub, norm_algebra_map_eq],
end
/-- The space of bounded sequences, with its sup norm -/
@[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ
open bounded_continuous_function metric topological_space
namespace Kuratowski_embedding
/-! ### In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/
variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α)
/-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in
a fixed countable set, if this set is dense. This map is given in the next definition,
without density assumptions. -/
def embedding_of_subset : ℓ_infty_ℝ :=
of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _)
lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl
/-- The embedding map is always a semi-contraction. -/
lemma embedding_of_subset_dist_le (a b : α) :
dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b :=
begin
refine (dist_le dist_nonneg).2 (λn, _),
have A : dist a (x n) + (dist (x 0) (x n) + (-dist b (x n) + -dist (x 0) (x n)))
= dist a (x n) - dist b (x n), by ring,
simp only [embedding_of_subset_coe, real.dist_eq, A, add_comm, neg_add_rev, _root_.neg_neg,
sub_eq_add_neg, add_left_comm],
exact abs_dist_sub_le _ _ _
end
/-- When the reference set is dense, the embedding map is an isometry on its image. -/
lemma embedding_of_subset_isometry (H : closure (range x) = univ) : isometry (embedding_of_subset x) :=
begin
refine isometry_emetric_iff_metric.2 (λa b, _),
refine le_antisymm (embedding_of_subset_dist_le x a b) (real.le_of_forall_epsilon_le (λe epos, _)),
/- First step: find n with dist a (x n) < e -/
have A : a ∈ closure (range x), by { have B := mem_univ a, rwa [← H] at B },
rcases metric.mem_closure_range_iff.1 A (e/2) (half_pos epos) with ⟨n, hn⟩,
/- Second step: use the norm control at index n to conclude -/
have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n :=
by { simp only [embedding_of_subset_coe, sub_sub_sub_cancel_right] },
have := calc
dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _
... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring }
... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) :
by apply_rules [add_le_add_left, le_abs_self]
... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) :
begin rw [C], apply_rules [add_le_add, mul_le_mul_of_nonneg_left, le_of_lt hn, le_refl], norm_num end
... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) :
begin rw [← sub_apply], apply add_le_add_left, rw [sub_apply, ←real.dist_eq], apply dist_coe_le_dist end
... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring,
simpa [dist_comm] using this
end
/-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/
theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] :
∃(f : α → ℓ_infty_ℝ), isometry f :=
begin
cases (univ : set α).eq_empty_or_nonempty with h h,
{ use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) },
{ /- We construct a map x : ℕ → α with dense image -/
rcases h with basepoint,
haveI : inhabited α := ⟨basepoint⟩,
have : ∃s:set α, countable s ∧ closure s = univ := separable_space.exists_countable_closure_eq_univ,
rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩,
rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩,
have : closure (range x) = univ :=
univ_subset_iff.1 (by { rw [← S_dense], apply closure_mono, assumption }),
/- Use embedding_of_subset to construct the desired isometry -/
exact ⟨embedding_of_subset x, embedding_of_subset_isometry x this⟩ }
end
end Kuratowski_embedding
open topological_space Kuratowski_embedding
/-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/
def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ :=
classical.some (Kuratowski_embedding.exists_isometric_embedding α)
/-- The Kuratowski embedding is an isometry -/
protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] :
isometry (Kuratowski_embedding α) :=
classical.some_spec (exists_isometric_embedding α)
/-- Version of the Kuratowski embedding for nonempty compacts -/
def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] :
nonempty_compacts ℓ_infty_ℝ :=
⟨range (Kuratowski_embedding α), range_nonempty _,
compact_range (Kuratowski_embedding.isometry α).continuous⟩
|
9c0acbe42bb2877cce07d2e0794b195ba4230cfa | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/macroError.lean | d81ed4b1bc7967f97129773bb0a72538a547cc1c | [
"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 | 69 | lean | macro "foo" : term => Lean.Macro.throwError "Test Error"
#check foo
|
0fc9cd81ce7afa5828b0dd60bc9e1e049acb75a6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/comma.lean | 4af917820261a07e0fc9303c0cd22895d214d7be | [] | 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 | 10,964 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johan Commelin, Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.natural_isomorphism
import Mathlib.PostPort
universes v₁ v₂ v₃ u₁ u₂ u₃ l
namespace Mathlib
/-!
# Comma categories
A comma category is a construction in category theory, which builds a category out of two functors
with a common codomain. Specifically, for functors `L : A ⥤ T` and `R : B ⥤ T`, an object in
`comma L R` is a morphism `hom : L.obj left ⟶ R.obj right` for some objects `left : A` and
`right : B`, and a morphism in `comma L R` between `hom : L.obj left ⟶ R.obj right` and
`hom' : L.obj left' ⟶ R.obj right'` is a commutative square
```
L.obj left ⟶ L.obj left'
| |
hom | | hom'
↓ ↓
R.obj right ⟶ R.obj right',
```
where the top and bottom morphism come from morphisms `left ⟶ left'` and `right ⟶ right'`,
respectively.
## Main definitions
* `comma L R`: the comma category of the functors `L` and `R`.
* `over X`: the over category of the object `X` (developed in `over.lean`).
* `under X`: the under category of the object `X` (also developed in `over.lean`).
* `arrow T`: the arrow category of the category `T` (developed in `arrow.lean`).
## References
* <https://ncatlab.org/nlab/show/comma+category>
## Tags
comma, slice, coslice, over, under, arrow
-/
namespace category_theory
/-- The objects of the comma category are triples of an object `left : A`, an object
`right : B` and a morphism `hom : L.obj left ⟶ R.obj right`. -/
structure comma {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T)
where
left : autoParam A
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
right : autoParam B
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
hom : functor.obj L left ⟶ functor.obj R right
-- Satisfying the inhabited linter
protected instance comma.inhabited {T : Type u₃} [category T] [Inhabited T] : Inhabited (comma 𝟭 𝟭) :=
{ default := comma.mk 𝟙 }
/-- A morphism between two objects in the comma category is a commutative square connecting the
morphisms coming from the two objects using morphisms in the image of the functors `L` and `R`.
-/
structure comma_morphism {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} (X : comma L R) (Y : comma L R)
where
left : autoParam (comma.left X ⟶ comma.left Y)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
right : autoParam (comma.right X ⟶ comma.right Y)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
w' : autoParam (functor.map L left ≫ comma.hom Y = comma.hom X ≫ functor.map R right)
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously")
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") [])
-- Satisfying the inhabited linter
protected instance comma_morphism.inhabited {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} [Inhabited (comma L R)] : Inhabited (comma_morphism Inhabited.default Inhabited.default) :=
{ default := comma_morphism.mk }
@[simp] theorem comma_morphism.w {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} {Y : comma L R} (c : comma_morphism X Y) : functor.map L (comma_morphism.left c) ≫ comma.hom Y = comma.hom X ≫ functor.map R (comma_morphism.right c) := sorry
@[simp] theorem comma_morphism.w_assoc {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} {Y : comma L R} (c : comma_morphism X Y) {X' : T} (f' : functor.obj R (comma.right Y) ⟶ X') : functor.map L (comma_morphism.left c) ≫ comma.hom Y ≫ f' = comma.hom X ≫ functor.map R (comma_morphism.right c) ≫ f' := sorry
protected instance comma_category {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} : category (comma L R) :=
category.mk
namespace comma
@[simp] theorem id_left {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} : comma_morphism.left 𝟙 = 𝟙 :=
rfl
@[simp] theorem id_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} : comma_morphism.right 𝟙 = 𝟙 :=
rfl
@[simp] theorem comp_left {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} {Y : comma L R} {Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} : comma_morphism.left (f ≫ g) = comma_morphism.left f ≫ comma_morphism.left g :=
rfl
@[simp] theorem comp_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L : A ⥤ T} {R : B ⥤ T} {X : comma L R} {Y : comma L R} {Z : comma L R} {f : X ⟶ Y} {g : Y ⟶ Z} : comma_morphism.right (f ≫ g) = comma_morphism.right f ≫ comma_morphism.right g :=
rfl
/-- The functor sending an object `X` in the comma category to `X.left`. -/
def fst {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T) : comma L R ⥤ A :=
functor.mk (fun (X : comma L R) => left X) fun (_x _x_1 : comma L R) (f : _x ⟶ _x_1) => comma_morphism.left f
/-- The functor sending an object `X` in the comma category to `X.right`. -/
@[simp] theorem snd_map {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T) (_x : comma L R) : ∀ (_x_1 : comma L R) (f : _x ⟶ _x_1), functor.map (snd L R) f = comma_morphism.right f :=
fun (_x_1 : comma L R) (f : _x ⟶ _x_1) => Eq.refl (functor.map (snd L R) f)
/-- We can interpret the commutative square constituting a morphism in the comma category as a
natural transformation between the functors `fst ⋙ L` and `snd ⋙ R` from the comma category
to `T`, where the components are given by the morphism that constitutes an object of the comma
category. -/
@[simp] theorem nat_trans_app {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T) (X : comma L R) : nat_trans.app (nat_trans L R) X = hom X :=
Eq.refl (nat_trans.app (nat_trans L R) X)
/--
Construct an isomorphism in the comma category given isomorphisms of the objects whose forward
directions give a commutative square.
-/
@[simp] theorem iso_mk_inv_left {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] {L₁ : A ⥤ T} {R₁ : B ⥤ T} {X : comma L₁ R₁} {Y : comma L₁ R₁} (l : left X ≅ left Y) (r : right X ≅ right Y) (h : functor.map L₁ (iso.hom l) ≫ hom Y = hom X ≫ functor.map R₁ (iso.hom r)) : comma_morphism.left (iso.inv (iso_mk l r h)) = iso.inv l :=
Eq.refl (comma_morphism.left (iso.inv (iso_mk l r h)))
/-- A natural transformation `L₁ ⟶ L₂` induces a functor `comma L₂ R ⥤ comma L₁ R`. -/
@[simp] theorem map_left_obj_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (R : B ⥤ T) {L₁ : A ⥤ T} {L₂ : A ⥤ T} (l : L₁ ⟶ L₂) (X : comma L₂ R) : right (functor.obj (map_left R l) X) = right X :=
Eq.refl (right (functor.obj (map_left R l) X))
/-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `L` is
naturally isomorphic to the identity functor. -/
@[simp] theorem map_left_id_inv_app_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T) (X : comma L R) : comma_morphism.right (nat_trans.app (iso.inv (map_left_id L R)) X) = 𝟙 :=
Eq.refl (comma_morphism.right (nat_trans.app (iso.inv (map_left_id L R)) X))
/-- The functor `comma L₁ R ⥤ comma L₃ R` induced by the composition of two natural transformations
`l : L₁ ⟶ L₂` and `l' : L₂ ⟶ L₃` is naturally isomorphic to the composition of the two functors
induced by these natural transformations. -/
@[simp] theorem map_left_comp_hom_app_left {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (R : B ⥤ T) {L₁ : A ⥤ T} {L₂ : A ⥤ T} {L₃ : A ⥤ T} (l : L₁ ⟶ L₂) (l' : L₂ ⟶ L₃) (X : comma L₃ R) : comma_morphism.left (nat_trans.app (iso.hom (map_left_comp R l l')) X) = 𝟙 :=
Eq.refl (comma_morphism.left (nat_trans.app (iso.hom (map_left_comp R l l')) X))
/-- A natural transformation `R₁ ⟶ R₂` induces a functor `comma L R₁ ⥤ comma L R₂`. -/
def map_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) {R₁ : B ⥤ T} {R₂ : B ⥤ T} (r : R₁ ⟶ R₂) : comma L R₁ ⥤ comma L R₂ :=
functor.mk (fun (X : comma L R₁) => mk (hom X ≫ nat_trans.app r (right X)))
fun (X Y : comma L R₁) (f : X ⟶ Y) => comma_morphism.mk
/-- The functor `comma L R ⥤ comma L R` induced by the identity natural transformation on `R` is
naturally isomorphic to the identity functor. -/
@[simp] theorem map_right_id_inv_app_left {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) (R : B ⥤ T) (X : comma L R) : comma_morphism.left (nat_trans.app (iso.inv (map_right_id L R)) X) = 𝟙 :=
Eq.refl (comma_morphism.left (nat_trans.app (iso.inv (map_right_id L R)) X))
/-- The functor `comma L R₁ ⥤ comma L R₃` induced by the composition of the natural transformations
`r : R₁ ⟶ R₂` and `r' : R₂ ⟶ R₃` is naturally isomorphic to the composition of the functors
induced by these natural transformations. -/
@[simp] theorem map_right_comp_inv_app_right {A : Type u₁} [category A] {B : Type u₂} [category B] {T : Type u₃} [category T] (L : A ⥤ T) {R₁ : B ⥤ T} {R₂ : B ⥤ T} {R₃ : B ⥤ T} (r : R₁ ⟶ R₂) (r' : R₂ ⟶ R₃) (X : comma L R₁) : comma_morphism.right (nat_trans.app (iso.inv (map_right_comp L r r')) X) = 𝟙 :=
Eq.refl (comma_morphism.right (nat_trans.app (iso.inv (map_right_comp L r r')) X))
|
6c1e57e4bf78dc10c666dbd2b453a945483e6cd0 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/deprecated/subfield.lean | 27b4826b1fafae23e412aecf453399bdaec8229e | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 5,171 | 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 deprecated.subring
import algebra.group_with_zero_power
variables {F : Type*} [field F] (S : set F)
class is_subfield extends is_subring S : Prop :=
(inv_mem : ∀ {x : F}, x ∈ S → x⁻¹ ∈ S)
instance is_subfield.field [is_subfield S] : field S :=
by letI cr_inst : comm_ring S := subset.comm_ring; exact
{ inv := λ x, ⟨x⁻¹, is_subfield.inv_mem x.2⟩,
exists_pair_ne := ⟨0, 1, λ h, zero_ne_one (subtype.ext_iff_val.1 h)⟩,
mul_inv_cancel := λ a ha, subtype.ext_iff_val.2 (mul_inv_cancel
(λ h, ha $ subtype.ext_iff_val.2 h)),
inv_zero := subtype.ext_iff_val.2 inv_zero,
.. cr_inst }
lemma is_subfield.pow_mem {a : F} {n : ℤ} {s : set F} [is_subfield s] (h : a ∈ s) :
a ^ n ∈ s :=
begin
cases n,
{ exact is_submonoid.pow_mem h },
{ exact is_subfield.inv_mem (is_submonoid.pow_mem h) },
end
instance univ.is_subfield : is_subfield (@set.univ F) :=
{ inv_mem := by intros; trivial }
/- note: in the next two declarations, if we let type-class inference figure out the instance
`ring_hom.is_subring_preimage` then that instance only applies when particular instances of
`is_add_subgroup _` and `is_submonoid _` are chosen (which are not the default ones).
If we specify it explicitly, then it doesn't complain. -/
instance preimage.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set K) [is_subfield s] : is_subfield (f ⁻¹' s) :=
{ inv_mem := λ a (ha : f a ∈ s), show f a⁻¹ ∈ s,
by { rw [f.map_inv],
exact is_subfield.inv_mem ha },
..f.is_subring_preimage s }
instance image.is_subfield {K : Type*} [field K]
(f : F →+* K) (s : set F) [is_subfield s] : is_subfield (f '' s) :=
{ inv_mem := λ a ⟨x, xmem, ha⟩, ⟨x⁻¹, is_subfield.inv_mem xmem, ha ▸ f.map_inv _⟩,
..f.is_subring_image s }
instance range.is_subfield {K : Type*} [field K]
(f : F →+* K) : is_subfield (set.range f) :=
by { rw ← set.image_univ, apply_instance }
namespace field
/-- `field.closure s` is the minimal subfield that includes `s`. -/
def closure : set F :=
{ x | ∃ y ∈ ring.closure S, ∃ z ∈ ring.closure S, y / z = x }
variables {S}
theorem ring_closure_subset : ring.closure S ⊆ closure S :=
λ x hx, ⟨x, hx, 1, is_submonoid.one_mem, div_one x⟩
instance closure.is_submonoid : is_submonoid (closure S) :=
{ mul_mem := by rintros _ _ ⟨p, hp, q, hq, hq0, rfl⟩ ⟨r, hr, s, hs, hs0, rfl⟩;
exact ⟨p * r,
is_submonoid.mul_mem hp hr,
q * s,
is_submonoid.mul_mem hq hs,
(div_mul_div _ _ _ _).symm⟩,
one_mem := ring_closure_subset $ is_submonoid.one_mem }
instance closure.is_subfield : is_subfield (closure S) :=
have h0 : (0:F) ∈ closure S, from ring_closure_subset $ is_add_submonoid.zero_mem,
{ add_mem := begin
intros a b ha hb,
rcases (id ha) with ⟨p, hp, q, hq, rfl⟩,
rcases (id hb) with ⟨r, hr, s, hs, rfl⟩,
classical, by_cases hq0 : q = 0, by simp [hb, hq0], by_cases hs0 : s = 0, by simp [ha, hs0],
exact ⟨p * s + q * r, is_add_submonoid.add_mem (is_submonoid.mul_mem hp hs)
(is_submonoid.mul_mem hq hr), q * s, is_submonoid.mul_mem hq hs,
(div_add_div p r hq0 hs0).symm⟩
end,
zero_mem := h0,
neg_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
exact ⟨-p, is_add_subgroup.neg_mem hp, q, hq, neg_div q p⟩
end,
inv_mem := begin
rintros _ ⟨p, hp, q, hq, rfl⟩,
classical, by_cases hp0 : p = 0, by simp [hp0, h0],
exact ⟨q, hq, p, hp, inv_div.symm⟩
end }
theorem mem_closure {a : F} (ha : a ∈ S) : a ∈ closure S :=
ring_closure_subset $ ring.mem_closure ha
theorem subset_closure : S ⊆ closure S :=
λ _, mem_closure
theorem closure_subset {T : set F} [is_subfield T] (H : S ⊆ T) : closure S ⊆ T :=
by rintros _ ⟨p, hp, q, hq, hq0, rfl⟩; exact is_submonoid.mul_mem (ring.closure_subset H hp)
(is_subfield.inv_mem $ ring.closure_subset H hq)
theorem closure_subset_iff (s t : set F) [is_subfield t] : closure s ⊆ t ↔ s ⊆ t :=
⟨set.subset.trans subset_closure, closure_subset⟩
theorem closure_mono {s t : set F} (H : s ⊆ t) : closure s ⊆ closure t :=
closure_subset $ set.subset.trans H subset_closure
end field
lemma is_subfield_Union_of_directed {ι : Type*} [hι : nonempty ι]
(s : ι → set F) [∀ i, is_subfield (s i)]
(directed : ∀ i j, ∃ k, s i ⊆ s k ∧ s j ⊆ s k) :
is_subfield (⋃i, s i) :=
{ inv_mem := λ x hx, let ⟨i, hi⟩ := set.mem_Union.1 hx in
set.mem_Union.2 ⟨i, is_subfield.inv_mem hi⟩,
to_is_subring := is_subring_Union_of_directed s directed }
instance is_subfield.inter (S₁ S₂ : set F) [is_subfield S₁] [is_subfield S₂] :
is_subfield (S₁ ∩ S₂) :=
{ inv_mem := λ x hx, ⟨is_subfield.inv_mem hx.1, is_subfield.inv_mem hx.2⟩ }
instance is_subfield.Inter {ι : Sort*} (S : ι → set F) [h : ∀ y : ι, is_subfield (S y)] :
is_subfield (set.Inter S) :=
{ inv_mem := λ x hx, set.mem_Inter.2 $ λ y, is_subfield.inv_mem $ set.mem_Inter.1 hx y }
|
ad56f9f681c6e6c0075785d422fbdb64610afe29 | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/basics/unnamed_1702.lean | e396eba67c63faab02236088d68ac53a1cfb15d9 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 120 | lean | import data.nat.gcd
variables w x y z : ℕ
example (h : x ∣ w) : x ∣ y * (x * z) + x^2 + w^2 :=
begin
sorry
end |
a01811d3cb362f2cc0f94df8caf37970c0671d1c | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/wfrec1.lean | 232164a3165a7aa270fe088a56b829f55316efed | [
"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 | 672 | lean | private definition S := Σ a : nat, nat
private definition R : S → S → Prop := sigma.skip_left nat lt
private definition Rwf : well_founded R :=
sigma.skip_left_wf nat nat.lt_wf
private definition f_aux : ∀ (p₁ : S), (∀ p₂ : S, R p₂ p₁ → nat) → nat
| (sigma.mk n (m+1)) F := F (sigma.mk (n+10) (m - n)) (sigma.mk_skip_left _ _ (nat.sub_lt_succ _ _))
| (sigma.mk n 0) F := n
definition f (n m : nat) : nat :=
well_founded.fix Rwf f_aux (sigma.mk n m)
lemma f.eq_1 (n m : nat) : f n (m+1) = f (n+10) (m - n) :=
well_founded.fix_eq Rwf f_aux (sigma.mk n (m+1))
lemma f.eq_2 (n m : nat) : f n 0 = n :=
well_founded.fix_eq Rwf f_aux (sigma.mk n 0)
|
ffaf3d9116b29dc6a54276bf88d5bc17ef2b9ba1 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/lean/run/Dorais1.lean | 9cd9b35229165410df40022dd6cb185437e1c743 | [
"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,110 | lean | inductive Tree (α : Type _) : Type _
| leaf : α → Tree α
| branch : Tree α → Tree α → Tree α
inductive Path {α : Type _} : Tree α → Type _
| term (x : α) : Path (Tree.leaf x)
| left (tl tr : Tree α) : Path tl → Path (Tree.branch tl tr)
| right (tl tr : Tree α) : Path tr → Path (Tree.branch tl tr)
section map
variables {α : Type _} {β : Type _} (f : α → β)
protected def Tree.map : Tree α → Tree β
| Tree.leaf x => Tree.leaf (f x)
| Tree.branch tl tr => Tree.branch (Tree.map tl) (Tree.map tr)
protected def Path.map : {t : Tree α} → Path t → Path (t.map f)
| Tree.leaf _, Path.term x => Path.term (f x)
| Tree.branch _ _, Path.left tl tr p => Path.left (tl.map f) (tr.map f) (Path.map p)
| Tree.branch _ _, Path.right tl tr p => Path.right (tl.map f) (tr.map f) (Path.map p)
protected def Path.unmap : {t : Tree α} → Path (t.map f) → Path t
| Tree.leaf x, Path.term _ => Path.term x
| Tree.branch tl tr, Path.left _ _ p => Path.left tl tr (Path.unmap p)
| Tree.branch tl tr, Path.right _ _ p => Path.right tl tr (Path.unmap p)
#print Path.unmap
end map
|
2c16da522025131855fc1cd981a4670c88dfff2e | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /tests/lean/run/beta_zeta.lean | 9138e32741e75a436d4781e604f762f37de09bf2 | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 442 | lean | open tactic
meta def check_expr (p : pexpr) (t : expr) : tactic unit :=
do e ← to_expr p, guard (t = e)
example : true :=
let x := 10 in
by do h ← get_local `x,
head_zeta h >>= check_expr `(10),
triv
example : let x := 10 in true :=
by do x ← intro1,
head_zeta x >>= check_expr `(10),
triv
example : true :=
by do h ← to_expr `((λ x : nat, x + 1) 1),
head_beta h >>= check_expr `(1 + 1),
triv
|
3b8baf8c05bce92fdb481d567f7dec0e0c2f227c | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/measure_theory/measure/null_measurable.lean | 4145f604f33256cc1151e768faa0de4b7e91f2e9 | [
"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 | 16,383 | 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 measure_theory.measure.measure_space_def
/-!
# Null measurable sets and complete measures
## Main definitions
### Null measurable sets and functions
A set `s : set α` is called *null measurable* (`measure_theory.null_measurable_set`) if it satisfies
any of the following equivalent conditions:
* there exists a measurable set `t` such that `s =ᵐ[μ] t` (this is used as a definition);
* `measure_theory.to_measurable μ s =ᵐ[μ] s`;
* there exists a measurable subset `t ⊆ s` such that `t =ᵐ[μ] s` (in this case the latter equality
means that `μ (s \ t) = 0`);
* `s` can be represented as a union of a measurable set and a set of measure zero;
* `s` can be represented as a difference of a measurable set and a set of measure zero.
Null measurable sets form a σ-algebra that is registered as a `measurable_space` instance on
`measure_theory.null_measurable_space α μ`. We also say that `f : α → β` is
`measure_theory.null_measurable` if the preimage of a measurable set is a null measurable set.
In other words, `f : α → β` is null measurable if it is measurable as a function
`measure_theory.null_measurable_space α μ → β`.
### Complete measures
We say that a measure `μ` is complete w.r.t. the `measurable_space α` σ-algebra (or the σ-algebra is
complete w.r.t measure `μ`) if every set of measure zero is measurable. In this case all null
measurable sets and functions are measurable.
For each measure `μ`, we define `measure_theory.measure.completion μ` to be the same measure
interpreted as a measure on `measure_theory.null_measurable_space α μ` and prove that this is a
complete measure.
## Implementation notes
We define `measure_theory.null_measurable_set` as `@measurable_set (null_measurable_space α μ) _` so
that theorems about `measurable_set`s like `measurable_set.union` can be applied to
`null_measurable_set`s. However, these lemmas output terms of the same form
`@measurable_set (null_measurable_space α μ) _ _`. While this is definitionally equal to the
expected output `null_measurable_set s μ`, it looks different and may be misleading. So we copy all
standard lemmas about measurable sets to the `measure_theory.null_measurable_set` namespace and fix
the output type.
## Tags
measurable, measure, null measurable, completion
-/
open filter set encodable
variables {ι α β γ : Type*}
namespace measure_theory
/-- A type tag for `α` with `measurable_set` given by `null_measurable_set`. -/
@[nolint unused_arguments]
def null_measurable_space (α : Type*) [measurable_space α] (μ : measure α . volume_tac) : Type* := α
section
variables {m0 : measurable_space α} {μ : measure α} {s t : set α}
instance [h : inhabited α] : inhabited (null_measurable_space α μ) := h
instance [h : subsingleton α] : subsingleton (null_measurable_space α μ) := h
instance : measurable_space (null_measurable_space α μ) :=
{ measurable_set' := λ s, ∃ t, measurable_set t ∧ s =ᵐ[μ] t,
measurable_set_empty := ⟨∅, measurable_set.empty, ae_eq_refl _⟩,
measurable_set_compl := λ s ⟨t, htm, hts⟩, ⟨tᶜ, htm.compl, hts.compl⟩,
measurable_set_Union := λ s hs, by { choose t htm hts using hs,
exact ⟨⋃ i, t i, measurable_set.Union htm, eventually_eq.countable_Union hts⟩ } }
/-- A set is called `null_measurable_set` if it can be approximated by a measurable set up to
a set of null measure. -/
def null_measurable_set [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop :=
@measurable_set (null_measurable_space α μ) _ s
@[simp] lemma _root_.measurable_set.null_measurable_set (h : measurable_set s) :
null_measurable_set s μ :=
⟨s, h, ae_eq_refl _⟩
@[simp] lemma null_measurable_set_empty : null_measurable_set ∅ μ := measurable_set.empty
@[simp] lemma null_measurable_set_univ : null_measurable_set univ μ := measurable_set.univ
namespace null_measurable_set
lemma of_null (h : μ s = 0) : null_measurable_set s μ :=
⟨∅, measurable_set.empty, ae_eq_empty.2 h⟩
lemma compl (h : null_measurable_set s μ) : null_measurable_set sᶜ μ := h.compl
lemma of_compl (h : null_measurable_set sᶜ μ) : null_measurable_set s μ := h.of_compl
@[simp] lemma compl_iff : null_measurable_set sᶜ μ ↔ null_measurable_set s μ :=
measurable_set.compl_iff
@[nontriviality]
lemma of_subsingleton [subsingleton α] : null_measurable_set s μ := subsingleton.measurable_set
protected lemma congr (hs : null_measurable_set s μ) (h : s =ᵐ[μ] t) :
null_measurable_set t μ :=
let ⟨s', hm, hs'⟩ := hs in ⟨s', hm, h.symm.trans hs'⟩
protected lemma Union [encodable ι] {s : ι → set α}
(h : ∀ i, null_measurable_set (s i) μ) : null_measurable_set (⋃ i, s i) μ :=
measurable_set.Union h
protected lemma bUnion_decode₂ [encodable ι] ⦃f : ι → set α⦄ (h : ∀ i, null_measurable_set (f i) μ)
(n : ℕ) : null_measurable_set (⋃ b ∈ encodable.decode₂ ι n, f b) μ :=
measurable_set.bUnion_decode₂ h n
protected lemma bUnion {f : ι → set α} {s : set ι} (hs : countable s)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋃ b ∈ s, f b) μ :=
measurable_set.bUnion hs h
protected lemma sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋃₀ s) μ :=
by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h }
lemma Union_Prop {p : Prop} {f : p → set α} (hf : ∀ i, null_measurable_set (f i) μ) :
null_measurable_set (⋃ i, f i) μ :=
measurable_set.Union_Prop hf
lemma Union_fintype [fintype ι] {f : ι → set α} (h : ∀ b, null_measurable_set (f b) μ) :
null_measurable_set (⋃ b, f b) μ :=
measurable_set.Union_fintype h
protected lemma Inter [encodable ι] {f : ι → set α} (h : ∀ i, null_measurable_set (f i) μ) :
null_measurable_set (⋂ i, f i) μ :=
measurable_set.Inter h
protected lemma bInter {f : β → set α} {s : set β} (hs : countable s)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
measurable_set.bInter hs h
protected lemma sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋂₀ s) μ :=
measurable_set.sInter hs h
lemma Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, null_measurable_set (f b) μ) :
null_measurable_set (⋂ b, f b) μ :=
measurable_set.Inter_Prop hf
lemma Inter_fintype [fintype ι] {f : ι → set α} (h : ∀ b, null_measurable_set (f b) μ) :
null_measurable_set (⋂ b, f b) μ :=
measurable_set.Inter_fintype h
@[simp] protected lemma union (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s ∪ t) μ :=
hs.union ht
protected lemma union_null (hs : null_measurable_set s μ) (ht : μ t = 0) :
null_measurable_set (s ∪ t) μ :=
hs.union (of_null ht)
@[simp] protected lemma inter (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s ∩ t) μ :=
hs.inter ht
@[simp] protected lemma diff (hs : null_measurable_set s μ) (ht : null_measurable_set t μ) :
null_measurable_set (s \ t) μ :=
hs.diff ht
@[simp] protected lemma disjointed {f : ℕ → set α} (h : ∀ i, null_measurable_set (f i) μ) (n) :
null_measurable_set (disjointed f n) μ :=
measurable_set.disjointed h n
@[simp] protected lemma const (p : Prop) : null_measurable_set {a : α | p} μ :=
measurable_set.const p
instance [measurable_singleton_class α] : measurable_singleton_class (null_measurable_space α μ) :=
⟨λ x, (@measurable_set_singleton α _ _ x).null_measurable_set⟩
protected lemma insert [measurable_singleton_class (null_measurable_space α μ)]
(hs : null_measurable_set s μ) (a : α) :
null_measurable_set (insert a s) μ :=
hs.insert a
lemma exists_measurable_superset_ae_eq (h : null_measurable_set s μ) :
∃ t ⊇ s, measurable_set t ∧ t =ᵐ[μ] s :=
begin
rcases h with ⟨t, htm, hst⟩,
refine ⟨t ∪ to_measurable μ (s \ t), _, htm.union (measurable_set_to_measurable _ _), _⟩,
{ exact diff_subset_iff.1 (subset_to_measurable _ _) },
{ have : to_measurable μ (s \ t) =ᵐ[μ] (∅ : set α), by simp [ae_le_set.1 hst.le],
simpa only [union_empty] using hst.symm.union this }
end
lemma to_measurable_ae_eq (h : null_measurable_set s μ) :
to_measurable μ s =ᵐ[μ] s :=
begin
rw [to_measurable, dif_pos],
exact h.exists_measurable_superset_ae_eq.some_spec.snd.2
end
lemma compl_to_measurable_compl_ae_eq (h : null_measurable_set s μ) :
(to_measurable μ sᶜ)ᶜ =ᵐ[μ] s :=
by simpa only [compl_compl] using h.compl.to_measurable_ae_eq.compl
lemma exists_measurable_subset_ae_eq (h : null_measurable_set s μ) :
∃ t ⊆ s, measurable_set t ∧ t =ᵐ[μ] s :=
⟨(to_measurable μ sᶜ)ᶜ, compl_subset_comm.2 $ subset_to_measurable _ _,
(measurable_set_to_measurable _ _).compl, h.compl_to_measurable_compl_ae_eq⟩
end null_measurable_set
lemma measure_Union {m0 : measurable_space α} {μ : measure α} [encodable ι] {f : ι → set α}
(hn : pairwise (disjoint on f)) (h : ∀ i, measurable_set (f i)) :
μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
rw [measure_eq_extend (measurable_set.Union h),
extend_Union measurable_set.empty _ measurable_set.Union _ hn h],
{ simp [measure_eq_extend, h] },
{ exact μ.empty },
{ exact μ.m_Union }
end
lemma measure_Union₀ [encodable ι] {f : ι → set α}
(hn : pairwise (disjoint on f)) (h : ∀ i, null_measurable_set (f i) μ) :
μ (⋃ i, f i) = ∑' i, μ (f i) :=
begin
refine (measure_Union_le _).antisymm _,
choose s hsf hsm hs_eq using λ i, (h i).exists_measurable_subset_ae_eq,
have hsd : pairwise (disjoint on s), from hn.mono (λ i j h, h.mono (hsf i) (hsf j)),
simp only [← measure_congr (hs_eq _), ← measure_Union hsd hsm],
exact measure_mono (Union_subset_Union hsf)
end
lemma measure_union₀ (hs : null_measurable_set s μ) (ht : null_measurable_set t μ)
(hd : disjoint s t) :
μ (s ∪ t) = μ s + μ t :=
begin
rw [union_eq_Union, measure_Union₀, tsum_fintype, fintype.sum_bool, cond, cond],
exacts [pairwise_disjoint_on_bool.2 hd, λ b, bool.cases_on b ht hs]
end
section measurable_singleton_class
variable [measurable_singleton_class (null_measurable_space α μ)]
lemma null_measurable_set_singleton (x : α) : null_measurable_set {x} μ :=
measurable_set_singleton x
@[simp] lemma null_measurable_set_insert {a : α} {s : set α} :
null_measurable_set (insert a s) μ ↔ null_measurable_set s μ :=
measurable_set_insert
lemma null_measurable_set_eq {a : α} : null_measurable_set {x | x = a} μ :=
null_measurable_set_singleton a
protected lemma _root_.set.finite.null_measurable_set (hs : finite s) : null_measurable_set s μ :=
finite.measurable_set hs
protected lemma _root_.finset.null_measurable_set (s : finset α) : null_measurable_set ↑s μ :=
finset.measurable_set s
end measurable_singleton_class
lemma _root_.set.finite.null_measurable_set_bUnion {f : ι → set α} {s : set ι} (hs : finite s)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) :
null_measurable_set (⋃ b ∈ s, f b) μ :=
finite.measurable_set_bUnion hs h
lemma _root_.finset.null_measurable_set_bUnion {f : ι → set α} (s : finset ι)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) :
null_measurable_set (⋃ b ∈ s, f b) μ :=
finset.measurable_set_bUnion s h
lemma _root_.set.finite.null_measurable_set_sUnion {s : set (set α)} (hs : finite s)
(h : ∀ t ∈ s, null_measurable_set t μ) :
null_measurable_set (⋃₀ s) μ :=
finite.measurable_set_sUnion hs h
lemma _root_.set.finite.null_measurable_set_bInter {f : ι → set α} {s : set ι} (hs : finite s)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
finite.measurable_set_bInter hs h
lemma _root_.finset.null_measurable_set_bInter {f : ι → set α} (s : finset ι)
(h : ∀ b ∈ s, null_measurable_set (f b) μ) : null_measurable_set (⋂ b ∈ s, f b) μ :=
s.finite_to_set.null_measurable_set_bInter h
lemma _root_.set.finite.null_measurable_set_sInter {s : set (set α)} (hs : finite s)
(h : ∀ t ∈ s, null_measurable_set t μ) : null_measurable_set (⋂₀ s) μ :=
null_measurable_set.sInter hs.countable h
lemma null_measurable_set_to_measurable : null_measurable_set (to_measurable μ s) μ :=
(measurable_set_to_measurable _ _).null_measurable_set
end
section null_measurable
variables [measurable_space α] [measurable_space β] [measurable_space γ]
{f : α → β} {μ : measure α}
/-- A function `f : α → β` is null measurable if the preimage of a measurable set is a null
measurable set. -/
def null_measurable (f : α → β) (μ : measure α . volume_tac) : Prop :=
∀ ⦃s : set β⦄, measurable_set s → null_measurable_set (f ⁻¹' s) μ
protected lemma _root_.measurable.null_measurable (h : measurable f) : null_measurable f μ :=
λ s hs, (h hs).null_measurable_set
protected lemma null_measurable.measurable' (h : null_measurable f μ) :
@measurable (null_measurable_space α μ) β _ _ f := h
lemma measurable.comp_null_measurable {g : β → γ} (hg : measurable g)
(hf : null_measurable f μ) : null_measurable (g ∘ f) μ :=
hg.comp hf
lemma null_measurable.congr {g : α → β} (hf : null_measurable f μ) (hg : f =ᵐ[μ] g) :
null_measurable g μ :=
λ s hs, (hf hs).congr $ eventually_eq_set.2 $ hg.mono $
λ x hx, by rw [mem_preimage, mem_preimage, hx]
end null_measurable
section is_complete
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
class measure.is_complete {_ : measurable_space α} (μ : measure α) : Prop :=
(out' : ∀ s, μ s = 0 → measurable_set s)
variables {m0 : measurable_space α} {μ : measure α} {s t : set α}
theorem measure.is_complete_iff :
μ.is_complete ↔ ∀ s, μ s = 0 → measurable_set s := ⟨λ h, h.1, λ h, ⟨h⟩⟩
theorem measure.is_complete.out (h : μ.is_complete) :
∀ s, μ s = 0 → measurable_set s := h.1
theorem measurable_set_of_null [μ.is_complete] (hs : μ s = 0) : measurable_set s :=
measure_theory.measure.is_complete.out' s hs
theorem null_measurable_set.measurable_of_complete (hs : null_measurable_set s μ) [μ.is_complete] :
measurable_set s :=
diff_diff_cancel_left (subset_to_measurable μ s) ▸ (measurable_set_to_measurable _ _).diff
(measurable_set_of_null (ae_le_set.1 hs.to_measurable_ae_eq.le))
theorem null_measurable.measurable_of_complete [μ.is_complete] {m1 : measurable_space β} {f : α → β}
(hf : null_measurable f μ) : measurable f :=
λ s hs, (hf hs).measurable_of_complete
lemma _root_.measurable.congr_ae {α β} [measurable_space α] [measurable_space β] {μ : measure α}
[hμ : μ.is_complete] {f g : α → β} (hf : measurable f) (hfg : f =ᵐ[μ] g) :
measurable g :=
(hf.null_measurable.congr hfg).measurable_of_complete
namespace measure
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {_ : measurable_space α} (μ : measure α) :
@measure_theory.measure (null_measurable_space α μ) _ :=
{ to_outer_measure := μ.to_outer_measure,
m_Union := λ s hs hd, measure_Union₀ hd hs,
trimmed := begin
refine le_antisymm (λ s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi, simp only [to_outer_measure_apply],
refine (binfi_le_binfi _).trans_eq (measure_eq_infi _).symm,
exact λ t ht, infi_le_infi2 (λ h, ⟨h.null_measurable_set, le_rfl⟩)
end }
instance completion.is_complete {m : measurable_space α} (μ : measure α) :
μ.completion.is_complete :=
⟨λ z hz, null_measurable_set.of_null hz⟩
@[simp] lemma coe_completion {_ : measurable_space α} (μ : measure α) :
⇑μ.completion = μ := rfl
lemma completion_apply {_ : measurable_space α} (μ : measure α) (s : set α) :
μ.completion s = μ s := rfl
end measure
end is_complete
end measure_theory
|
8b85d30361e438a00abf2144b8a6c2ceec8aede2 | 618003631150032a5676f229d13a079ac875ff77 | /src/data/erased.lean | 59b7da4d3edda865b2d6b2f14d846b7f5136621e | [
"Apache-2.0"
] | permissive | awainverse/mathlib | 939b68c8486df66cfda64d327ad3d9165248c777 | ea76bd8f3ca0a8bf0a166a06a475b10663dec44a | refs/heads/master | 1,659,592,962,036 | 1,590,987,592,000 | 1,590,987,592,000 | 268,436,019 | 1 | 0 | Apache-2.0 | 1,590,990,500,000 | 1,590,990,500,000 | null | UTF-8 | Lean | false | false | 3,753 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.equiv.basic
universes u
/-!
# A type for VM-erased data
This file defines a type `erased α` which is classically isomorphic to `α`,
but erased in the VM. That is, at runtime every value of `erased α` is
represented as `0`, just like types and proofs.
-/
/-- `erased α` is the same as `α`, except that the elements
of `erased α` are erased in the VM in the same way as types
and proofs. This can be used to track data without storing it
literally. -/
def erased (α : Sort u) : Sort (max 1 u) :=
Σ' s : α → Prop, ∃ a, (λ b, a = b) = s
namespace erased
/-- Erase a value. -/
@[inline] def mk {α} (a : α) : erased α := ⟨λ b, a = b, a, rfl⟩
/-- Extracts the erased value, noncomputably. -/
noncomputable def out {α} : erased α → α
| ⟨s, h⟩ := classical.some h
/--
Extracts the erased value, if it is a type.
Note: `(mk a).out_type` is not definitionally equal to `a`.
-/
@[reducible] def out_type (a : erased (Sort u)) : Sort u := out a
/-- Extracts the erased value, if it is a proof. -/
theorem out_proof {p : Prop} (a : erased p) : p := out a
@[simp] theorem out_mk {α} (a : α) : (mk a).out = a :=
begin
let h, show classical.some h = a,
have := classical.some_spec h,
exact cast (congr_fun this a).symm rfl
end
@[simp] theorem mk_out {α} : ∀ (a : erased α), mk (out a) = a
| ⟨s, h⟩ := by simp [mk]; congr; exact classical.some_spec h
@[ext] lemma out_inj {α} (a b : erased α) (h : a.out = b.out) : a = b :=
by simpa using congr_arg mk h
/-- Equivalence between `erased α` and `α`. -/
noncomputable def equiv (α) : erased α ≃ α :=
⟨out, mk, mk_out, out_mk⟩
instance (α : Type u) : has_repr (erased α) := ⟨λ _, "erased"⟩
instance (α : Type u) : has_to_string (erased α) := ⟨λ _, "erased"⟩
meta instance (α : Type u) : has_to_format (erased α) := ⟨λ _, ("erased" : format)⟩
/-- Computably produce an erased value from a proof of nonemptiness. -/
def choice {α} (h : nonempty α) : erased α := mk (classical.choice h)
@[simp] theorem nonempty_iff {α} : nonempty (erased α) ↔ nonempty α :=
⟨λ ⟨a⟩, ⟨a.out⟩, λ ⟨a⟩, ⟨mk a⟩⟩
instance {α} [h : nonempty α] : inhabited (erased α) :=
⟨choice h⟩
/--
`(>>=)` operation on `erased`.
This is a separate definition because `α` and `β` can live in different
universes (the universe is fixed in `monad`).
-/
def bind {α β} (a : erased α) (f : α → erased β) : erased β :=
⟨λ b, (f a.out).1 b, (f a.out).2⟩
@[simp] theorem bind_eq_out {α β} (a f) : @bind α β a f = f a.out :=
by delta bind bind._proof_1; cases f a.out; refl
/--
Collapses two levels of erasure.
-/
def join {α} (a : erased (erased α)) : erased α := bind a id
@[simp] theorem join_eq_out {α} (a) : @join α a = a.out := bind_eq_out _ _
/--
`(<$>)` operation on `erased`.
This is a separate definition because `α` and `β` can live in different
universes (the universe is fixed in `functor`).
-/
def map {α β} (f : α → β) (a : erased α) : erased β :=
bind a (mk ∘ f)
@[simp] theorem map_out {α β} {f : α → β} (a : erased α) : (a.map f).out = f a.out :=
by simp [map]
instance : monad erased := { pure := @mk, bind := @bind, map := @map }
@[simp] lemma pure_def {α} : (pure : α → erased α) = @mk _ := rfl
@[simp] lemma bind_def {α β} : ((>>=) : erased α → (α → erased β) → erased β) = @bind _ _ := rfl
@[simp] lemma map_def {α β} : ((<$>) : (α → β) → erased α → erased β) = @map _ _ := rfl
instance : is_lawful_monad erased := by refine {..}; intros; ext; simp
end erased
|
961e3d9bc755ce61e410e455e37f1bc4d47b241e | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/posView.lean | c0da5b96cabebaab8f183e680e75996d85f32cf5 | [
"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,613 | lean | structure Pos where
protected succ :: protected pred : Nat
deriving Repr
protected def Pos.add : Pos → Pos → Pos
| .succ x, .succ y => .succ (x + y).succ
instance : Add Pos := ⟨Pos.add⟩
instance (x : Nat) : OfNat Pos x.succ := ⟨.succ x⟩
/-- View for `Pos` type. -/
inductive PosView where
| one
| succ (x : Pos)
/--
Convert `Pos` into `PosView`.
Remark: nonrecursive views do not impact performance of the generated code if marked as `[inline]`
-/
@[inline] def Pos.view (p : Pos) : PosView :=
match p with
| { pred := 0 } => PosView.one
| { pred := Nat.succ n } => PosView.succ ⟨n⟩
/--
Helper theorem for proving termination.
In the future, we should be able to mark it as a forward reasoning theorem for `decreasing_tactic`,
and it will be applied automatically for us. -/
theorem sizeof_lt_of_view_eq (h : Pos.view p₁ = PosView.succ p₂) : sizeOf p₂ < sizeOf p₁ := by
match p₁, p₂ with
| { pred := Nat.succ n }, { pred := Nat.succ m } => simp [Pos.view] at h; simp_arith [h]
| { pred := Nat.succ n }, { pred := 0 } => simp [Pos.view] at h; simp_arith [h]
| { pred := 0 }, _ => simp [Pos.view] at h
/-- `1` as notation for `PosView.one` -/
instance : OfNat PosView (nat_lit 1) where
ofNat := PosView.one
def f (p : Pos) : Pos :=
match h : p.view with -- It would also be nice to have a feature to force Lean to applies "views" automatically for us.
| 1 => 1
| .succ x =>
have : sizeOf x < sizeOf p := sizeof_lt_of_view_eq h -- See comment at `sizeof_lt_of_view_eq`
f x + x + 1
|
034e75cec46f73c1f4a788394772acc23b4504c2 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/order/filter/extr.lean | 72f0d2e246d636e77ebb1aff6d5e8c08031de4b5 | [
"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 | 21,708 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import order.filter.basic
/-!
# Minimum and maximum w.r.t. a filter and on a aet
## Main Definitions
This file defines six predicates of the form `is_A_B`, where `A` is `min`, `max`, or `extr`,
and `B` is `filter` or `on`.
* `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a`;
* `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a`;
* `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a`.
Similar predicates with `_on` suffix are particular cases for `l = 𝓟 s`.
## Main statements
### Change of the filter (set) argument
* `is_*_filter.filter_mono` : replace the filter with a smaller one;
* `is_*_filter.filter_inf` : replace a filter `l` with `l ⊓ l'`;
* `is_*_on.on_subset` : restrict to a smaller set;
* `is_*_on.inter` : replace a set `s` wtih `s ∩ t`.
### Composition
* `is_*_*.comp_mono` : if `x` is an extremum for `f` and `g` is a monotone function,
then `x` is an extremum for `g ∘ f`;
* `is_*_*.comp_antitone` : similarly for the case of antitone `g`;
* `is_*_*.bicomp_mono` : if `x` is an extremum of the same type for `f` and `g`
and a binary operation `op` is monotone in both arguments, then `x` is an extremum
of the same type for `λ x, op (f x) (g x)`.
* `is_*_filter.comp_tendsto` : if `g x` is an extremum for `f` w.r.t. `l'` and `tendsto g l l'`,
then `x` is an extremum for `f ∘ g` w.r.t. `l`.
* `is_*_on.on_preimage` : if `g x` is an extremum for `f` on `s`, then `x` is an extremum
for `f ∘ g` on `g ⁻¹' s`.
### Algebraic operations
* `is_*_*.add` : if `x` is an extremum of the same type for two functions,
then it is an extremum of the same type for their sum;
* `is_*_*.neg` : if `x` is an extremum for `f`, then it is an extremum
of the opposite type for `-f`;
* `is_*_*.sub` : if `x` is an a minimum for `f` and a maximum for `g`,
then it is a minimum for `f - g` and a maximum for `g - f`;
* `is_*_*.max`, `is_*_*.min`, `is_*_*.sup`, `is_*_*.inf` : similarly for `is_*_*.add`
for pointwise `max`, `min`, `sup`, `inf`, respectively.
### Miscellaneous definitions
* `is_*_*_const` : any point is both a minimum and maximum for a constant function;
* `is_min/max_*.is_ext` : any minimum/maximum point is an extremum;
* `is_*_*.dual`, `is_*_*.undual`: conversion between codomains `α` and `dual α`;
## Missing features (TODO)
* Multiplication and division;
* `is_*_*.bicompl` : if `x` is a minimum for `f`, `y` is a minimum for `g`, and `op` is a monotone
binary operation, then `(x, y)` is a minimum for `uncurry (bicompl op f g)`. From this point
of view, `is_*_*.bicomp` is a composition
* It would be nice to have a tactic that specializes `comp_(anti)mono` or `bicomp_mono`
based on a proof of monotonicity of a given (binary) function. The tactic should maintain a `meta`
list of known (anti)monotone (binary) functions with their names, as well as a list of special
types of filters, and define the missing lemmas once one of these two lists grows.
-/
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
open set filter
open_locale filter
section preorder
variables [preorder β] [preorder γ]
variables (f : α → β) (s : set α) (l : filter α) (a : α)
/-! ### Definitions -/
/-- `is_min_filter f l a` means that `f a ≤ f x` in some `l`-neighborhood of `a` -/
def is_min_filter : Prop := ∀ᶠ x in l, f a ≤ f x
/-- `is_max_filter f l a` means that `f x ≤ f a` in some `l`-neighborhood of `a` -/
def is_max_filter : Prop := ∀ᶠ x in l, f x ≤ f a
/-- `is_extr_filter f l a` means `is_min_filter f l a` or `is_max_filter f l a` -/
def is_extr_filter : Prop := is_min_filter f l a ∨ is_max_filter f l a
/-- `is_min_on f s a` means that `f a ≤ f x` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_min_on := is_min_filter f (𝓟 s) a
/-- `is_max_on f s a` means that `f x ≤ f a` for all `x ∈ a`. Note that we do not assume `a ∈ s`. -/
def is_max_on := is_max_filter f (𝓟 s) a
/-- `is_extr_on f s a` means `is_min_on f s a` or `is_max_on f s a` -/
def is_extr_on : Prop := is_extr_filter f (𝓟 s) a
variables {f s a l} {t : set α} {l' : filter α}
lemma is_extr_on.elim {p : Prop} :
is_extr_on f s a → (is_min_on f s a → p) → (is_max_on f s a → p) → p :=
or.elim
lemma is_min_on_iff : is_min_on f s a ↔ ∀ x ∈ s, f a ≤ f x := iff.rfl
lemma is_max_on_iff : is_max_on f s a ↔ ∀ x ∈ s, f x ≤ f a := iff.rfl
lemma is_min_on_univ_iff : is_min_on f univ a ↔ ∀ x, f a ≤ f x :=
univ_subset_iff.trans eq_univ_iff_forall
lemma is_max_on_univ_iff : is_max_on f univ a ↔ ∀ x, f x ≤ f a :=
univ_subset_iff.trans eq_univ_iff_forall
lemma is_min_filter.tendsto_principal_Ici (h : is_min_filter f l a) :
tendsto f l (𝓟 $ Ici (f a)) :=
tendsto_principal.2 h
lemma is_max_filter.tendsto_principal_Iic (h : is_max_filter f l a) :
tendsto f l (𝓟 $ Iic (f a)) :=
tendsto_principal.2 h
/-! ### Conversion to `is_extr_*` -/
lemma is_min_filter.is_extr : is_min_filter f l a → is_extr_filter f l a := or.inl
lemma is_max_filter.is_extr : is_max_filter f l a → is_extr_filter f l a := or.inr
lemma is_min_on.is_extr (h : is_min_on f s a) : is_extr_on f s a := h.is_extr
lemma is_max_on.is_extr (h : is_max_on f s a) : is_extr_on f s a := h.is_extr
/-! ### Constant function -/
lemma is_min_filter_const {b : β} : is_min_filter (λ _, b) l a :=
univ_mem' $ λ _, le_rfl
lemma is_max_filter_const {b : β} : is_max_filter (λ _, b) l a :=
univ_mem' $ λ _, le_rfl
lemma is_extr_filter_const {b : β} : is_extr_filter (λ _, b) l a := is_min_filter_const.is_extr
lemma is_min_on_const {b : β} : is_min_on (λ _, b) s a := is_min_filter_const
lemma is_max_on_const {b : β} : is_max_on (λ _, b) s a := is_max_filter_const
lemma is_extr_on_const {b : β} : is_extr_on (λ _, b) s a := is_extr_filter_const
/-! ### Order dual -/
open order_dual (to_dual)
lemma is_min_filter_dual_iff : is_min_filter (to_dual ∘ f) l a ↔ is_max_filter f l a :=
iff.rfl
lemma is_max_filter_dual_iff : is_max_filter (to_dual ∘ f) l a ↔ is_min_filter f l a :=
iff.rfl
lemma is_extr_filter_dual_iff : is_extr_filter (to_dual ∘ f) l a ↔ is_extr_filter f l a :=
or_comm _ _
alias is_min_filter_dual_iff ↔ is_min_filter.undual is_max_filter.dual
alias is_max_filter_dual_iff ↔ is_max_filter.undual is_min_filter.dual
alias is_extr_filter_dual_iff ↔ is_extr_filter.undual is_extr_filter.dual
lemma is_min_on_dual_iff : is_min_on (to_dual ∘ f) s a ↔ is_max_on f s a := iff.rfl
lemma is_max_on_dual_iff : is_max_on (to_dual ∘ f) s a ↔ is_min_on f s a := iff.rfl
lemma is_extr_on_dual_iff : is_extr_on (to_dual ∘ f) s a ↔ is_extr_on f s a := or_comm _ _
alias is_min_on_dual_iff ↔ is_min_on.undual is_max_on.dual
alias is_max_on_dual_iff ↔ is_max_on.undual is_min_on.dual
alias is_extr_on_dual_iff ↔ is_extr_on.undual is_extr_on.dual
/-! ### Operations on the filter/set -/
lemma is_min_filter.filter_mono (h : is_min_filter f l a) (hl : l' ≤ l) :
is_min_filter f l' a := hl h
lemma is_max_filter.filter_mono (h : is_max_filter f l a) (hl : l' ≤ l) :
is_max_filter f l' a := hl h
lemma is_extr_filter.filter_mono (h : is_extr_filter f l a) (hl : l' ≤ l) :
is_extr_filter f l' a :=
h.elim (λ h, (h.filter_mono hl).is_extr) (λ h, (h.filter_mono hl).is_extr)
lemma is_min_filter.filter_inf (h : is_min_filter f l a) (l') : is_min_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_max_filter.filter_inf (h : is_max_filter f l a) (l') : is_max_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_extr_filter.filter_inf (h : is_extr_filter f l a) (l') : is_extr_filter f (l ⊓ l') a :=
h.filter_mono inf_le_left
lemma is_min_on.on_subset (hf : is_min_on f t a) (h : s ⊆ t) : is_min_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_max_on.on_subset (hf : is_max_on f t a) (h : s ⊆ t) : is_max_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_extr_on.on_subset (hf : is_extr_on f t a) (h : s ⊆ t) : is_extr_on f s a :=
hf.filter_mono $ principal_mono.2 h
lemma is_min_on.inter (hf : is_min_on f s a) (t) : is_min_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_max_on.inter (hf : is_max_on f s a) (t) : is_max_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
lemma is_extr_on.inter (hf : is_extr_on f s a) (t) : is_extr_on f (s ∩ t) a :=
hf.on_subset (inter_subset_left s t)
/-! ### Composition with (anti)monotone functions -/
lemma is_min_filter.comp_mono (hf : is_min_filter f l a) {g : β → γ} (hg : monotone g) :
is_min_filter (g ∘ f) l a :=
mem_of_superset hf $ λ x hx, hg hx
lemma is_max_filter.comp_mono (hf : is_max_filter f l a) {g : β → γ} (hg : monotone g) :
is_max_filter (g ∘ f) l a :=
mem_of_superset hf $ λ x hx, hg hx
lemma is_extr_filter.comp_mono (hf : is_extr_filter f l a) {g : β → γ} (hg : monotone g) :
is_extr_filter (g ∘ f) l a :=
hf.elim (λ hf, (hf.comp_mono hg).is_extr) (λ hf, (hf.comp_mono hg).is_extr)
lemma is_min_filter.comp_antitone (hf : is_min_filter f l a) {g : β → γ}
(hg : antitone g) :
is_max_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_max_filter.comp_antitone (hf : is_max_filter f l a) {g : β → γ}
(hg : antitone g) :
is_min_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_extr_filter.comp_antitone (hf : is_extr_filter f l a) {g : β → γ}
(hg : antitone g) :
is_extr_filter (g ∘ f) l a :=
hf.dual.comp_mono (λ x y h, hg h)
lemma is_min_on.comp_mono (hf : is_min_on f s a) {g : β → γ} (hg : monotone g) :
is_min_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_max_on.comp_mono (hf : is_max_on f s a) {g : β → γ} (hg : monotone g) :
is_max_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_extr_on.comp_mono (hf : is_extr_on f s a) {g : β → γ} (hg : monotone g) :
is_extr_on (g ∘ f) s a :=
hf.comp_mono hg
lemma is_min_on.comp_antitone (hf : is_min_on f s a) {g : β → γ}
(hg : antitone g) :
is_max_on (g ∘ f) s a :=
hf.comp_antitone hg
lemma is_max_on.comp_antitone (hf : is_max_on f s a) {g : β → γ}
(hg : antitone g) :
is_min_on (g ∘ f) s a :=
hf.comp_antitone hg
lemma is_extr_on.comp_antitone (hf : is_extr_on f s a) {g : β → γ}
(hg : antitone g) :
is_extr_on (g ∘ f) s a :=
hf.comp_antitone hg
lemma is_min_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_filter f l a) {g : α → γ} (hg : is_min_filter g l a) :
is_min_filter (λ x, op (f x) (g x)) l a :=
mem_of_superset (inter_mem hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
lemma is_max_filter.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_filter f l a) {g : α → γ} (hg : is_max_filter g l a) :
is_max_filter (λ x, op (f x) (g x)) l a :=
mem_of_superset (inter_mem hf hg) $ λ x ⟨hfx, hgx⟩, hop hfx hgx
-- No `extr` version because we need `hf` and `hg` to be of the same kind
lemma is_min_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_min_on f s a) {g : α → γ} (hg : is_min_on g s a) :
is_min_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
lemma is_max_on.bicomp_mono [preorder δ] {op : β → γ → δ} (hop : ((≤) ⇒ (≤) ⇒ (≤)) op op)
(hf : is_max_on f s a) {g : α → γ} (hg : is_max_on g s a) :
is_max_on (λ x, op (f x) (g x)) s a :=
hf.bicomp_mono hop hg
/-! ### Composition with `tendsto` -/
lemma is_min_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_min_filter f l (g b))
(hg : tendsto g l' l) :
is_min_filter (f ∘ g) l' b :=
hg hf
lemma is_max_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ} (hf : is_max_filter f l (g b))
(hg : tendsto g l' l) :
is_max_filter (f ∘ g) l' b :=
hg hf
lemma is_extr_filter.comp_tendsto {g : δ → α} {l' : filter δ} {b : δ}
(hf : is_extr_filter f l (g b)) (hg : tendsto g l' l) :
is_extr_filter (f ∘ g) l' b :=
hf.elim (λ hf, (hf.comp_tendsto hg).is_extr) (λ hf, (hf.comp_tendsto hg).is_extr)
lemma is_min_on.on_preimage (g : δ → α) {b : δ} (hf : is_min_on f s (g b)) :
is_min_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_max_on.on_preimage (g : δ → α) {b : δ} (hf : is_max_on f s (g b)) :
is_max_on (f ∘ g) (g ⁻¹' s) b :=
hf.comp_tendsto (tendsto_principal_principal.mpr $ subset.refl _)
lemma is_extr_on.on_preimage (g : δ → α) {b : δ} (hf : is_extr_on f s (g b)) :
is_extr_on (f ∘ g) (g ⁻¹' s) b :=
hf.elim (λ hf, (hf.on_preimage g).is_extr) (λ hf, (hf.on_preimage g).is_extr)
end preorder
/-! ### Pointwise addition -/
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.add (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x + g x) l a :=
show is_min_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg
lemma is_max_filter.add (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x + g x) l a :=
show is_max_filter (λ x, f x + g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, add_le_add hx hy) hg
lemma is_min_on.add (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x + g x) s a :=
hf.add hg
lemma is_max_on.add (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x + g x) s a :=
hf.add hg
end ordered_add_comm_monoid
/-! ### Pointwise negation and subtraction -/
section ordered_add_comm_group
variables [ordered_add_comm_group β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.neg (hf : is_min_filter f l a) : is_max_filter (λ x, -f x) l a :=
hf.comp_antitone (λ x y hx, neg_le_neg hx)
lemma is_max_filter.neg (hf : is_max_filter f l a) : is_min_filter (λ x, -f x) l a :=
hf.comp_antitone (λ x y hx, neg_le_neg hx)
lemma is_extr_filter.neg (hf : is_extr_filter f l a) : is_extr_filter (λ x, -f x) l a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_on.neg (hf : is_min_on f s a) : is_max_on (λ x, -f x) s a :=
hf.comp_antitone (λ x y hx, neg_le_neg hx)
lemma is_max_on.neg (hf : is_max_on f s a) : is_min_on (λ x, -f x) s a :=
hf.comp_antitone (λ x y hx, neg_le_neg hx)
lemma is_extr_on.neg (hf : is_extr_on f s a) : is_extr_on (λ x, -f x) s a :=
hf.elim (λ hf, hf.neg.is_extr) (λ hf, hf.neg.is_extr)
lemma is_min_filter.sub (hf : is_min_filter f l a) (hg : is_max_filter g l a) :
is_min_filter (λ x, f x - g x) l a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_max_filter.sub (hf : is_max_filter f l a) (hg : is_min_filter g l a) :
is_max_filter (λ x, f x - g x) l a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_min_on.sub (hf : is_min_on f s a) (hg : is_max_on g s a) :
is_min_on (λ x, f x - g x) s a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
lemma is_max_on.sub (hf : is_max_on f s a) (hg : is_min_on g s a) :
is_max_on (λ x, f x - g x) s a :=
by simpa only [sub_eq_add_neg] using hf.add hg.neg
end ordered_add_comm_group
/-! ### Pointwise `sup`/`inf` -/
section semilattice_sup
variables [semilattice_sup β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.sup (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊔ g x) l a :=
show is_min_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_max_filter.sup (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊔ g x) l a :=
show is_max_filter (λ x, f x ⊔ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, sup_le_sup hx hy) hg
lemma is_min_on.sup (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
lemma is_max_on.sup (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊔ g x) s a :=
hf.sup hg
end semilattice_sup
section semilattice_inf
variables [semilattice_inf β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.inf (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, f x ⊓ g x) l a :=
show is_min_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_max_filter.inf (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, f x ⊓ g x) l a :=
show is_max_filter (λ x, f x ⊓ g x) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, inf_le_inf hx hy) hg
lemma is_min_on.inf (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
lemma is_max_on.inf (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, f x ⊓ g x) s a :=
hf.inf hg
end semilattice_inf
/-! ### Pointwise `min`/`max` -/
section linear_order
variables [linear_order β] {f g : α → β} {a : α} {s : set α} {l : filter α}
lemma is_min_filter.min (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, min (f x) (g x)) l a :=
show is_min_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_max_filter.min (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, min (f x) (g x)) l a :=
show is_max_filter (λ x, min (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, min_le_min hx hy) hg
lemma is_min_on.min (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_max_on.min (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, min (f x) (g x)) s a :=
hf.min hg
lemma is_min_filter.max (hf : is_min_filter f l a) (hg : is_min_filter g l a) :
is_min_filter (λ x, max (f x) (g x)) l a :=
show is_min_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_max_filter.max (hf : is_max_filter f l a) (hg : is_max_filter g l a) :
is_max_filter (λ x, max (f x) (g x)) l a :=
show is_max_filter (λ x, max (f x) (g x)) l a,
from hf.bicomp_mono (λ x x' hx y y' hy, max_le_max hx hy) hg
lemma is_min_on.max (hf : is_min_on f s a) (hg : is_min_on g s a) :
is_min_on (λ x, max (f x) (g x)) s a :=
hf.max hg
lemma is_max_on.max (hf : is_max_on f s a) (hg : is_max_on g s a) :
is_max_on (λ x, max (f x) (g x)) s a :=
hf.max hg
end linear_order
section eventually
/-! ### Relation with `eventually` comparisons of two functions -/
lemma filter.eventually_le.is_max_filter {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (hle : g ≤ᶠ[l] f) (hfga : f a = g a) (h : is_max_filter f l a) :
is_max_filter g l a :=
begin
refine hle.mp (h.mono $ λ x hf hgf, _),
rw ← hfga,
exact le_trans hgf hf
end
lemma is_max_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_max_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_max_filter g l a :=
heq.symm.le.is_max_filter hfga h
lemma filter.eventually_eq.is_max_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_max_filter f l a ↔ is_max_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
lemma filter.eventually_le.is_min_filter {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (hle : f ≤ᶠ[l] g) (hfga : f a = g a) (h : is_min_filter f l a) :
is_min_filter g l a :=
@filter.eventually_le.is_max_filter _ (order_dual β) _ _ _ _ _ hle hfga h
lemma is_min_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_min_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_min_filter g l a :=
heq.le.is_min_filter hfga h
lemma filter.eventually_eq.is_min_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_min_filter f l a ↔ is_min_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
lemma is_extr_filter.congr {α β : Type*} [preorder β] {f g : α → β} {a : α} {l : filter α}
(h : is_extr_filter f l a) (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_extr_filter g l a :=
begin
rw is_extr_filter at *,
rwa [← heq.is_max_filter_iff hfga, ← heq.is_min_filter_iff hfga],
end
lemma filter.eventually_eq.is_extr_filter_iff {α β : Type*} [preorder β] {f g : α → β} {a : α}
{l : filter α} (heq : f =ᶠ[l] g) (hfga : f a = g a) :
is_extr_filter f l a ↔ is_extr_filter g l a :=
⟨λ h, h.congr heq hfga, λ h, h.congr heq.symm hfga.symm⟩
end eventually
/-! ### `is_max_on`/`is_min_on` imply `csupr`/`cinfi` -/
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] {f : β → α} {s : set β} {x₀ : β}
lemma is_max_on.supr_eq (hx₀ : x₀ ∈ s) (h : is_max_on f s x₀) :
(⨆ x : s, f x) = f x₀ :=
begin
haveI : nonempty s := ⟨⟨x₀, hx₀⟩⟩,
exact csupr_eq_of_forall_le_of_forall_lt_exists_gt (λ x, h x.prop) (λ w hw, ⟨⟨x₀, hx₀⟩, hw⟩),
end
lemma is_min_on.infi_eq (hx₀ : x₀ ∈ s) (h : is_min_on f s x₀) :
(⨅ x : s, f x) = f x₀ :=
@is_max_on.supr_eq (order_dual α) β _ _ _ _ hx₀ h
end conditionally_complete_linear_order
|
61200bc8b430e233489fa309e5b89547b5f5f82b | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/colvec.lean | 4ef4a859ea2ec6777adf25990ef29e5d6584693f | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 14,852 | lean |
import tactic.interactive
import .mat .one_by_one_matrix
import tactic.transfer
import logic.relator
import .inner_product_space
-- TODO: move
namespace fin
open finset
lemma sum_image_succ_univ {α : Type} [comm_ring α] {n : nat} (f : fin (n + 1) → α) :
sum (image fin.succ univ) (λ x, f x) = sum univ (λ i, f (fin.succ i)) :=
begin
rw finset.sum_image,
intros _ _ _ _ h,
apply (eq_iff_veq _ _).2,
apply (eq_iff_veq _ _).1 (succ.inj h),
end
lemma image_succ_univ (n : nat) :
insert (⟨0, nat.zero_lt_succ n⟩ : fin (n + 1)) (image fin.succ (univ : finset (fin n)))
= (univ : finset (fin (n + 1))) :=
begin
apply subset.antisymm,
{ intros k hk,
rw mem_insert at hk,
apply or.elim hk (λ _, mem_univ) (λ _, mem_univ),
},
{ intros k _,
by_cases h_cases: k = ⟨0, nat.zero_lt_succ n⟩,
{ rw h_cases,
apply mem_insert_self _ },
{ apply mem_insert_of_mem,
rw mem_image,
use fin.pred k h_cases,
use mem_univ _,
apply succ_pred } }
end
lemma not_mem_image_succ_univ (n : nat) :
¬ (⟨0, nat.zero_lt_succ n⟩ : fin (n + 1)) ∈ image fin.succ (univ : finset (fin n)) :=
begin
intros h,
rw mem_image at h,
apply exists.elim h,
intros k hk,
apply exists.elim hk,
intros _ hk',
rw eq_iff_veq at hk',
simp at hk',
exact nat.succ_ne_zero _ hk'
end
lemma sum_succ {α : Type} [comm_ring α] {n : nat} (f : fin (n + 1) → α) :
finset.sum finset.univ (λ x : fin (n + 1), f x) = f ⟨0, nat.zero_lt_succ n⟩ + finset.sum finset.univ (λ x : fin n, f x.succ) :=
begin
rw [← sum_image_succ_univ],
rw [← image_succ_univ n],
rw sum_insert,
apply not_mem_image_succ_univ n
end
end fin
section transport
open tactic
@[user_attribute]
meta def to_rowvec_attr : user_attribute (name_map name) name :=
{ name := `to_rowvec,
descr := "Transport column vector to row vector",
cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do
val ← to_rowvec_attr.get_param n,
pure $ dict.insert n val) mk_name_map, []⟩,
parser := lean.parser.ident,
after_set := some $ λ src _ _, do
env ← get_env,
dict ← to_rowvec_attr.get_cache,
tgt ← to_rowvec_attr.get_param src,
(get_decl tgt >> skip) <|>
transport_with_dict dict src tgt }
end transport
def colvec (n : Type) [fintype n] (α : Type) : Type := matrix n (fin 1) α
def rowvec (n : Type) [fintype n] (α : Type) : Type := matrix (fin 1) n α
attribute [to_rowvec rowvec] colvec
section instances
variables {α : Type} {n : Type} [fintype n]
instance colvec.has_scalar [semiring α] : has_scalar α (colvec n α) := matrix.has_scalar
instance rowvec.has_scalar [semiring α] : has_scalar α (rowvec n α) := matrix.has_scalar
attribute [to_rowvec rowvec.has_scalar] colvec.has_scalar
instance colvec.has_add [has_add α] : has_add (colvec n α) := matrix.has_add
instance rowvec.has_add [has_add α] : has_add (rowvec n α) := matrix.has_add
attribute [to_rowvec rowvec.has_add] colvec.has_add
instance colvec.has_zero [has_zero α] : has_zero (colvec n α) := matrix.has_zero
instance rowvec.has_zero [has_zero α] : has_zero (rowvec n α) := matrix.has_zero
attribute [to_rowvec rowvec.has_zero] colvec.has_zero
instance colvec.add_comm_group [add_comm_group α] : add_comm_group (colvec n α) := matrix.add_comm_group
instance rowvec.add_comm_group [add_comm_group α] : add_comm_group (rowvec n α) := matrix.add_comm_group
attribute [to_rowvec rowvec.add_comm_group] colvec.add_comm_group
instance colvec.module [ring α] : module α (colvec n α) := matrix.module
instance rowvec.module [ring α] : module α (rowvec n α) := matrix.module
attribute [to_rowvec rowvec.add_comm_group] colvec.add_comm_group
def colvec.nth (x : colvec n α) (i : n) : α := x i 0
def rowvec.nth (x : rowvec n α) (i : n) : α := x 0 i
attribute [to_rowvec rowvec.nth] colvec.nth
def colvec.mk (f : n → α) : colvec n α := λ i j, f i
def rowvec.mk (f : n → α) : rowvec n α := λ i j, f j
attribute [to_rowvec rowvec.mk] colvec.mk
@[simp, to_rowvec rowvec.nth_mk]
lemma colvec.nth_mk (f : n → α) : colvec.nth (colvec.mk f) = f :=
by refl
@[simp, to_rowvec rowvec.nth_mk]
lemma colvec.nth_zero [has_zero α] (i : n): (0 : colvec n α).nth i = 0 :=
by refl
lemma colvec.eq_of_nth_eq (x : colvec n α) (y : colvec n α) (h : ∀i, x.nth i = y.nth i) : x = y :=
begin
ext i j,
rw fin.eq_zero_fin1 j,
apply h,
end
lemma rowvec.eq_of_nth_eq (x : rowvec n α) (y : rowvec n α) (h : ∀i, x.nth i = y.nth i) : x = y :=
begin
ext i j,
rw fin.eq_zero_fin1 i,
apply h,
end
attribute [to_rowvec rowvec.eq_of_nth_eq] colvec.eq_of_nth_eq
end instances
section inner
variables {α : Type} [has_mul α] [add_comm_monoid α] {n : Type} [fintype n]
def colvec.inner (v w : colvec n α) : α := (matrix.mul vᵀ w) 0 0
def rowvec.inner (v w : rowvec n α) : α := (matrix.mul v wᵀ) 0 0
end inner
section transfer
variables {α : Type} [has_mul α] [add_comm_monoid α] {n : Type} [fintype n]
open transfer
/- Set up relators for transfer tactic to transfer from colvec to rowvec -/
lemma colvec.rel_eq_inner {α : Type} [comm_ring α]:
((λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ (λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ @eq α) rowvec.inner colvec.inner :=
begin
intros x xt hx y yt hy,
unfold colvec.inner rowvec.inner,
rw [hy,←hx,matrix.transpose_transpose]
end
lemma colvec.rel_transpose_add {α : Type} [comm_ring α]:
((λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ (λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ (λ (x : rowvec n α) (y : colvec n α), xᵀ = y)) (+) (+) :=
begin
intros x xt hx y yt hy,
rw [←hx,←hy,matrix.transpose_add]
end
lemma relator.rel_eq_add {α : Type} [comm_ring α]:
((@eq α) ⇒ (@eq α) ⇒ (@eq α)) (+) (+) :=
begin
intros x x' hx y y' hy,
rw [hx,hy]
end
lemma relator.rel_le {α : Type} [has_le α] :
(@eq α ⇒ @eq α ⇒ (↔)) (≤) (≤) :=
λ _ _ h1 _ _ h2, by rw [h1, h2]
lemma relator.rel_pos {α : Type} [has_le α] [has_zero α] :
(@eq α ⇒ (↔)) (has_le.le 0) (has_le.le 0) :=
λ _ _ h, by rw [h]
lemma relator.rel_eq_const {α : Type} {a : rowvec n α} :
((@eq (rowvec n α))) (a) (a) := rfl
lemma relator.rel_eq_zero_transpose {α : Type} [has_zero α] :
((λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ (↔)) (eq 0) (eq 0) :=
begin
intros x y h,
convert matrix.eq_iff_transpose_eq _ _,
apply h.symm
end
lemma colvec.rel_smul_transpose {α : Type} [semiring α] (a : α) :
((λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒
(λ (x : rowvec n α) (y : colvec n α), xᵀ = y))
(has_scalar.smul a) (has_scalar.smul a) :=
λ _ _ h, by rw [matrix.transpose_smul,h]
lemma relator.rel_mul_const {α : Type} [has_mul α] (a : α) :
((=) ⇒ (=)) (has_mul.mul a) (has_mul.mul a) :=
λ _ _ h, by rw [h]
lemma relator.rel_eq_zero {α : Type} [has_zero α] :
((@eq α) ⇒ (↔)) (eq 0) (eq 0) :=
λ _ _ h, by rw [h]
-- TODO: move
lemma relator.rel_imp' : ((↔) ⇒ (↔) ⇒ (↔)) (→) (→) :=
λ _ _ h1 _ _ h2, by rw [h1, h2]
-- TODO: move
lemma relator.rel_eq_same {α : Type} : (@eq α ⇒ @eq α ⇒ (↔)) (=) (=) :=
begin
apply relator.rel_eq,
split,
exact λ a b c h1 h2, eq.trans h1 h2.symm,
exact λ a b c h1 h2, eq.trans h1.symm h2
end
instance colvec.bi_total_transpose : relator.bi_total (λ (x : rowvec n α) (y : colvec n α), xᵀ = y) :=
⟨λ x, ⟨xᵀ, eq.refl _⟩, λ x, ⟨xᵀ, matrix.transpose_transpose _⟩⟩
lemma colvec.rel_forall_transpose : (((λ (x : rowvec n α) (y : colvec n α), xᵀ = y) ⇒ iff) ⇒ iff) (λp, ∀i, p i) (λq, ∀i, q i) :=
by apply relator.rel_forall_of_total
meta def colvec.transfer : tactic unit :=
tactic.transfer [
`relator.rel_eq_zero_transpose,
`relator.rel_eq_zero,
`relator.rel_eq_same,
`relator.rel_eq_add,
`relator.rel_pos,
`relator.rel_imp',
`colvec.rel_forall_transpose,
`colvec.rel_eq_inner,
`colvec.rel_transpose_add,
`relator.rel_eq_const,
`colvec.rel_smul_transpose,
`relator.rel_mul_const
]
end transfer
section inner
variables {α : Type} [comm_ring α] {n : Type} [fintype n] (a : α) (x y z : colvec n α)
lemma colvec.inner_comm : x.inner y = y.inner x :=
begin
dsimp [colvec.inner, colvec, mat],
intros,
rw [←matrix.transpose_transpose ((matrix.transpose y).mul x), matrix.transpose_mul, matrix.transpose_transpose y],
refl
end
lemma rowvec.inner_comm : ∀ (x y : rowvec n α), x.inner y = y.inner x :=
begin colvec.transfer, exact colvec.inner_comm end
lemma colvec.inner_add_left : (x + y).inner z = x.inner z + y.inner z :=
by simp [colvec.inner, colvec, mat, matrix.transpose_add, matrix.add_mul']
lemma rowvec.inner_add_left : ∀ (x y z : rowvec n α), (x + y).inner z = x.inner z + y.inner z :=
begin colvec.transfer, exact colvec.inner_add_left end
lemma colvec.inner_smul_left : (a • x).inner y = a * x.inner y :=
by simp [colvec.inner, colvec, mat, matrix.smul_mul, matrix.transpose_smul]; refl
lemma rowvec.inner_smul_left (a : α) : ∀ (x y : rowvec n α), (a • x).inner y = a * x.inner y :=
begin colvec.transfer, exact colvec.inner_smul_left a end
end inner
section inner
variables {α : Type} [linear_ordered_comm_ring α] {m : Type} [fintype m] {n : Type} [fintype n] [decidable_eq n] (a : α) (x y z : colvec n α)
lemma colvec.inner_self_nonneg : 0 ≤ x.inner x :=
begin
dsimp [colvec.inner, colvec, mat, matrix.mul],
apply finset.sum_nonneg,
intros i _,
apply mul_self_nonneg
end
lemma rowvec.inner_self_nonneg : ∀ (x : rowvec n α), 0 ≤ x.inner x :=
begin colvec.transfer, exact colvec.inner_self_nonneg end
lemma colvec.eq_zero_of_inner_self_eq_zero : 0 = x.inner x → 0 = x :=
begin
dsimp [colvec.inner, colvec, mat, matrix.mul],
intros h,
apply colvec.eq_of_nth_eq,
intro i,
apply (eq_zero_of_mul_self_eq_zero ((finset.sum_eq_zero_iff_of_nonneg _).1 h.symm i (finset.mem_univ _))).symm,
intros i hi,
apply mul_self_nonneg
end
lemma rowvec.eq_zero_of_inner_self_eq_zero : ∀ (x : rowvec n α), 0 = x.inner x → 0 = x :=
begin colvec.transfer, exact colvec.eq_zero_of_inner_self_eq_zero end
local attribute [instance] classical.prop_decidable
noncomputable instance colvec.real_inner_product_space : real_inner_product_space (colvec n ℝ) :=
{
inner := colvec.inner,
inner_add_left := colvec.inner_add_left,
inner_smul_left := colvec.inner_smul_left,
inner_comm := colvec.inner_comm,
inner_self_nonneg := colvec.inner_self_nonneg,
eq_zero_of_inner_self_eq_zero := λ x h, (colvec.eq_zero_of_inner_self_eq_zero x h.symm).symm
}
noncomputable instance rowvec.real_inner_product_space : real_inner_product_space (rowvec n ℝ) :=
{
inner := rowvec.inner,
inner_add_left := rowvec.inner_add_left,
inner_smul_left := rowvec.inner_smul_left,
inner_comm := rowvec.inner_comm,
inner_self_nonneg := rowvec.inner_self_nonneg,
eq_zero_of_inner_self_eq_zero := λ x h, (rowvec.eq_zero_of_inner_self_eq_zero x h.symm).symm
}
lemma colvec.inner_eq_sum_nth :
x.inner y = finset.univ.sum (λi, x.nth i * y.nth i) :=
by unfold colvec.inner matrix.mul colvec.nth; refl
lemma rowvec.inner_eq_sum_nth (x : rowvec n α) (y : rowvec n α) :
x.inner y = finset.univ.sum (λi, x.nth i * y.nth i) :=
by unfold rowvec.inner matrix.mul colvec.nth; refl
attribute [to_rowvec rowvec.inner_eq_sum_nth] colvec.inner_eq_sum_nth
--TODO @[to_rowvec rowvec.inner_mul]
lemma colvec.inner_mul (A : matrix m n ℝ) (x : colvec n ℝ) (y : colvec m ℝ) :
⟪ x, Aᵀ.mul y ⟫ = ⟪ y, A.mul x ⟫ :=
begin
unfold has_inner.inner colvec.inner,
rw [←one_by_one_matrix.transpose ℝ (matrix.mul xᵀ (matrix.mul Aᵀ y)),
matrix.transpose_mul, matrix.transpose_mul, ←matrix.mul_assoc,
matrix.transpose_transpose, matrix.transpose_transpose]
end
end inner
section fin_index
variables {α : Type} {n : nat} (a : α) (x y z : colvec (fin n) α)
@[to_rowvec rowvec.head]
def colvec.head (x : colvec (fin (n+1)) α) : α := x.nth ⟨0, nat.zero_lt_succ n⟩
@[to_rowvec rowvec.tail]
def colvec.tail (x : colvec (fin (n+1)) α) : colvec (fin n) α :=
colvec.mk (λ i, x.nth ⟨i.1.succ, nat.succ_lt_succ i.2⟩)
@[to_rowvec rowvec.cons]
def colvec.cons (c : α) (x : colvec (fin n) α) : colvec (fin (n+1)) α :=
colvec.mk (λ i, dite (i.val = 0) (λ_, c) (λhi, x.nth ⟨i.val.pred,nat.pred_lt_pred hi i.2⟩))
@[simp, to_rowvec rowvec.head_smul]
lemma colvec.head_smul [semiring α] (c : α) (x : colvec (fin (n+1)) α) :
(c • x).head = c * x.head :=
by refl
@[simp, to_rowvec rowvec.tail_smul]
lemma colvec.tail_smul [semiring α] (c : α) (x : colvec (fin (n+1)) α) :
(c • x).tail = c • x.tail :=
by refl
@[simp, to_rowvec rowvec.head_cons]
lemma colvec.head_cons (c : α) (x : colvec (fin n) α) : (colvec.cons c x).head = c :=
by refl
-- TODO: get rid of this?
attribute [to_rowvec rowvec.head.equations._eqn_1] colvec.head.equations._eqn_1
attribute [to_rowvec rowvec.tail.equations._eqn_1] colvec.tail.equations._eqn_1
attribute [to_rowvec rowvec.cons.equations._eqn_1] colvec.cons.equations._eqn_1
@[simp, to_rowvec rowvec.tail_cons]
lemma colvec.tail_cons (x : colvec (fin n) α) (c : α) : (colvec.cons c x).tail = x :=
by apply colvec.eq_of_nth_eq; simp [colvec.tail,colvec.cons,nat.pred_succ,dif_eq_if, nat.succ_ne_zero]
@[simp, to_rowvec rowvec.cons_head_tail]
lemma colvec.cons_head_tail (x : colvec (fin (n+1)) α) : colvec.cons x.head x.tail = x :=
begin
apply colvec.eq_of_nth_eq,
intro i,
unfold colvec.cons colvec.head colvec.tail,
by_cases h_cases : i.val = 0,
{ have hi : i = ⟨0, nat.zero_lt_succ n⟩,
from (fin.eq_iff_veq _ _).2 h_cases,
simp [hi] },
{ simp [h_cases, nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero h_cases)] },
end
--TODO: @[to_rowvec rowvec.last]
lemma colvec.mul_head_add_mul_tail {α : Type} [comm_ring α] (x y : colvec (fin (n+1)) ℝ) :
x.head * y.head + ⟪ x.tail, y.tail ⟫ = ⟪ x, y ⟫ :=
begin
unfold has_inner.inner,
simp only [colvec.inner_eq_sum_nth],
unfold colvec.head colvec.tail,
rw fin.sum_succ (λ j : fin (n+1), x.nth j * y.nth j),
congr,
simp,
funext,
congr,
apply (fin.eq_iff_veq _ _).2,
simp,
apply (fin.eq_iff_veq _ _).2,
simp,
end
@[to_rowvec rowvec.last]
def colvec.last (x : colvec (fin (n+1)) α) : α := x.nth ⟨n, nat.lt_succ_self n⟩
@[to_rowvec rowvec.butlast]
def colvec.butlast (x : colvec (fin (n+1)) α) : colvec (fin n) α :=
colvec.mk (λ i, x.nth ⟨i.1, nat.le_succ_of_le i.2⟩)
@[to_rowvec rowvec.snoc]
def colvec.snoc (x : colvec (fin n) α) (c : α) : colvec (fin (n+1)) α :=
colvec.mk (λ i, dite (i.val < n) (λhi, x.nth ⟨i.val,hi⟩) (λ_, c))
--TODO: Lemmas about last, butlast, snoc
end fin_index
|
5278785986dc51b1f3b336e4876342266e7ceddc | 947b78d97130d56365ae2ec264df196ce769371a | /stage0/src/Init/Core.lean | 665c17f6ba3403131479e3a461ecc009360f3004 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 65,125 | 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
notation, basic datatypes and type classes
-/
prelude
notation `Prop` := Sort 0
reserve infixr ` $ `:1
notation f ` $ ` a := f a
/- Logical operations and relations -/
reserve prefix `¬`:40
reserve infixr ` ∧ `:35
reserve infixr ` /\ `:35
reserve infixr ` \/ `:30
reserve infixr ` ∨ `:30
reserve infix ` <-> `:20
reserve infix ` ↔ `:20
reserve infix ` = `:50
reserve infix ` == `:50
reserve infix ` != `:50
reserve infix ` ~= `:50
reserve infix ` ≅ `:50
reserve infix ` ≠ `:50
reserve infix ` ≈ `:50
reserve infixr ` ▸ `:75
/- types and Type constructors -/
reserve infixr ` × `:35
/- arithmetic operations -/
reserve infixl ` + `:65
reserve infixl ` - `:65
reserve infixl ` * `:70
reserve infixl ` / `:70
reserve infixl ` % `:70
reserve infixl ` %ₙ `:70
reserve prefix `-`:100
reserve infixr ` ^ `:80
reserve infixr ` ∘ `:90
reserve infix ` <= `:50
reserve infix ` ≤ `:50
reserve infix ` < `:50
reserve infix ` >= `:50
reserve infix ` ≥ `:50
reserve infix ` > `:50
/- boolean operations -/
reserve prefix `!`:40
reserve infixl ` && `:35
reserve infixl ` || `:30
/- other symbols -/
reserve infixl ` ++ `:65
reserve infixr ` :: `:67
/- Control -/
reserve infixr ` <|> `:2
reserve infixl ` >>= `:55
reserve infixr ` >=> `:55
reserve infixl ` <*> `:60
reserve infixl ` <* ` :60
reserve infixr ` *> ` :60
reserve infixr ` >> ` :60
reserve infixr ` <$> `:100
reserve infixl ` <&> `:100
universes u v w
/-- Auxiliary unsafe constant used by the Compiler when erasing proofs from code. -/
unsafe axiom lcProof {α : Prop} : α
/-- Auxiliary unsafe constant used by the Compiler to mark unreachable code. -/
unsafe axiom lcUnreachable {α : Sort u} : α
@[inline] def id {α : Sort u} (a : α) : α := a
def inline {α : Sort u} (a : α) : α := a
@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=
fun b a => f a b
/-
The kernel definitional equality test (t =?= s) has special support for idDelta applications.
It implements the following rules
1) (idDelta t) =?= t
2) t =?= (idDelta t)
3) (idDelta t) =?= s IF (unfoldOf t) =?= s
4) t =?= idDelta s IF t =?= (unfoldOf s)
This is mechanism for controlling the delta reduction (aka unfolding) used in the kernel.
We use idDelta applications to address performance problems when Type checking
theorems generated by the equation Compiler.
-/
@[inline] def idDelta {α : Sort u} (a : α) : α :=
a
/-- Gadget for optional parameter support. -/
@[reducible] def optParam (α : Sort u) (default : α) : Sort u :=
α
/-- Gadget for marking output parameters in type classes. -/
@[reducible] def outParam (α : Sort u) : Sort u := α
/-- Auxiliary Declaration used to implement the notation (a : α) -/
@[reducible] def typedExpr (α : Sort u) (a : α) : α := a
/- `idRhs` is an auxiliary Declaration used in the equation Compiler to address performance
issues when proving equational theorems. The equation Compiler uses it as a marker. -/
@[macroInline, reducible] def idRhs (α : Sort u) (a : α) : α := a
/-- Auxiliary Declaration used to implement the named patterns `x@p` -/
@[reducible] def namedPattern {α : Sort u} (x a : α) : α := a
inductive PUnit : Sort u
| unit : PUnit
/-- An abbreviation for `PUnit.{0}`, its most common instantiation.
This Type should be preferred over `PUnit` where possible to avoid
unnecessary universe parameters. -/
abbrev Unit : Type := PUnit
@[matchPattern] abbrev Unit.unit : Unit := PUnit.unit
/- Remark: thunks have an efficient implementation in the runtime. -/
structure Thunk (α : Type u) : Type u :=
(fn : Unit → α)
attribute [extern "lean_mk_thunk"] Thunk.mk
@[noinline, extern "lean_thunk_pure"]
protected def Thunk.pure {α : Type u} (a : α) : Thunk α :=
⟨fun _ => a⟩
@[noinline, extern "lean_thunk_get_own"]
protected def Thunk.get {α : Type u} (x : @& Thunk α) : α :=
x.fn ()
@[noinline, extern "lean_thunk_map"]
protected def Thunk.map {α : Type u} {β : Type v} (f : α → β) (x : Thunk α) : Thunk β :=
⟨fun _ => f x.get⟩
@[noinline, extern "lean_thunk_bind"]
protected def Thunk.bind {α : Type u} {β : Type v} (x : Thunk α) (f : α → Thunk β) : Thunk β :=
⟨fun _ => (f x.get).get⟩
inductive True : Prop
| intro : True
inductive False : Prop
inductive Empty : Type
def Not (a : Prop) : Prop := a → False
prefix `¬` := Not
inductive Eq {α : Sort u} (a : α) : α → Prop
| refl {} : Eq a
@[elabAsEliminator, inline, reducible]
def Eq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} (m : C a) {b : α} (h : Eq a b) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
@[elabAsEliminator, inline, reducible]
def Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : α → Sort u1} {b : α} (h : Eq a b) (m : C a) : C b :=
@Eq.rec α a (fun α _ => C α) m b h
/-
Initialize the Quotient Module, which effectively adds the following definitions:
constant Quot {α : Sort u} (r : α → α → Prop) : Sort u
constant Quot.mk {α : Sort u} (r : α → α → Prop) (a : α) : Quot r
constant Quot.lift {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) :
(∀ a b : α, r a b → Eq (f a) (f b)) → Quot r → β
constant Quot.ind {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} :
(∀ a : α, β (Quot.mk r a)) → ∀ q : Quot r, β q
-/
init_quot
inductive HEq {α : Sort u} (a : α) : ∀ {β : Sort u}, β → Prop
| refl {} : HEq a
structure Prod (α : Type u) (β : Type v) :=
(fst : α) (snd : β)
attribute [unbox] Prod
/-- Similar to `Prod`, but α and β can be propositions.
We use this Type internally to automatically generate the brecOn recursor. -/
structure PProd (α : Sort u) (β : Sort v) :=
(fst : α) (snd : β)
structure And (a b : Prop) : Prop :=
intro :: (left : a) (right : b)
structure Iff (a b : Prop) : Prop :=
intro :: (mp : a → b) (mpr : b → a)
/- Eq basic support -/
infix `=` := Eq
@[matchPattern] def rfl {α : Sort u} {a : α} : a = a := Eq.refl a
@[elabAsEliminator]
theorem Eq.subst {α : Sort u} {P : α → Prop} {a b : α} (h₁ : a = b) (h₂ : P a) : P b :=
Eq.ndrec h₂ h₁
infixr `▸` := Eq.subst
theorem Eq.trans {α : Sort u} {a b c : α} (h₁ : a = b) (h₂ : b = c) : a = c :=
h₂ ▸ h₁
theorem Eq.symm {α : Sort u} {a b : α} (h : a = b) : b = a :=
h ▸ rfl
infix `~=` := HEq
infix `≅` := HEq
@[matchPattern] def HEq.rfl {α : Sort u} {a : α} : a ≅ a := HEq.refl a
theorem eqOfHEq {α : Sort u} {a a' : α} (h : a ≅ a') : a = a' :=
have ∀ (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') (h₂ : α = α'), (Eq.recOn h₂ a : α') = a' :=
fun (α' : Sort u) (a' : α') (h₁ : @HEq α a α' a') => HEq.recOn h₁ (fun (h₂ : α = α) => rfl);
show (Eq.ndrecOn (Eq.refl α) a : α) = a' from
this α a' h (Eq.refl α)
inductive Sum (α : Type u) (β : Type v)
| inl (val : α) : Sum
| inr (val : β) : Sum
inductive PSum (α : Sort u) (β : Sort v)
| inl (val : α) : PSum
| inr (val : β) : PSum
inductive Or (a b : Prop) : Prop
| inl (h : a) : Or
| inr (h : b) : Or
def Or.introLeft {a : Prop} (b : Prop) (ha : a) : Or a b :=
Or.inl ha
def Or.introRight (a : Prop) {b : Prop} (hb : b) : Or a b :=
Or.inr hb
structure Sigma {α : Type u} (β : α → Type v) :=
mk :: (fst : α) (snd : β fst)
attribute [unbox] Sigma
structure PSigma {α : Sort u} (β : α → Sort v) :=
mk :: (fst : α) (snd : β fst)
inductive Bool : Type
| false : Bool
| true : Bool
/- Remark: Subtype must take a Sort instead of Type because of the axiom strongIndefiniteDescription. -/
structure Subtype {α : Sort u} (p : α → Prop) :=
(val : α) (property : p val)
inductive Exists {α : Sort u} (p : α → Prop) : Prop
| intro (w : α) (h : p w) : Exists
class inductive Decidable (p : Prop)
| isFalse (h : ¬p) : Decidable
| isTrue (h : p) : Decidable
abbrev DecidablePred {α : Sort u} (r : α → Prop) :=
∀ (a : α), Decidable (r a)
abbrev DecidableRel {α : Sort u} (r : α → α → Prop) :=
∀ (a b : α), Decidable (r a b)
abbrev DecidableEq (α : Sort u) :=
∀ (a b : α), Decidable (a = b)
def decEq {α : Sort u} [s : DecidableEq α] (a b : α) : Decidable (a = b) :=
s a b
inductive Option (α : Type u)
| none : Option
| some (val : α) : Option
attribute [unbox] Option
export Option (none some)
export Bool (false true)
inductive List (T : Type u)
| nil : List
| cons (hd : T) (tl : List) : List
infixr `::` := List.cons
inductive Nat
| zero : Nat
| succ (n : Nat) : Nat
/- Auxiliary axiom used to implement `sorry`.
TODO: add this theorem on-demand. That is,
we should only add it if after the first error. -/
axiom sorryAx (α : Sort u) (synthetic := true) : α
/- Declare builtin and reserved notation -/
class HasZero (α : Type u) := mk {} :: (zero : α)
class HasOne (α : Type u) := mk {} :: (one : α)
class HasAdd (α : Type u) := (add : α → α → α)
class HasMul (α : Type u) := (mul : α → α → α)
class HasNeg (α : Type u) := (neg : α → α)
class HasSub (α : Type u) := (sub : α → α → α)
class HasDiv (α : Type u) := (div : α → α → α)
class HasMod (α : Type u) := (mod : α → α → α)
class HasModN (α : Type u) := (modn : α → Nat → α)
class HasLessEq (α : Type u) := (LessEq : α → α → Prop)
class HasLess (α : Type u) := (Less : α → α → Prop)
class HasBeq (α : Type u) := (beq : α → α → Bool)
class HasAppend (α : Type u) := (append : α → α → α)
class HasOrelse (α : Type u) := (orelse : α → α → α)
class HasAndthen (α : Type u) := (andthen : α → α → α)
class HasEquiv (α : Sort u) := (Equiv : α → α → Prop)
class HasEmptyc (α : Type u) := (emptyc : α)
class HasPow (α : Type u) (β : Type v) :=
(pow : α → β → α)
infix `+` := HasAdd.add
infix `*` := HasMul.mul
infix `-` := HasSub.sub
infix `/` := HasDiv.div
infix `%` := HasMod.mod
infix `%ₙ` := HasModN.modn
prefix `-` := HasNeg.neg
infix `<=` := HasLessEq.LessEq
infix `≤` := HasLessEq.LessEq
infix `<` := HasLess.Less
infix `==` := HasBeq.beq
infix `++` := HasAppend.append
notation `∅` := HasEmptyc.emptyc
infix `≈` := HasEquiv.Equiv
infixr `^` := HasPow.pow
infixr `/\` := And
infixr `∧` := And
infixr `\/` := Or
infixr `∨` := Or
infix `<->` := Iff
infix `↔` := Iff
-- notation `exists` binders `, ` r:(scoped P, Exists P) := r
-- notation `∃` binders `, ` r:(scoped P, Exists P) := r
infixr `<|>` := HasOrelse.orelse
infixr `>>` := HasAndthen.andthen
@[reducible] def GreaterEq {α : Type u} [HasLessEq α] (a b : α) : Prop := HasLessEq.LessEq b a
@[reducible] def Greater {α : Type u} [HasLess α] (a b : α) : Prop := HasLess.Less b a
infix `>=` := GreaterEq
infix `≥` := GreaterEq
infix `>` := Greater
@[inline] def bit0 {α : Type u} [s : HasAdd α] (a : α) : α := a + a
@[inline] def bit1 {α : Type u} [s₁ : HasOne α] [s₂ : HasAdd α] (a : α) : α := (bit0 a) + 1
attribute [matchPattern] HasZero.zero HasOne.one bit0 bit1 HasAdd.add HasNeg.neg
/- Nat basic instances -/
@[extern "lean_nat_add"]
protected def Nat.add : (@& Nat) → (@& Nat) → Nat
| a, Nat.zero => a
| a, Nat.succ b => Nat.succ (Nat.add a b)
/- We mark the following definitions as pattern to make sure they can be used in recursive equations,
and reduced by the equation Compiler. -/
attribute [matchPattern] Nat.add Nat.add._main
instance : HasZero Nat := ⟨Nat.zero⟩
instance : HasOne Nat := ⟨Nat.succ (Nat.zero)⟩
instance : HasAdd Nat := ⟨Nat.add⟩
/- Auxiliary constant used by equation compiler. -/
constant hugeFuel : Nat := 10000
def std.priority.default : Nat := 1000
def std.priority.max : Nat := 0xFFFFFFFF
protected def Nat.prio := std.priority.default + 100
/-
Global declarations of right binding strength
If a Module reassigns these, it will be incompatible with other modules that adhere to these
conventions.
When hovering over a symbol, use "C-c C-k" to see how to input it.
-/
def std.prec.max : Nat := 1024 -- the strength of application, identifiers, (, [, etc.
def std.prec.arrow : Nat := 25
/-
The next def is "max + 10". It can be used e.g. for postfix operations that should
be stronger than application.
-/
def std.prec.maxPlus : Nat := std.prec.max + 10
/- Remark: tasks have an efficient implementation in the runtime. -/
structure Task (α : Type u) : Type u := pure ::
(get : α)
attribute [extern "lean_task_pure"] Task.pure
attribute [extern "lean_task_get_own"] Task.get
namespace Task
/-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/
abbrev Priority := Nat
def Priority.default : Priority := 0
-- see `LEAN_MAX_PRIO`
def Priority.max : Priority := 8
/--
Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.
This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more
non-dedicated workers than the number of cores to reduce context switches. -/
def Priority.dedicated : Priority := 9
@[noinline, extern "lean_task_spawn"]
protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α :=
⟨fn ()⟩
@[noinline, extern "lean_task_map"]
protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β :=
⟨f x.get⟩
@[noinline, extern "lean_task_bind"]
protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β :=
⟨(f x.get).get⟩
end Task
infixr `×` := Prod
-- notation for n-ary tuples
/- Some type that is not a scalar value in our runtime. -/
structure NonScalar :=
(val : Nat)
/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/
inductive PNonScalar : Type u
| mk (v : Nat) : PNonScalar
/- For numeric literals notation -/
class HasOfNat (α : Type u) :=
(ofNat : Nat → α)
export HasOfNat (ofNat)
instance : HasOfNat Nat :=
⟨id⟩
/- sizeof -/
class HasSizeof (α : Sort u) :=
(sizeof : α → Nat)
export HasSizeof (sizeof)
/-
Declare sizeof instances and theorems for types declared before HasSizeof.
From now on, the inductive Compiler will automatically generate sizeof instances and theorems.
-/
/- Every Type `α` has a default HasSizeof instance that just returns 0 for every element of `α` -/
protected def default.sizeof (α : Sort u) : α → Nat
| a => 0
instance defaultHasSizeof (α : Sort u) : HasSizeof α :=
⟨default.sizeof α⟩
protected def Nat.sizeof : Nat → Nat
| n => n
instance : HasSizeof Nat :=
⟨Nat.sizeof⟩
protected def Prod.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Prod α β) → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Prod α β) :=
⟨Prod.sizeof⟩
protected def Sum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (Sum α β) → Nat
| Sum.inl a => 1 + sizeof a
| Sum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (Sum α β) :=
⟨Sum.sizeof⟩
protected def PSum.sizeof {α : Type u} {β : Type v} [HasSizeof α] [HasSizeof β] : (PSum α β) → Nat
| PSum.inl a => 1 + sizeof a
| PSum.inr b => 1 + sizeof b
instance (α : Type u) (β : Type v) [HasSizeof α] [HasSizeof β] : HasSizeof (PSum α β) :=
⟨PSum.sizeof⟩
protected def Sigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : Sigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (Sigma β) :=
⟨Sigma.sizeof⟩
protected def PSigma.sizeof {α : Type u} {β : α → Type v} [HasSizeof α] [∀ a, HasSizeof (β a)] : PSigma β → Nat
| ⟨a, b⟩ => 1 + sizeof a + sizeof b
instance (α : Type u) (β : α → Type v) [HasSizeof α] [∀ a, HasSizeof (β a)] : HasSizeof (PSigma β) :=
⟨PSigma.sizeof⟩
protected def PUnit.sizeof : PUnit → Nat
| u => 1
instance : HasSizeof PUnit := ⟨PUnit.sizeof⟩
protected def Bool.sizeof : Bool → Nat
| b => 1
instance : HasSizeof Bool := ⟨Bool.sizeof⟩
protected def Option.sizeof {α : Type u} [HasSizeof α] : Option α → Nat
| none => 1
| some a => 1 + sizeof a
instance (α : Type u) [HasSizeof α] : HasSizeof (Option α) :=
⟨Option.sizeof⟩
protected def List.sizeof {α : Type u} [HasSizeof α] : List α → Nat
| List.nil => 1
| List.cons a l => 1 + sizeof a + List.sizeof l
instance (α : Type u) [HasSizeof α] : HasSizeof (List α) :=
⟨List.sizeof⟩
protected def Subtype.sizeof {α : Type u} [HasSizeof α] {p : α → Prop} : Subtype p → Nat
| ⟨a, _⟩ => sizeof a
instance {α : Type u} [HasSizeof α] (p : α → Prop) : HasSizeof (Subtype p) :=
⟨Subtype.sizeof⟩
theorem natAddZero (n : Nat) : n + 0 = n := rfl
theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl
/-- Like `by applyInstance`, but not dependent on the tactic framework. -/
@[reducible] def inferInstance {α : Type u} [i : α] : α := i
@[reducible, elabSimple] def inferInstanceAs (α : Type u) [i : α] : α := i
/- Boolean operators -/
@[macroInline] def cond {a : Type u} : Bool → a → a → a
| true, x, y => x
| false, x, y => y
@[inline] def condEq {β : Sort u} (b : Bool) (h₁ : b = true → β) (h₂ : b = false → β) : β :=
@Bool.casesOn (λ x => b = x → β) b h₂ h₁ rfl
@[macroInline] def or : Bool → Bool → Bool
| true, _ => true
| false, b => b
@[macroInline] def and : Bool → Bool → Bool
| false, _ => false
| true, b => b
@[macroInline] def not : Bool → Bool
| true => false
| false => true
@[macroInline] def xor : Bool → Bool → Bool
| true, b => not b
| false, b => b
prefix `!` := not
infix `||` := or
infix `&&` := and
@[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂
@[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂
@[inline] def bne {α : Type u} [HasBeq α] (a b : α) : Bool :=
!(a == b)
infix `!=` := bne
/- Logical connectives an equality -/
def implies (a b : Prop) := a → b
theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
fun hp => h₂ (h₁ hp)
def trivial : True := ⟨⟩
@[macroInline] def False.elim {C : Sort u} (h : False) : C :=
False.rec (fun _ => C) h
@[macroInline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b :=
False.elim (h₂ h₁)
theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=
fun ha => h₂ (h₁ ha)
theorem notFalse : ¬False := id
-- proof irrelevance is built in
theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl
theorem id.def {α : Sort u} (a : α) : id a = a := rfl
@[macroInline] def Eq.mp {α β : Sort u} (h₁ : α = β) (h₂ : α) : β :=
Eq.recOn h₁ h₂
@[macroInline] def Eq.mpr {α β : Sort u} : (α = β) → β → α :=
fun h₁ h₂ => Eq.recOn (Eq.symm h₁) h₂
@[elabAsEliminator]
theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=
Eq.subst (Eq.symm h₁) h₂
theorem congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ :=
Eq.subst h₁ (Eq.subst h₂ rfl)
theorem congrFun {α : Sort u} {β : α → Sort v} {f g : ∀ x, β x} (h : f = g) (a : α) : f a = g a :=
Eq.subst h (Eq.refl (f a))
theorem congrArg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) (h : a₁ = a₂) : f a₁ = f a₂ :=
congr rfl h
theorem transRelLeft {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c :=
h₂ ▸ h₁
theorem transRelRight {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c :=
h₁.symm ▸ h₂
theorem ofEqTrue {p : Prop} (h : p = True) : p :=
h.symm ▸ trivial
theorem notOfEqFalse {p : Prop} (h : p = False) : ¬p :=
fun hp => h ▸ hp
@[macroInline] def cast {α β : Sort u} (h : α = β) (a : α) : β :=
Eq.rec a h
theorem castProofIrrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl
theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl
@[reducible] def Ne {α : Sort u} (a b : α) := ¬(a = b)
infix `≠` := Ne
theorem Ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl
section Ne
variable {α : Sort u}
variables {a b : α} {p : Prop}
theorem Ne.intro (h : a = b → False) : a ≠ b := h
theorem Ne.elim (h : a ≠ b) : a = b → False := h
theorem Ne.irrefl (h : a ≠ a) : False := h rfl
theorem Ne.symm (h : a ≠ b) : b ≠ a :=
fun h₁ => h (h₁.symm)
theorem falseOfNe : a ≠ a → False := Ne.irrefl
theorem neFalseOfSelf : p → p ≠ False :=
fun (hp : p) (h : p = False) => h ▸ hp
theorem neTrueOfNot : ¬p → p ≠ True :=
fun (hnp : ¬p) (h : p = True) => (h ▸ hnp) trivial
theorem trueNeFalse : ¬True = False :=
neFalseOfSelf trivial
end Ne
theorem eqFalseOfNeTrue : ∀ {b : Bool}, b ≠ true → b = false
| true, h => False.elim (h rfl)
| false, h => rfl
theorem eqTrueOfNeFalse : ∀ {b : Bool}, b ≠ false → b = true
| true, h => rfl
| false, h => False.elim (h rfl)
theorem neFalseOfEqTrue : ∀ {b : Bool}, b = true → b ≠ false
| true, _ => fun h => Bool.noConfusion h
| false, h => Bool.noConfusion h
theorem neTrueOfEqFalse : ∀ {b : Bool}, b = false → b ≠ true
| true, h => Bool.noConfusion h
| false, _ => fun h => Bool.noConfusion h
section
variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}
@[elabAsEliminator]
theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} (m : C a) {β : Sort u2} {b : β} (h : a ≅ b) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
@[elabAsEliminator]
theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {C : ∀ {β : Sort u2}, β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : C a) : C b :=
@HEq.rec α a (fun β b _ => C b) m β b h
theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b :=
Eq.recOn (eqOfHEq h₁) h₂
theorem HEq.subst {p : ∀ (T : Sort u), T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b :=
HEq.ndrecOn h₁ h₂
theorem HEq.symm (h : a ≅ b) : b ≅ a :=
HEq.ndrecOn h (HEq.refl a)
theorem heqOfEq (h : a = a') : a ≅ a' :=
Eq.subst h (HEq.refl a)
theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c :=
HEq.subst h₂ h₁
theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' :=
HEq.trans h₁ (heqOfEq h₂)
theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b :=
HEq.trans (heqOfEq h₁) h₂
def typeEqOfHEq (h : a ≅ b) : α = β :=
HEq.ndrecOn h (Eq.refl α)
end
theorem eqRecHEq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (Eq.recOn h p : φ a') ≅ p
| a, _, rfl, p => HEq.refl p
theorem ofHEqTrue {a : Prop} (h : a ≅ True) : a :=
ofEqTrue (eqOfHEq h)
theorem castHEq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a ≅ a
| α, _, rfl, a => HEq.refl a
variables {a b c d : Prop}
theorem And.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c :=
And.rec h₂ h₁
theorem And.swap : a ∧ b → b ∧ a :=
fun ⟨ha, hb⟩ => ⟨hb, ha⟩
def And.symm := @And.swap
theorem Or.elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c :=
Or.rec h₂ h₃ h₁
theorem Or.swap (h : a ∨ b) : b ∨ a :=
Or.elim h Or.inr Or.inl
def Or.symm := @Or.swap
/- xor -/
def Xor (a b : Prop) : Prop := (a ∧ ¬ b) ∨ (b ∧ ¬ a)
@[recursor 5]
theorem Iff.elim (h₁ : (a → b) → (b → a) → c) (h₂ : a ↔ b) : c :=
Iff.rec h₁ h₂
theorem Iff.left : (a ↔ b) → a → b := Iff.mp
theorem Iff.right : (a ↔ b) → b → a := Iff.mpr
theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)
theorem Iff.refl (a : Prop) : a ↔ a :=
Iff.intro (fun h => h) (fun h => h)
theorem Iff.rfl {a : Prop} : a ↔ a :=
Iff.refl a
theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=
Iff.intro
(fun ha => Iff.mp h₂ (Iff.mp h₁ ha))
(fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))
theorem Iff.symm (h : a ↔ b) : b ↔ a :=
Iff.intro (Iff.right h) (Iff.left h)
theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=
Iff.intro Iff.symm Iff.symm
theorem Eq.toIff {a b : Prop} (h : a = b) : a ↔ b :=
Eq.recOn h Iff.rfl
theorem neqOfNotIff {a b : Prop} : ¬(a ↔ b) → a ≠ b :=
fun h₁ h₂ =>
have a ↔ b from Eq.subst h₂ (Iff.refl a);
absurd this h₁
theorem notIffNotOfIff (h₁ : a ↔ b) : ¬a ↔ ¬b :=
Iff.intro
(fun (hna : ¬ a) (hb : b) => hna (Iff.right h₁ hb))
(fun (hnb : ¬ b) (ha : a) => hnb (Iff.left h₁ ha))
theorem ofIffTrue (h : a ↔ True) : a :=
Iff.mp (Iff.symm h) trivial
theorem notOfIffFalse : (a ↔ False) → ¬a := Iff.mp
theorem iffTrueIntro (h : a) : a ↔ True :=
Iff.intro
(fun hl => trivial)
(fun hr => h)
theorem iffFalseIntro (h : ¬a) : a ↔ False :=
Iff.intro h (False.rec (fun _ => a))
theorem notNotIntro (ha : a) : ¬¬a :=
fun hna => hna ha
theorem notTrue : (¬ True) ↔ False :=
iffFalseIntro (notNotIntro trivial)
/- or resolution rulses -/
theorem resolveLeft {a b : Prop} (h : a ∨ b) (na : ¬ a) : b :=
Or.elim h (fun ha => absurd ha na) id
theorem negResolveLeft {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b :=
Or.elim h (fun na => absurd ha na) id
theorem resolveRight {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a :=
Or.elim h id (fun hb => absurd hb nb)
theorem negResolveRight {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a :=
Or.elim h id (fun nb => absurd hb nb)
/- Exists -/
theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}
(h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=
Exists.rec h₂ h₁
/- Decidable -/
@[inlineIfReduce, nospecialize] def Decidable.decide (p : Prop) [h : Decidable p] : Bool :=
Decidable.casesOn h (fun h₁ => false) (fun h₂ => true)
export Decidable (isTrue isFalse decide)
instance beqOfEq {α : Type u} [DecidableEq α] : HasBeq α :=
⟨fun a b => decide (a = b)⟩
theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=
match h with
| isTrue h => rfl
| isFalse h => False.elim (Iff.mp notTrue h)
theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=
match h with
| isFalse h => rfl
| isTrue h => False.elim h
theorem decideEqTrue : ∀ {p : Prop} [s : Decidable p], p → decide p = true
| _, isTrue _, _ => rfl
| _, isFalse h₁, h₂ => absurd h₂ h₁
theorem decideEqFalse : ∀ {p : Prop} [s : Decidable p], ¬p → decide p = false
| _, isTrue h₁, h₂ => absurd h₁ h₂
| _, isFalse h, _ => rfl
theorem ofDecideEqTrue {p : Prop} [s : Decidable p] : decide p = true → p :=
fun h => match s with
| isTrue h₁ => h₁
| isFalse h₁ => absurd h (neTrueOfEqFalse (decideEqFalse h₁))
theorem ofDecideEqFalse {p : Prop} [s : Decidable p] : decide p = false → ¬p :=
fun h => match s with
| isTrue h₁ => absurd h (neFalseOfEqTrue (decideEqTrue h₁))
| isFalse h₁ => h₁
/-- Similar to `decide`, but uses an explicit instance -/
@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=
@decide p d
theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=
@decideEqTrue _ d h
theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=
@ofDecideEqTrue _ d h
theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=
@ofDecideEqFalse _ d h
instance : Decidable True :=
isTrue trivial
instance : Decidable False :=
isFalse notFalse
-- We use "dependent" if-then-else to be able to communicate the if-then-else condition
-- to the branches
@[macroInline] def dite {α : Sort u} (c : Prop) [h : Decidable c] : (c → α) → (¬ c → α) → α :=
fun t e => Decidable.casesOn h e t
/- if-then-else -/
@[macroInline] def ite {α : Sort u} (c : Prop) [h : Decidable c] (t e : α) : α :=
Decidable.casesOn h (fun hnc => e) (fun hc => t)
namespace Decidable
variables {p q : Prop}
def recOnTrue [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => False.rec _ (h h₃)) (fun h => h₄)
def recOnFalse [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃)
: (Decidable.recOn h h₂ h₁ : Sort u) :=
Decidable.casesOn h (fun h => h₄) (fun h => False.rec _ (h₃ h))
@[macroInline] def byCases {q : Sort u} [s : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=
match s with
| isTrue h => h1 h
| isFalse h => h2 h
theorem em (p : Prop) [Decidable p] : p ∨ ¬p :=
byCases Or.inl Or.inr
theorem byContradiction [Decidable p] (h : ¬p → False) : p :=
byCases id (fun np => False.elim (h np))
theorem ofNotNot [Decidable p] : ¬ ¬ p → p :=
fun hnn => byContradiction (fun hn => absurd hn hnn)
theorem notNotIff (p) [Decidable p] : (¬ ¬ p) ↔ p :=
Iff.intro ofNotNot notNotIntro
theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=
Iff.intro
(fun h => match d₁, d₂ with
| isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h
| _, isFalse h₂ => Or.inr h₂
| isFalse h₁, _ => Or.inl h₁)
(fun (h) ⟨hp, hq⟩ => Or.elim h (fun h => h hp) (fun h => h hq))
end Decidable
section
variables {p q : Prop}
@[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q :=
if hp : p then isTrue (Iff.mp h hp)
else isFalse (Iff.mp (notIffNotOfIff h) hp)
@[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=
decidableOfDecidableOfIff hp h.toIff
end
section
variables {p q : Prop}
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∧ q) :=
if hp : p then
if hq : q then isTrue ⟨hp, hq⟩
else isFalse (fun h => hq (And.right h))
else isFalse (fun h => hp (And.left h))
@[macroInline] instance [Decidable p] [Decidable q] : Decidable (p ∨ q) :=
if hp : p then isTrue (Or.inl hp) else
if hq : q then isTrue (Or.inr hq) else
isFalse (fun h => Or.elim h hp hq)
instance [Decidable p] : Decidable (¬p) :=
if hp : p then isFalse (absurd hp) else isTrue hp
@[macroInline] instance implies.Decidable [Decidable p] [Decidable q] : Decidable (p → q) :=
if hp : p then
if hq : q then isTrue (fun h => hq)
else isFalse (fun h => absurd (h hp) hq)
else isTrue (fun h => absurd h hp)
instance [Decidable p] [Decidable q] : Decidable (p ↔ q) :=
if hp : p then
if hq : q then isTrue ⟨fun _ => hq, fun _ => hp⟩
else isFalse $ fun h => hq (h.1 hp)
else
if hq : q then isFalse $ fun h => hp (h.2 hq)
else isTrue $ ⟨fun h => absurd h hp, fun h => absurd h hq⟩
instance [Decidable p] [Decidable q] : Decidable (Xor p q) :=
if hp : p then
if hq : q then isFalse (fun h => Or.elim h (fun ⟨_, h⟩ => h hq : ¬(p ∧ ¬ q)) (fun ⟨_, h⟩ => h hp : ¬(q ∧ ¬ p)))
else isTrue $ Or.inl ⟨hp, hq⟩
else
if hq : q then isTrue $ Or.inr ⟨hq, hp⟩
else isFalse (fun h => Or.elim h (fun ⟨h, _⟩ => hp h : ¬(p ∧ ¬ q)) (fun ⟨h, _⟩ => hq h : ¬(q ∧ ¬ p)))
end
@[inline] instance {α : Sort u} [DecidableEq α] (a b : α) : Decidable (a ≠ b) :=
match decEq a b with
| isTrue h => isFalse $ fun h' => absurd h h'
| isFalse h => isTrue h
theorem Bool.falseNeTrue (h : false = true) : False :=
Bool.noConfusion h
@[inline] instance : DecidableEq Bool :=
fun a b => match a, b with
| false, false => isTrue rfl
| false, true => isFalse Bool.falseNeTrue
| true, false => isFalse (Ne.symm Bool.falseNeTrue)
| true, true => isTrue rfl
/- if-then-else expression theorems -/
theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => absurd hc hnc
theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=
match h with
| (isTrue hc) => absurd hc hnc
| (isFalse hnc) => rfl
-- Remark: dite and ite are "defally equal" when we ignore the proofs.
theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e :=
match h with
| (isTrue hc) => rfl
| (isFalse hnc) => rfl
instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=
match dC with
| (isTrue hc) => dT
| (isFalse hc) => dE
instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=
match dC with
| (isTrue hc) => dT hc
| (isFalse hc) => dE hc
/-- Universe lifting operation -/
structure ULift.{r, s} (α : Type s) : Type (max s r) :=
up :: (down : α)
namespace ULift
/- Bijection between α and ULift.{v} α -/
theorem upDown {α : Type u} : ∀ (b : ULift.{v} α), up (down b) = b
| up a => rfl
theorem downUp {α : Type u} (a : α) : down (up.{v} a) = a := rfl
end ULift
/-- Universe lifting operation from Sort to Type -/
structure PLift (α : Sort u) : Type u :=
up :: (down : α)
namespace PLift
/- Bijection between α and PLift α -/
theorem upDown {α : Sort u} : ∀ (b : PLift α), up (down b) = b
| up a => rfl
theorem downUp {α : Sort u} (a : α) : down (up a) = a := rfl
end PLift
/- pointed types -/
structure PointedType :=
(type : Type u) (val : type)
/- Inhabited -/
class Inhabited (α : Sort u) :=
mk {} :: (default : α)
constant arbitrary (α : Sort u) [Inhabited α] : α :=
Inhabited.default α
instance Prop.Inhabited : Inhabited Prop :=
⟨True⟩
instance Fun.Inhabited (α : Sort u) {β : Sort v} [h : Inhabited β] : Inhabited (α → β) :=
Inhabited.casesOn h (fun b => ⟨fun a => b⟩)
instance Forall.Inhabited (α : Sort u) {β : α → Sort v} [∀ x, Inhabited (β x)] : Inhabited (∀ x, β x) :=
⟨fun a => arbitrary (β a)⟩
instance : Inhabited Bool := ⟨false⟩
instance : Inhabited True := ⟨trivial⟩
instance : Inhabited Nat := ⟨0⟩
instance : Inhabited NonScalar := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PNonScalar.{u} := ⟨⟨arbitrary _⟩⟩
instance : Inhabited PointedType := ⟨{type := PUnit, val := ⟨⟩}⟩
class inductive Nonempty (α : Sort u) : Prop
| intro (val : α) : Nonempty
protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p :=
Nonempty.rec h₂ h₁
instance nonemptyOfInhabited {α : Sort u} [Inhabited α] : Nonempty α :=
⟨arbitrary α⟩
theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α
| ⟨w, h⟩ => ⟨w⟩
/- Subsingleton -/
class inductive Subsingleton (α : Sort u) : Prop
| intro (h : ∀ (a b : α), a = b) : Subsingleton
protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : ∀ (a b : α), a = b :=
Subsingleton.casesOn h (fun p => p)
protected def Subsingleton.helim {α β : Sort u} [h : Subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a ≅ b :=
Eq.recOn h (fun a b => heqOfEq (Subsingleton.elim a b))
instance subsingletonProp (p : Prop) : Subsingleton p :=
⟨fun a b => proofIrrel a b⟩
instance (p : Prop) : Subsingleton (Decidable p) :=
Subsingleton.intro $ fun d₁ =>
match d₁ with
| (isTrue t₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => Eq.recOn (proofIrrel t₁ t₂) rfl
| (isFalse f₂) => absurd t₁ f₂
| (isFalse f₁) => fun d₂ =>
match d₂ with
| (isTrue t₂) => absurd t₂ f₁
| (isFalse f₂) => Eq.recOn (proofIrrel f₁ f₂) rfl
protected theorem recSubsingleton {p : Prop} [h : Decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u}
[h₃ : ∀ (h : p), Subsingleton (h₁ h)] [h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]
: Subsingleton (Decidable.casesOn h h₂ h₁) :=
match h with
| (isTrue h) => h₃ h
| (isFalse h) => h₄ h
section relation
variables {α : Sort u} {β : Sort v} (r : β → β → Prop)
def Reflexive := ∀ x, r x x
def Symmetric := ∀ {x y}, r x y → r y x
def Transitive := ∀ {x y z}, r x y → r y z → r x z
def Equivalence := Reflexive r ∧ Symmetric r ∧ Transitive r
def Total := ∀ x y, r x y ∨ r y x
def mkEquivalence (rfl : Reflexive r) (symm : Symmetric r) (trans : Transitive r) : Equivalence r :=
⟨rfl, @symm, @trans⟩
def Irreflexive := ∀ x, ¬ r x x
def AntiSymmetric := ∀ {x y}, r x y → r y x → x = y
def emptyRelation (a₁ a₂ : α) : Prop := False
def Subrelation (q r : β → β → Prop) := ∀ {x y}, q x y → r x y
def InvImage (f : α → β) : α → α → Prop :=
fun a₁ a₂ => r (f a₁) (f a₂)
theorem InvImage.Transitive (f : α → β) (h : Transitive r) : Transitive (InvImage r f) :=
fun (a₁ a₂ a₃ : α) (h₁ : InvImage r f a₁ a₂) (h₂ : InvImage r f a₂ a₃) => h h₁ h₂
theorem InvImage.Irreflexive (f : α → β) (h : Irreflexive r) : Irreflexive (InvImage r f) :=
fun (a : α) (h₁ : InvImage r f a a) => h (f a) h₁
inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop
| base : ∀ a b, r a b → TC a b
| trans : ∀ a b c, TC a b → TC b c → TC a c
@[elabAsEliminator]
theorem TC.ndrec.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
{a b : α} (h : TC r a b) : C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
@[elabAsEliminator]
theorem TC.ndrecOn.{u1, u2} {α : Sort u} {r : α → α → Prop} {C : α → α → Prop}
{a b : α} (h : TC r a b)
(m₁ : ∀ (a b : α), r a b → C a b)
(m₂ : ∀ (a b c : α), TC r a b → TC r b c → C a b → C b c → C a c)
: C a b :=
@TC.rec α r (fun a b _ => C a b) m₁ m₂ a b h
end relation
section Binary
variables {α : Type u} {β : Type v}
variable (f : α → α → α)
def Commutative := ∀ a b, f a b = f b a
def Associative := ∀ a b c, f (f a b) c = f a (f b c)
def RightCommutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁
def LeftCommutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b)
theorem leftComm : Commutative f → Associative f → LeftCommutative f :=
fun hcomm hassoc a b c =>
((Eq.symm (hassoc a b c)).trans (hcomm a b ▸ rfl : f (f a b) c = f (f b a) c)).trans (hassoc b a c)
theorem rightComm : Commutative f → Associative f → RightCommutative f :=
fun hcomm hassoc a b c =>
((hassoc a b c).trans (hcomm b c ▸ rfl : f a (f b c) = f a (f c b))).trans (Eq.symm (hassoc a c b))
end Binary
/- Subtype -/
namespace Subtype
def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)
| ⟨a, h⟩ => ⟨a, h⟩
variables {α : Type u} {p : α → Prop}
theorem tagIrrelevant {a : α} (h1 h2 : p a) : mk a h1 = mk a h2 :=
rfl
protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩, ⟨.(x), h2⟩, rfl => rfl
theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a :=
Subtype.eq rfl
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} :=
⟨⟨a, h⟩⟩
instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=
fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>
if h : a = b then isTrue (Subtype.eq h)
else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))
end Subtype
/- Sum -/
section
variables {α : Type u} {β : Type v}
instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) :=
⟨Sum.inl (arbitrary α)⟩
instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) :=
⟨Sum.inr (arbitrary β)⟩
instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) :=
fun a b =>
match a, b with
| (Sum.inl a), (Sum.inl b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inr b) =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse (fun h' => Sum.noConfusion h' (fun h' => absurd h' h))
| (Sum.inr a), (Sum.inl b) => isFalse (fun h => Sum.noConfusion h)
| (Sum.inl a), (Sum.inr b) => isFalse (fun h => Sum.noConfusion h)
end
/- Product -/
section
variables {α : Type u} {β : Type v}
instance [Inhabited α] [Inhabited β] : Inhabited (Prod α β) :=
⟨(arbitrary α, arbitrary β)⟩
instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=
fun ⟨a, b⟩ ⟨a', b'⟩ =>
match (decEq a a') with
| (isTrue e₁) =>
match (decEq b b') with
| (isTrue e₂) => isTrue (Eq.recOn e₁ (Eq.recOn e₂ rfl))
| (isFalse n₂) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₂' n₂))
| (isFalse n₁) => isFalse (fun h => Prod.noConfusion h (fun e₁' e₂' => absurd e₁' n₁))
instance [HasBeq α] [HasBeq β] : HasBeq (α × β) :=
⟨fun ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ => a₁ == a₂ && b₁ == b₂⟩
instance [HasLess α] [HasLess β] : HasLess (α × β) :=
⟨fun s t => s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)⟩
instance prodHasDecidableLt
[HasLess α] [HasLess β] [DecidableEq α] [DecidableEq β]
[∀ (a b : α), Decidable (a < b)] [∀ (a b : β), Decidable (a < b)]
: ∀ (s t : α × β), Decidable (s < t) :=
fun t s => Or.Decidable
theorem Prod.ltDef [HasLess α] [HasLess β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=
rfl
end
def Prod.map.{u₁, u₂, v₁, v₂} {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}
(f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂
| (a, b) => (f a, g b)
/- Dependent products -/
-- notation `Σ` binders `, ` r:(scoped p, Sigma p) := r
-- notation `Σ'` binders `, ` r:(scoped p, PSigma p) := r
theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)
| ⟨x, hx⟩ => ⟨x, hx⟩
section
variables {α : Type u} {β : α → Type v}
protected theorem Sigma.eq : ∀ {p₁ p₂ : Sigma (fun a => β a)} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
section
variables {α : Sort u} {β : α → Sort v}
protected theorem PSigma.eq : ∀ {p₁ p₂ : PSigma β} (h₁ : p₁.1 = p₂.1), (Eq.recOn h₁ p₁.2 : β p₂.1) = p₂.2 → p₁ = p₂
| ⟨a, b⟩, ⟨.(a), .(b)⟩, rfl, rfl => rfl
end
/- Universe polymorphic unit -/
theorem punitEq (a b : PUnit) : a = b :=
PUnit.recOn a (PUnit.recOn b rfl)
theorem punitEqPUnit (a : PUnit) : a = () :=
punitEq a ()
instance : Subsingleton PUnit :=
Subsingleton.intro punitEq
instance : Inhabited PUnit :=
⟨⟨⟩⟩
instance : DecidableEq PUnit :=
fun a b => isTrue (punitEq a b)
/- Setoid -/
class Setoid (α : Sort u) :=
(r : α → α → Prop) (iseqv {} : Equivalence r)
instance setoidHasEquiv {α : Sort u} [Setoid α] : HasEquiv α :=
⟨Setoid.r⟩
namespace Setoid
variables {α : Sort u} [Setoid α]
theorem refl (a : α) : a ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hRefl a
theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hSymm hab
theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
match Setoid.iseqv α with
| ⟨hRefl, hSymm, hTrans⟩ => hTrans hab hbc
end Setoid
/- Propositional extensionality -/
axiom propext {a b : Prop} : (a ↔ b) → a = b
theorem eqTrueIntro {a : Prop} (h : a) : a = True :=
propext (iffTrueIntro h)
theorem eqFalseIntro {a : Prop} (h : ¬a) : a = False :=
propext (iffFalseIntro h)
/- Quotients -/
-- Iff can now be used to do substitutions in a calculation
theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=
Eq.subst (propext h₁) h₂
namespace Quot
axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b
attribute [elabAsEliminator] lift ind
protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v} (f : α → β) (c : ∀ a b, r a b → f a = f b) (a : α) : lift f c (Quot.mk r a) = f a :=
rfl
protected theorem indBeta {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (p : ∀ a, β (Quot.mk r a)) (a : α) : (ind p (Quot.mk r a) : β (Quot.mk r a)) = p a :=
rfl
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : ∀ a b, r a b → f a = f b) : β :=
lift f c q
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {β : Quot r → Prop} (q : Quot r) (h : ∀ a, β (Quot.mk r a)) : β q :=
ind h q
theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=
Quot.inductionOn q (fun a => ⟨a, rfl⟩)
section
variable {α : Sort u}
variable {r : α → α → Prop}
variable {β : Quot r → Sort v}
@[reducible, macroInline]
protected def indep (f : ∀ a, β (Quot.mk r a)) (a : α) : PSigma β :=
⟨Quot.mk r a, f a⟩
protected theorem indepCoherent (f : ∀ a, β (Quot.mk r a))
(h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
: ∀ a b, r a b → Quot.indep f a = Quot.indep f b :=
fun a b e => PSigma.eq (sound e) (h a b e)
protected theorem liftIndepPr1
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q :=
Quot.ind (fun (a : α) => Eq.refl (Quot.indep f a).1) q
@[reducible, elabAsEliminator, inline]
protected def rec
(f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b)
(q : Quot r) : β q :=
Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (h : ∀ (a b : α) (p : r a b), (Eq.rec (f a) (sound p) : β (Quot.mk r b)) = f b) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quot.mk r a))] (q : Quot r) (f : ∀ a, β (Quot.mk r a)) : β q :=
Quot.rec f (fun a b h => Subsingleton.elim _ (f b)) q
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quot r) (f : ∀ a, β (Quot.mk r a)) (c : ∀ (a b : α) (p : r a b), f a ≅ f b) : β q :=
Quot.recOn q f $
fun a b p => eqOfHEq $
have p₁ : (Eq.rec (f a) (sound p) : β (Quot.mk r b)) ≅ f a := eqRecHEq (sound p) (f a);
HEq.trans p₁ (c a b p)
end
end Quot
def Quotient {α : Sort u} (s : Setoid α) :=
@Quot α Setoid.r
namespace Quotient
@[inline]
protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=
Quot.mk Setoid.r a
def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b :=
Quot.sound
@[reducible, elabAsEliminator]
protected def lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : (∀ a b, a ≈ b → f a = f b) → Quotient s → β :=
Quot.lift f
@[elabAsEliminator]
protected theorem ind {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} : (∀ a, β (Quotient.mk a)) → ∀ q, β q :=
Quot.ind
@[reducible, elabAsEliminator, inline]
protected def liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : ∀ a b, a ≈ b → f a = f b) : β :=
Quot.liftOn q f c
@[elabAsEliminator]
protected theorem inductionOn {α : Sort u} [s : Setoid α] {β : Quotient s → Prop} (q : Quotient s) (h : ∀ a, β (Quotient.mk a)) : β q :=
Quot.inductionOn q h
theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) :=
Quot.existsRep q
section
variable {α : Sort u}
variable [s : Setoid α]
variable {β : Quotient s → Sort v}
@[inline]
protected def rec
(f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b)
(q : Quotient s) : β q :=
Quot.rec f h q
@[reducible, elabAsEliminator, inline]
protected def recOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (h : ∀ (a b : α) (p : a ≈ b), (Eq.rec (f a) (Quotient.sound p) : β (Quotient.mk b)) = f b) : β q :=
Quot.recOn q f h
@[reducible, elabAsEliminator, inline]
protected def recOnSubsingleton
[h : ∀ a, Subsingleton (β (Quotient.mk a))] (q : Quotient s) (f : ∀ a, β (Quotient.mk a)) : β q :=
@Quot.recOnSubsingleton _ _ _ h q f
@[reducible, elabAsEliminator, inline]
protected def hrecOn
(q : Quotient s) (f : ∀ a, β (Quotient.mk a)) (c : ∀ (a b : α) (p : a ≈ b), f a ≅ f b) : β q :=
Quot.hrecOn q f c
end
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB} {φ : Sort uC}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator, inline]
protected def lift₂
(f : α → β → φ)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂)
(q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ :=
Quotient.lift
(fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂)
(fun (a b : α) (h : a ≈ b) =>
@Quotient.ind β s₂
(fun (a1 : Quotient s₂) =>
(Quotient.lift (f a) (fun (a1 b : β) => c a a1 a b (Setoid.refl a)) a1)
=
(Quotient.lift (f b) (fun (a b1 : β) => c b a b b1 (Setoid.refl b)) a1))
(fun (a' : β) => c a a' b a' h (Setoid.refl a'))
q₂)
q₁
@[reducible, elabAsEliminator, inline]
protected def liftOn₂
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : α → β → φ) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : φ :=
Quotient.lift₂ f c q₁ q₂
@[elabAsEliminator]
protected theorem ind₂ {φ : Quotient s₁ → Quotient s₂ → Prop} (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) (q₁ : Quotient s₁) (q₂ : Quotient s₂) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₂
{φ : Quotient s₁ → Quotient s₂ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (h : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => h a₁ a₂) q₂) q₁
@[elabAsEliminator]
protected theorem inductionOn₃
[s₃ : Setoid φ]
{δ : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop} (q₁ : Quotient s₁) (q₂ : Quotient s₂) (q₃ : Quotient s₃) (h : ∀ a b c, δ (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))
: δ q₁ q₂ q₃ :=
Quotient.ind (fun a₁ => Quotient.ind (fun a₂ => Quotient.ind (fun a₃ => h a₁ a₂ a₃) q₃) q₂) q₁
end
section Exact
variable {α : Sort u}
private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop :=
Quotient.liftOn₂ q₁ q₂
(fun a₁ a₂ => a₁ ≈ a₂)
(fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ =>
propext (Iff.intro
(fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))
(fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))
private theorem rel.refl [s : Setoid α] : ∀ (q : Quotient s), rel q q :=
fun q => Quot.inductionOn q (fun a => Setoid.refl a)
private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=
fun h => Eq.ndrecOn h (rel.refl q₁)
theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b :=
fun h => eqImpRel h
end Exact
section
universes uA uB uC
variables {α : Sort uA} {β : Sort uB}
variables [s₁ : Setoid α] [s₂ : Setoid β]
@[reducible, elabAsEliminator]
protected def recOnSubsingleton₂
{φ : Quotient s₁ → Quotient s₂ → Sort uC} [h : ∀ a b, Subsingleton (φ (Quotient.mk a) (Quotient.mk b))]
(q₁ : Quotient s₁) (q₂ : Quotient s₂) (f : ∀ a b, φ (Quotient.mk a) (Quotient.mk b)) : φ q₁ q₂:=
@Quotient.recOnSubsingleton _ s₁ (fun q => φ q q₂) (fun a => Quotient.ind (fun b => h a b) q₂) q₁
(fun a => Quotient.recOnSubsingleton q₂ (fun b => f a b))
end
end Quotient
section
variable {α : Type u}
variable (r : α → α → Prop)
inductive EqvGen : α → α → Prop
| rel : ∀ x y, r x y → EqvGen x y
| refl : ∀ x, EqvGen x x
| symm : ∀ x y, EqvGen x y → EqvGen y x
| trans : ∀ x y z, EqvGen x y → EqvGen y z → EqvGen x z
theorem EqvGen.isEquivalence : Equivalence (@EqvGen α r) :=
mkEquivalence _ EqvGen.refl EqvGen.symm EqvGen.trans
def EqvGen.Setoid : Setoid α :=
Setoid.mk _ (EqvGen.isEquivalence r)
theorem Quot.exact {a b : α} (H : Quot.mk r a = Quot.mk r b) : EqvGen r a b :=
@Quotient.exact _ (EqvGen.Setoid r) a b (@congrArg _ _ _ _
(Quot.lift (@Quotient.mk _ (EqvGen.Setoid r)) (fun x y h => Quot.sound (EqvGen.rel x y h))) H)
theorem Quot.eqvGenSound {r : α → α → Prop} {a b : α} (H : EqvGen r a b) : Quot.mk r a = Quot.mk r b :=
EqvGen.recOn H
(fun x y h => Quot.sound h)
(fun x => rfl)
(fun x y _ IH => Eq.symm IH)
(fun x y z _ _ IH₁ IH₂ => Eq.trans IH₁ IH₂)
end
instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=
fun (q₁ q₂ : Quotient s) =>
Quotient.recOnSubsingleton₂ q₁ q₂
(fun a₁ a₂ =>
match (d a₁ a₂) with
| (isTrue h₁) => isTrue (Quotient.sound h₁)
| (isFalse h₂) => isFalse (fun h => absurd (Quotient.exact h) h₂))
/- Function extensionality -/
namespace Function
variables {α : Sort u} {β : α → Sort v}
def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x
protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f :=
fun x => rfl
protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ :=
fun h x => Eq.symm (h x)
protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ :=
fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x)
protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) :=
mkEquivalence (@Function.Equiv α β) (@Equiv.refl α β) (@Equiv.symm α β) (@Equiv.trans α β)
end Function
section
open Quotient
variables {α : Sort u} {β : α → Sort v}
@[instance]
private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) :=
Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β)
private def extfunApp (f : Quotient $ funSetoid α β) : ∀ (x : α), β x :=
fun x =>
Quot.liftOn f
(fun (f : ∀ (x : α), β x) => f x)
(fun f₁ f₂ h => h x)
theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ :=
show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂) from
congrArg extfunApp (sound h)
end
instance Forall.Subsingleton {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) :=
⟨fun f₁ f₂ => funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))⟩
/- General operations on functions -/
namespace Function
universes u₁ u₂ u₃ u₄
variables {α : Sort u₁} {β : Sort u₂} {φ : Sort u₃} {δ : Sort u₄} {ζ : Sort u₁}
@[inline, reducible] def comp (f : β → φ) (g : α → β) : α → φ :=
fun x => f (g x)
infixr ` ∘ ` := Function.comp
@[inline, reducible] def onFun (f : β → β → φ) (g : α → β) : α → α → φ :=
fun x y => f (g x) (g y)
@[inline, reducible] def combine (f : α → β → φ) (op : φ → δ → ζ) (g : α → β → δ)
: α → β → ζ :=
fun x y => op (f x y) (g x y)
@[inline, reducible] def const (β : Sort u₂) (a : α) : β → α :=
fun x => a
@[inline, reducible] def swap {φ : α → β → Sort u₃} (f : ∀ x y, φ x y) : ∀ y x, φ x y :=
fun y x => f x y
end Function
/- Squash -/
def Squash (α : Type u) := Quot (fun (a b : α) => True)
def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x
theorem Squash.ind {α : Type u} {β : Squash α → Prop} (h : ∀ (a : α), β (Squash.mk a)) : ∀ (q : Squash α), β q :=
Quot.ind h
@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=
Quot.lift f (fun a b _ => Subsingleton.elim _ _) s
instance Squash.Subsingleton {α} : Subsingleton (Squash α) :=
⟨Squash.ind (fun (a : α) => Squash.ind (fun (b : α) => Quot.sound trivial))⟩
namespace Lean
/- Kernel reduction hints -/
/--
When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.
The kernel will not use the interpreter if `c` is not a constant.
This feature is useful for performing proofs by reflection.
Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing
free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with
`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.
Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.
This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using
external type checkers (e.g., Trepplein) that do not implement this feature.
Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.
So, you are mainly losing the capability of type checking your developement using external checkers.
Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.
If an extern function is executed, then the trusted code base will also include the implementation of the associated
foreign function.
-/
constant reduceBool (b : Bool) : Bool := b
/--
Similar to `Lean.reduceBool` for closed `Nat` terms.
Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.
The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.
We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/
constant reduceNat (n : Nat) : Nat := n
axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b
axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b
end Lean
/- Classical reasoning support -/
namespace Classical
axiom choice {α : Sort u} : Nonempty α → α
noncomputable def indefiniteDescription {α : Sort u} (p : α → Prop)
(h : Exists (fun x => p x)) : {x // p x} :=
choice $ let ⟨x, px⟩ := h; ⟨⟨x, px⟩⟩
noncomputable def choose {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : α :=
(indefiniteDescription p h).val
theorem chooseSpec {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) : p (choose h) :=
(indefiniteDescription p h).property
/- Diaconescu's theorem: excluded middle from choice, Function extensionality and propositional extensionality. -/
theorem em (p : Prop) : p ∨ ¬p :=
let U (x : Prop) : Prop := x = True ∨ p;
let V (x : Prop) : Prop := x = False ∨ p;
have exU : Exists (fun x => U x) from ⟨True, Or.inl rfl⟩;
have exV : Exists (fun x => V x) from ⟨False, Or.inl rfl⟩;
let u : Prop := choose exU;
let v : Prop := choose exV;
have uDef : U u from chooseSpec exU;
have vDef : V v from chooseSpec exV;
have notUvOrP : u ≠ v ∨ p from
Or.elim uDef
(fun hut =>
Or.elim vDef
(fun hvf =>
have hne : u ≠ v from hvf.symm ▸ hut.symm ▸ trueNeFalse;
Or.inl hne)
Or.inr)
Or.inr;
have pImpliesUv : p → u = v from
fun hp =>
have hpred : U = V from
funext $ fun x =>
have hl : (x = True ∨ p) → (x = False ∨ p) from
fun a => Or.inr hp;
have hr : (x = False ∨ p) → (x = True ∨ p) from
fun a => Or.inr hp;
show (x = True ∨ p) = (x = False ∨ p) from
propext (Iff.intro hl hr);
have h₀ : ∀ exU exV, @choose _ U exU = @choose _ V exV from
hpred ▸ fun exU exV => rfl;
show u = v from h₀ _ _;
Or.elim notUvOrP
(fun (hne : u ≠ v) => Or.inr (mt pImpliesUv hne))
Or.inl
theorem existsTrueOfNonempty {α : Sort u} : Nonempty α → Exists (fun (x : α) => True)
| ⟨x⟩ => ⟨x, trivial⟩
noncomputable def inhabitedOfNonempty {α : Sort u} (h : Nonempty α) : Inhabited α :=
⟨choice h⟩
noncomputable def inhabitedOfExists {α : Sort u} {p : α → Prop} (h : Exists (fun x => p x)) :
Inhabited α :=
inhabitedOfNonempty (Exists.elim h (fun w hw => ⟨w⟩))
/- all propositions are Decidable -/
noncomputable def propDecidable (a : Prop) : Decidable a :=
choice $ Or.elim (em a)
(fun ha => ⟨isTrue ha⟩)
(fun hna => ⟨isFalse hna⟩)
noncomputable def decidableInhabited (a : Prop) : Inhabited (Decidable a) :=
⟨propDecidable a⟩
noncomputable def typeDecidableEq (α : Sort u) : DecidableEq α :=
fun x y => propDecidable (x = y)
noncomputable def typeDecidable (α : Sort u) : PSum α (α → False) :=
match (propDecidable (Nonempty α)) with
| (isTrue hp) => PSum.inl (@arbitrary _ (inhabitedOfNonempty hp))
| (isFalse hn) => PSum.inr (fun a => absurd (Nonempty.intro a) hn)
noncomputable def strongIndefiniteDescription {α : Sort u} (p : α → Prop)
(h : Nonempty α) : {x : α // Exists (fun (y : α) => p y) → p x} :=
@dite _ (Exists (fun (x : α) => p x)) (propDecidable _)
(fun (hp : Exists (fun (x : α) => p x)) =>
show {x : α // Exists (fun (y : α) => p y) → p x} from
let xp := indefiniteDescription _ hp;
⟨xp.val, fun h' => xp.property⟩)
(fun hp => ⟨choice h, fun h => absurd h hp⟩)
/- the Hilbert epsilon Function -/
noncomputable def epsilon {α : Sort u} [h : Nonempty α] (p : α → Prop) : α :=
(strongIndefiniteDescription p h).val
theorem epsilonSpecAux {α : Sort u} (h : Nonempty α) (p : α → Prop)
: Exists (fun y => p y) → p (@epsilon α h p) :=
(strongIndefiniteDescription p h).property
theorem epsilonSpec {α : Sort u} {p : α → Prop} (hex : Exists (fun y => p y)) :
p (@epsilon α (nonemptyOfExists hex) p) :=
epsilonSpecAux (nonemptyOfExists hex) p hex
theorem epsilonSingleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (fun y => y = x) = x :=
@epsilonSpec α (fun y => y = x) ⟨x, rfl⟩
/- the axiom of choice -/
theorem axiomOfChoice {α : Sort u} {β : α → Sort v} {r : ∀ x, β x → Prop} (h : ∀ x, Exists (fun y => r x y)) :
Exists (fun (f : ∀ x, β x) => ∀ x, r x (f x)) :=
⟨_, fun x => chooseSpec (h x)⟩
theorem skolem {α : Sort u} {b : α → Sort v} {p : ∀ x, b x → Prop} :
(∀ x, Exists (fun y => p x y)) ↔ Exists (fun (f : ∀ x, b x) => ∀ x, p x (f x)) :=
⟨axiomOfChoice, fun ⟨f, hw⟩ (x) => ⟨f x, hw x⟩⟩
theorem propComplete (a : Prop) : a = True ∨ a = False :=
Or.elim (em a)
(fun t => Or.inl (eqTrueIntro t))
(fun f => Or.inr (eqFalseIntro f))
-- this supercedes byCases in Decidable
theorem byCases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q :=
@Decidable.byCases _ _ (propDecidable _) hpq hnpq
-- this supercedes byContradiction in Decidable
theorem byContradiction {p : Prop} (h : ¬p → False) : p :=
@Decidable.byContradiction _ (propDecidable _) h
end Classical
|
f7d8ebec584353259a560bc8916e54545529d765 | 58840d1f4c8fba0ed6eb3a08b3c7491e28e2a4a2 | /SGDT/storage.lean | 071d8d86416f08da77fc1a1d046b70a6646a8f9e | [] | no_license | jonsterling/lean4-sgdt | 7ba9f2ff2a21981f1d6517b86be1bee76e8d426e | 5858bfe96f2c5de8343c0f7befddd946ef6ce3e6 | refs/heads/master | 1,685,409,923,012 | 1,623,505,684,000 | 1,623,505,684,000 | 371,836,555 | 10 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 295 | lean | import sgdt.domain
import sgdt.lift
class storable (a : Type) [domain a] where
store : [domain b] → (a → b) → (a ⊸ b)
noncomputable instance : storable [a]⊥ where
store {b} _ f :=
⟨fun m => lift.dombind (f ∘ lift.now) m,
fun _ => by simp [is_strict, Functor.map,pure]⟩ |
f649539abc4a6da17b532fdc3b5a875e6ab40403 | 01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab | /categories/category.lean | ca67cb6ddfd3c7b42feba5110ae36f4329d5ef51 | [] | no_license | PatrickMassot/lean-category-theory | 0f56a83464396a253c28a42dece16c93baf8ad74 | ef239978e91f2e1c3b8e88b6e9c64c155dc56c99 | refs/heads/master | 1,629,739,187,316 | 1,512,422,659,000 | 1,512,422,659,000 | 113,098,786 | 0 | 0 | null | 1,512,424,022,000 | 1,512,424,022,000 | null | UTF-8 | Lean | false | false | 2,485 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Stephen Morgan, Scott Morrison
import .tactics
import .graphs
open categories.graphs
namespace categories
structure {u v} Category :=
( Obj : Type u )
( Hom : Obj → Obj → Type v )
( identity : Π X : Obj, Hom X X )
( compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z )
( left_identity : ∀ { X Y : Obj } (f : Hom X Y), compose (identity X) f = f )
( right_identity : ∀ { X Y : Obj } (f : Hom X Y), compose f (identity Y) = f )
( associativity : ∀ { W X Y Z : Obj } (f : Hom W X) (g : Hom X Y) (h : Hom Y Z),
compose (compose f g) h = compose f (compose g h) )
attribute [simp] Category.left_identity
attribute [simp] Category.right_identity
attribute [simp,ematch] Category.associativity
attribute [applicable] Category.identity
@[tidy] meta def rewrite_associativity_backwards : tactic string :=
(`[repeat_at_least_once { rewrite ← Category.associativity }])
>> `[simp]
>> tactic.done
>> pure "repeat_at_least_once {rewrite ← Category.associativity}, simp"
-- instance Category_to_Hom : has_coe_to_fun Category :=
-- { F := λ C, C.Obj → C.Obj → Type v,
-- coe := Category.Hom }
definition Category.graph ( C : Category ) : Graph :=
{
Obj := C.Obj,
Hom := C.Hom
}
@[ematch] lemma Category.identity_idempotent
( C : Category )
( X : C.Obj ) : C.identity X = C.compose (C.identity X) (C.identity X) := ♮
open Category
inductive {u v} morphism_path { C : Category.{u v} } : C.Obj → C.Obj → Type (max u v)
| nil : Π ( h : C.Obj ), morphism_path h h
| cons : Π { h s t : C.Obj } ( e : C.Hom h s ) ( l : morphism_path s t ), morphism_path h t
notation a :: b := morphism_path.cons a b
notation `c[` l:(foldr `, ` (h t, morphism_path.cons h t) morphism_path.nil _ `]`) := l
definition {u v} concatenate_paths
{ C : Category.{u v} } :
Π { x y z : C.Obj }, morphism_path x y → morphism_path y z → morphism_path x z
| ._ ._ _ (morphism_path.nil _) q := q
| ._ ._ _ (@morphism_path.cons ._ _ _ _ e p') q := morphism_path.cons e (concatenate_paths p' q)
definition {u v} Category.compose_path ( C : Category.{u v} ) : Π { X Y : C.Obj }, morphism_path X Y → C.Hom X Y
| X ._ (morphism_path.nil ._) := C.identity X
| _ _ (@morphism_path.cons ._ ._ _ ._ e p) := C.compose e (Category.compose_path p)
end categories
|
08f44c134045f0a99aa4ed7d5ac49478aa149b94 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/tactic/cancel_denoms.lean | 5fd761c78b9fdf11b487ec611cf3a0c055483937 | [
"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 | 9,238 | lean | /-
Copyright (c) 2020 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis
-/
import data.rat.meta_defs
import tactic.norm_num
import data.tree
import meta.expr
/-!
# A tactic for canceling numeric denominators
This file defines tactics that cancel numeric denominators from field expressions.
As an example, we want to transform a comparison `5*(a/3 + b/4) < c/3` into the equivalent
`5*(4*a + 3*b) < 4*c`.
## Implementation notes
The tooling here was originally written for `linarith`, not intended as an interactive tactic.
The interactive version has been split off because it is sometimes convenient to use on its own.
There are likely some rough edges to it.
Improving this tactic would be a good project for someone interested in learning tactic programming.
-/
namespace cancel_factors
/-! ### Lemmas used in the procedure -/
lemma mul_subst {α} [comm_ring α] {n1 n2 k e1 e2 t1 t2 : α} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2)
(h3 : n1*n2 = k) : 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]
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_left_comm, h2, ←mul_assoc, h1, mul_comm, one_mul]
lemma cancel_factors_eq_div {α} [field α] {n e e' : α} (h : n*e = e') (h2 : n ≠ 0) :
e = e' / n :=
eq_div_of_mul_eq h2 $ by rwa mul_comm at h
lemma add_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *]
lemma sub_subst {α} [ring α] {n e1 e2 t1 t2 : α} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *, sub_eq_add_neg]
lemma neg_subst {α} [ring α] {n e t : α} (h1 : n * e = t) : n * (-e) = -t := by simp *
lemma cancel_factors_lt {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a')
(hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) :
a < b = ((1/gcd)*(bd*a') < (1/gcd)*(ad*b')) :=
begin
rw [mul_lt_mul_left, ←ha, ←hb, ←mul_assoc, ←mul_assoc, mul_comm bd, mul_lt_mul_left],
exact mul_pos had hbd,
exact one_div_pos.2 hgcd
end
lemma cancel_factors_le {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a')
(hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) :
a ≤ b = ((1/gcd)*(bd*a') ≤ (1/gcd)*(ad*b')) :=
begin
rw [mul_le_mul_left, ←ha, ←hb, ←mul_assoc, ←mul_assoc, mul_comm bd, mul_le_mul_left],
exact mul_pos had hbd,
exact one_div_pos.2 hgcd
end
lemma cancel_factors_eq {α} [linear_ordered_field α] {a b ad bd a' b' gcd : α} (ha : ad*a = a')
(hb : bd*b = b') (had : 0 < ad) (hbd : 0 < bd) (hgcd : 0 < gcd) :
a = b = ((1/gcd)*(bd*a') = (1/gcd)*(ad*b')) :=
begin
rw [←ha, ←hb, ←mul_assoc bd, ←mul_assoc ad, mul_comm bd],
ext, split,
{ rintro rfl, refl },
{ intro h,
simp only [←mul_assoc] at h,
refine mul_left_cancel₀ (mul_ne_zero _ _) h,
apply mul_ne_zero, apply div_ne_zero,
all_goals {apply ne_of_gt; assumption <|> exact zero_lt_one}}
end
open tactic expr
/-! ### Computing cancelation factors -/
open tree
/--
`find_cancel_factor e` produces a natural number `n`, such that multiplying `e` by `n` will
be able to cancel all the numeric denominators in `e`. The returned `tree` describes how to
distribute the value `n` over products inside `e`.
-/
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, 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, node lcm t1 t2)
| `(%%e1 * %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in
(pd, node pd t1 t2)
| `(%%e1 / %%e2) :=
match e2.to_nonneg_rat with
| some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in
(n, node n t1 (node q.num.nat_abs tree.nil tree.nil))
| none := (1, node 1 tree.nil tree.nil)
end
| `(-%%e) := find_cancel_factor e
| _ := (1, node 1 tree.nil tree.nil)
/--
`mk_prod_prf n tr e` produces a proof of `n*e = e'`, where numeric denominators have been
canceled in `e'`, distributing `n` proportionally according to `tr`.
-/
meta def mk_prod_prf : ℕ → tree ℕ → expr → tactic expr
| v (node _ lhs rhs) `(%%e1 + %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2]
| v (node _ lhs rhs) `(%%e1 - %%e2) :=
do v1 ← mk_prod_prf v lhs e1, v2 ← mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2]
| v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf ln lhs e1, v2 ← mk_prod_prf (v/ln) rhs e2,
ln' ← tp.of_nat ln, vln' ← tp.of_nat (v/ln), v' ← tp.of_nat v,
ntp ← to_expr ``(%%ln' * %%vln' = %%v'),
(_, npf) ← solve_aux ntp `[norm_num, done],
mk_app ``mul_subst [v1, v2, npf]
| v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) :=
do tp ← infer_type e1, v1 ← mk_prod_prf (v/rn) lhs e1,
rn' ← tp.of_nat rn, vrn' ← tp.of_nat (v/rn), n' ← tp.of_nat n, v' ← tp.of_nat v,
ntp ← to_expr ``(%%rn' / %%e2 = 1),
(_, npf) ← solve_aux ntp `[norm_num, done],
ntp2 ← to_expr ``(%%vrn' * %%n' = %%v'),
(_, npf2) ← solve_aux ntp2 `[norm_num, done],
mk_app ``div_subst [v1, npf, npf2]
| v t `(-%%e) := do v' ← mk_prod_prf v t e, mk_app ``neg_subst [v']
| v _ e :=
do tp ← infer_type e,
v' ← tp.of_nat v,
e' ← to_expr ``(%%v' * %%e),
mk_app `eq.refl [e']
/--
Given `e`, a term with rational division, produces a natural number `n` and a proof of `n*e = e'`,
where `e'` has no division. Assumes "well-behaved" division.
-/
meta def derive (e : expr) : tactic (ℕ × expr) :=
let (n, t) := find_cancel_factor e in
prod.mk n <$> mk_prod_prf n t e <|>
fail!"cancel_factors.derive failed to normalize {e}. Are you sure this is well-behaved division?"
/--
Given `e`, a term with rational divison, produces a natural number `n` and a proof of `e = e' / n`,
where `e'` has no divison. Assumes "well-behaved" division.
-/
meta def derive_div (e : expr) : tactic (ℕ × expr) :=
do (n, p) ← derive e,
tp ← infer_type e,
n' ← tp.of_nat n, tgt ← to_expr ``(%%n' ≠ 0),
(_, pn) ← solve_aux tgt `[norm_num, done],
prod.mk n <$> mk_mapp ``cancel_factors_eq_div [none, none, n', none, none, p, pn]
/--
`find_comp_lemma e` arranges `e` in the form `lhs R rhs`, where `R ∈ {<, ≤, =}`, and returns
`lhs`, `rhs`, and the `cancel_factors` lemma corresponding to `R`.
-/
meta def find_comp_lemma : expr → option (expr × expr × name)
| `(%%a < %%b) := (a, b, ``cancel_factors_lt)
| `(%%a ≤ %%b) := (a, b, ``cancel_factors_le)
| `(%%a = %%b) := (a, b, ``cancel_factors_eq)
| `(%%a ≥ %%b) := (b, a, ``cancel_factors_le)
| `(%%a > %%b) := (b, a, ``cancel_factors_lt)
| _ := none
/--
`cancel_denominators_in_type h` assumes that `h` is of the form `lhs R rhs`,
where `R ∈ {<, ≤, =, ≥, >}`.
It produces an expression `h'` of the form `lhs' R rhs'` and a proof that `h = h'`.
Numeric denominators have been canceled in `lhs'` and `rhs'`.
-/
meta def cancel_denominators_in_type (h : expr) : tactic (expr × expr) :=
do some (lhs, rhs, lem) ← return $ find_comp_lemma h | fail "cannot kill factors",
(al, lhs_p) ← derive lhs,
(ar, rhs_p) ← derive rhs,
let gcd := al.gcd ar,
tp ← infer_type lhs,
al ← tp.of_nat al,
ar ← tp.of_nat ar,
gcd ← tp.of_nat gcd,
al_pos ← to_expr ``(0 < %%al),
ar_pos ← to_expr ``(0 < %%ar),
gcd_pos ← to_expr ``(0 < %%gcd),
(_, al_pos) ← solve_aux al_pos `[norm_num, done],
(_, ar_pos) ← solve_aux ar_pos `[norm_num, done],
(_, gcd_pos) ← solve_aux gcd_pos `[norm_num, done],
pf ← mk_app lem [lhs_p, rhs_p, al_pos, ar_pos, gcd_pos],
pf_tp ← infer_type pf,
return ((find_comp_lemma pf_tp).elim default (prod.fst ∘ prod.snd), pf)
end cancel_factors
/-! ### Interactive version -/
setup_tactic_parser
open tactic expr cancel_factors
/--
`cancel_denoms` attempts to remove numerals from the denominators of fractions.
It works on propositions that are field-valued inequalities.
```lean
variables {α : Type} [linear_ordered_field α] (a b c : α)
example (h : a / 5 + b / 4 < c) : 4*a + 5*b < 20*c :=
begin
cancel_denoms at h,
exact h
end
example (h : a > 0) : a / 5 > 0 :=
begin
cancel_denoms,
exact h
end
```
-/
meta def tactic.interactive.cancel_denoms (l : parse location) : tactic unit :=
do locs ← l.get_locals,
tactic.replace_at cancel_denominators_in_type locs l.include_goal >>= guardb
<|> fail "failed to cancel any denominators",
tactic.interactive.norm_num [simp_arg_type.symm_expr ``(mul_assoc)] l
add_tactic_doc
{ name := "cancel_denoms",
category := doc_category.tactic,
decl_names := [`tactic.interactive.cancel_denoms],
tags := ["simplification"] }
|
94040212262b9247e08b1212b918b3cae012b75a | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/data/option/instances.lean | 96d498b3612b44150798e88fd7e03cd2914ea000 | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 652 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.data.option.basic
universes u v
theorem Option.eqOfEqSome {α : Type u} : ∀ {x y : Option α}, (∀z, x = some z ↔ y = some z) → x = y
| none none h := rfl
| none (some z) h := Option.noConfusion ((h z).2 rfl)
| (some z) none h := Option.noConfusion ((h z).1 rfl)
| (some z) (some w) h := Option.noConfusion ((h w).2 rfl) (congrArg some)
theorem Option.eqNoneOfIsNone {α : Type u} : ∀ {o : Option α}, o.isNone → o = none
| none h := rfl
|
867019c8bbb6f52b05aee02138e4a1c401daa8c7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Util/Exit.lean | 2ce22f9a23bf22b33b3af13bffedc01cc359a558 | [
"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 | 624 | lean | /-
Copyright (c) 2021 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
namespace Lake
/-- A process exit / return code. -/
abbrev ExitCode := UInt32
class MonadExit (m : Type u → Type v) where
exit {α : Type u} : ExitCode → m α
export MonadExit (exit)
instance [MonadLift m n] [MonadExit m] : MonadExit n where
exit rc := liftM (m := m) <| exit rc
/-- Exit with `ExitCode` if it is not 0. Otherwise, continue. -/
@[inline] def exitIfErrorCode [Pure m] [MonadExit m] (rc : ExitCode) : m Unit :=
if rc != 0 then exit rc else pure ()
|
cef75e22fd0b32419a48c66946e51247d72d9604 | 969dbdfed67fda40a6f5a2b4f8c4a3c7dc01e0fb | /src/linear_algebra/affine_space/midpoint.lean | 2dfeda6f7452a1d864cdbdef9477b1b69c3f7cee | [
"Apache-2.0"
] | permissive | SAAluthwela/mathlib | 62044349d72dd63983a8500214736aa7779634d3 | 83a4b8b990907291421de54a78988c024dc8a552 | refs/heads/master | 1,679,433,873,417 | 1,615,998,031,000 | 1,615,998,031,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,622 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Yury Kudryashov
-/
import algebra.char_p.invertible
import linear_algebra.affine_space.affine_equiv
/-!
# Midpoint of a segment
## Main definitions
* `midpoint R x y`: midpoint of the segment `[x, y]`. We define it for `x` and `y`
in a module over a ring `R` with invertible `2`.
* `add_monoid_hom.of_map_midpoint`: construct an `add_monoid_hom` given a map `f` such that
`f` sends zero to zero and midpoints to midpoints.
## Main theorems
* `midpoint_eq_iff`: `z` is the midpoint of `[x, y]` if and only if `x + y = z + z`,
* `midpoint_unique`: `midpoint R x y` does not depend on `R`;
* `midpoint x y` is linear both in `x` and `y`;
* `point_reflection_midpoint_left`, `point_reflection_midpoint_right`:
`equiv.point_reflection (midpoint R x y)` swaps `x` and `y`.
We do not mark most lemmas as `@[simp]` because it is hard to tell which side is simpler.
## Tags
midpoint, add_monoid_hom
-/
open affine_map affine_equiv
section
variables (R : Type*) {V V' P P' : Type*} [ring R] [invertible (2:R)]
[add_comm_group V] [semimodule R V] [add_torsor V P]
[add_comm_group V'] [semimodule R V'] [add_torsor V' P']
include V
/-- `midpoint x y` is the midpoint of the segment `[x, y]`. -/
def midpoint (x y : P) : P := line_map x y (⅟2:R)
variables {R} {x y z : P}
include V'
@[simp] lemma affine_map.map_midpoint (f : P →ᵃ[R] P') (a b : P) :
f (midpoint R a b) = midpoint R (f a) (f b) :=
f.apply_line_map a b _
@[simp] lemma affine_equiv.map_midpoint (f : P ≃ᵃ[R] P') (a b : P) :
f (midpoint R a b) = midpoint R (f a) (f b) :=
f.apply_line_map a b _
omit V'
@[simp] lemma affine_equiv.point_reflection_midpoint_left (x y : P) :
point_reflection R (midpoint R x y) x = y :=
by rw [midpoint, point_reflection_apply, line_map_apply, vadd_vsub,
vadd_assoc, ← add_smul, ← two_mul, mul_inv_of_self, one_smul, vsub_vadd]
lemma midpoint_comm (x y : P) : midpoint R x y = midpoint R y x :=
by rw [midpoint, ← line_map_apply_one_sub, one_sub_inv_of_two, midpoint]
@[simp] lemma affine_equiv.point_reflection_midpoint_right (x y : P) :
point_reflection R (midpoint R x y) y = x :=
by rw [midpoint_comm, affine_equiv.point_reflection_midpoint_left]
lemma midpoint_vsub_midpoint (p₁ p₂ p₃ p₄ : P) :
midpoint R p₁ p₂ -ᵥ midpoint R p₃ p₄ = midpoint R (p₁ -ᵥ p₃) (p₂ -ᵥ p₄) :=
line_map_vsub_line_map _ _ _ _ _
lemma midpoint_vadd_midpoint (v v' : V) (p p' : P) :
midpoint R v v' +ᵥ midpoint R p p' = midpoint R (v +ᵥ p) (v' +ᵥ p') :=
line_map_vadd_line_map _ _ _ _ _
lemma midpoint_eq_iff {x y z : P} : midpoint R x y = z ↔ point_reflection R z x = y :=
eq_comm.trans ((injective_point_reflection_left_of_module R x).eq_iff'
(affine_equiv.point_reflection_midpoint_left x y)).symm
@[simp] lemma midpoint_vsub_left (p₁ p₂ : P) : midpoint R p₁ p₂ -ᵥ p₁ = (⅟2:R) • (p₂ -ᵥ p₁) :=
line_map_vsub_left _ _ _
@[simp] lemma midpoint_vsub_right (p₁ p₂ : P) : midpoint R p₁ p₂ -ᵥ p₂ = (⅟2:R) • (p₁ -ᵥ p₂) :=
by rw [midpoint_comm, midpoint_vsub_left]
@[simp] lemma left_vsub_midpoint (p₁ p₂ : P) : p₁ -ᵥ midpoint R p₁ p₂ = (⅟2:R) • (p₁ -ᵥ p₂) :=
left_vsub_line_map _ _ _
@[simp] lemma right_vsub_midpoint (p₁ p₂ : P) : p₂ -ᵥ midpoint R p₁ p₂ = (⅟2:R) • (p₂ -ᵥ p₁) :=
by rw [midpoint_comm, left_vsub_midpoint]
@[simp] lemma midpoint_sub_left (v₁ v₂ : V) : midpoint R v₁ v₂ - v₁ = (⅟2:R) • (v₂ - v₁) :=
midpoint_vsub_left v₁ v₂
@[simp] lemma midpoint_sub_right (v₁ v₂ : V) : midpoint R v₁ v₂ - v₂ = (⅟2:R) • (v₁ - v₂) :=
midpoint_vsub_right v₁ v₂
@[simp] lemma left_sub_midpoint (v₁ v₂ : V) : v₁ - midpoint R v₁ v₂ = (⅟2:R) • (v₁ - v₂) :=
left_vsub_midpoint v₁ v₂
@[simp] lemma right_sub_midpoint (v₁ v₂ : V) : v₂ - midpoint R v₁ v₂ = (⅟2:R) • (v₂ - v₁) :=
right_vsub_midpoint v₁ v₂
variable (R)
lemma midpoint_eq_midpoint_iff_vsub_eq_vsub {x x' y y' : P} :
midpoint R x y = midpoint R x' y' ↔ x -ᵥ x' = y' -ᵥ y :=
by rw [← @vsub_eq_zero_iff_eq V, midpoint_vsub_midpoint, midpoint_eq_iff, point_reflection_apply,
vsub_eq_sub, zero_sub, vadd_eq_add, add_zero, neg_eq_iff_neg_eq, neg_vsub_eq_vsub_rev, eq_comm]
lemma midpoint_eq_iff' {x y z : P} : midpoint R x y = z ↔ equiv.point_reflection z x = y :=
midpoint_eq_iff
/-- `midpoint` does not depend on the ring `R`. -/
lemma midpoint_unique (R' : Type*) [ring R'] [invertible (2:R')] [semimodule R' V] (x y : P) :
midpoint R x y = midpoint R' x y :=
(midpoint_eq_iff' R).2 $ (midpoint_eq_iff' R').1 rfl
@[simp] lemma midpoint_self (x : P) : midpoint R x x = x :=
line_map_same_apply _ _
@[simp] lemma midpoint_add_self (x y : V) : midpoint R x y + midpoint R x y = x + y :=
calc midpoint R x y +ᵥ midpoint R x y = midpoint R x y +ᵥ midpoint R y x : by rw midpoint_comm
... = x + y : by rw [midpoint_vadd_midpoint, vadd_eq_add, vadd_eq_add, add_comm, midpoint_self]
lemma midpoint_zero_add (x y : V) : midpoint R 0 (x + y) = midpoint R x y :=
(midpoint_eq_midpoint_iff_vsub_eq_vsub R).2 $ by simp [sub_add_eq_sub_sub_swap]
end
lemma line_map_inv_two {R : Type*} {V P : Type*} [division_ring R] [char_zero R]
[add_comm_group V] [semimodule R V] [add_torsor V P] (a b : P) :
line_map a b (2⁻¹:R) = midpoint R a b :=
rfl
lemma line_map_one_half {R : Type*} {V P : Type*} [division_ring R] [char_zero R]
[add_comm_group V] [semimodule R V] [add_torsor V P] (a b : P) :
line_map a b (1/2:R) = midpoint R a b :=
by rw [one_div, line_map_inv_two]
lemma homothety_inv_of_two {R : Type*} {V P : Type*} [comm_ring R] [invertible (2:R)]
[add_comm_group V] [semimodule R V] [add_torsor V P] (a b : P) :
homothety a (⅟2:R) b = midpoint R a b :=
rfl
lemma homothety_inv_two {k : Type*} {V P : Type*} [field k] [char_zero k]
[add_comm_group V] [semimodule k V] [add_torsor V P] (a b : P) :
homothety a (2⁻¹:k) b = midpoint k a b :=
rfl
lemma homothety_one_half {k : Type*} {V P : Type*} [field k] [char_zero k]
[add_comm_group V] [semimodule k V] [add_torsor V P] (a b : P) :
homothety a (1/2:k) b = midpoint k a b :=
by rw [one_div, homothety_inv_two]
@[simp] lemma pi_midpoint_apply {k ι : Type*} {V : Π i : ι, Type*} {P : Π i : ι, Type*} [field k]
[invertible (2:k)] [Π i, add_comm_group (V i)] [Π i, semimodule k (V i)]
[Π i, add_torsor (V i) (P i)] (f g : Π i, P i) (i : ι) :
midpoint k f g i = midpoint k (f i) (g i) := rfl
namespace add_monoid_hom
variables (R R' : Type*) {E F : Type*}
[ring R] [invertible (2:R)] [add_comm_group E] [semimodule R E]
[ring R'] [invertible (2:R')] [add_comm_group F] [semimodule R' F]
/-- A map `f : E → F` sending zero to zero and midpoints to midpoints is an `add_monoid_hom`. -/
def of_map_midpoint (f : E → F) (h0 : f 0 = 0)
(hm : ∀ x y, f (midpoint R x y) = midpoint R' (f x) (f y)) :
E →+ F :=
{ to_fun := f,
map_zero' := h0,
map_add' := λ x y,
calc f (x + y) = f 0 + f (x + y) : by rw [h0, zero_add]
... = midpoint R' (f 0) (f (x + y)) + midpoint R' (f 0) (f (x + y)) :
(midpoint_add_self _ _ _).symm
... = f (midpoint R x y) + f (midpoint R x y) : by rw [← hm, midpoint_zero_add]
... = f x + f y : by rw [hm, midpoint_add_self] }
@[simp] lemma coe_of_map_midpoint (f : E → F) (h0 : f 0 = 0)
(hm : ∀ x y, f (midpoint R x y) = midpoint R' (f x) (f y)) :
⇑(of_map_midpoint R R' f h0 hm) = f := rfl
end add_monoid_hom
|
e6496c320761db275ca5807af2278a9899b820e6 | de91c42b87530c3bdcc2b138ef1a3c3d9bee0d41 | /expressions/time_expr.lean | 697dbc6c31fc0f7074e30c84f984fe06e0d16613 | [] | no_license | kevinsullivan/lang | d3e526ba363dc1ddf5ff1c2f36607d7f891806a7 | e9d869bff94fb13ad9262222a6f3c4aafba82d5e | refs/heads/master | 1,687,840,064,795 | 1,628,047,969,000 | 1,628,047,969,000 | 282,210,749 | 0 | 1 | null | 1,608,153,830,000 | 1,595,592,637,000 | Lean | UTF-8 | Lean | false | false | 14,728 | lean | import .expr_base
import ...phys.time.time
import .scalar_expr
namespace lang.time
universes u
structure time_frame_var extends var
inductive time_frame_expr : Type 1 --{f : fm scalar T}
| lit (f : time_frame) : time_frame_expr
| var (v : time_frame_var) : time_frame_expr
abbreviation time_frame_env :=
time_frame_var → time_frame
abbreviation time_frame_eval :=
time_frame_env → time_frame_expr → time_frame
noncomputable def default_frame_env : time_frame_env :=
λv, time_std_frame
noncomputable def default_frame_eval : time_frame_eval := λenv_, λexpr_,
begin
cases expr_,
exact expr_,
exact (default_frame_env expr_)
end
def static_frame_eval : time_frame_eval
| env_ (time_frame_expr.lit f) := f
| env_ (time_frame_expr.var v) := env_ v
noncomputable def time_frame_expr.value (expr_ : time_frame_expr) : time_frame :=
(static_frame_eval) (default_frame_env) expr_
structure time_space_var (f : time_frame_expr) extends var
inductive time_space_expr (f : time_frame_expr) : Type 1
| lit (sp : time_space f.value) : time_space_expr
| var (v : time_space_var f) : time_space_expr
| mk : time_space_expr
abbreviation time_space_env := Π(f : time_frame_expr),
time_space_var f → time_space f.value
abbreviation time_space_eval := Π(f : time_frame_expr),
time_space_env → time_space_expr f → time_space f.value
noncomputable def default_space_env : time_space_env :=
λf, λv, mk_space f.value
noncomputable def default_space_eval : time_space_eval := λf, λenv_, λexpr_,
begin
cases expr_,
exact expr_,
exact (default_space_env f expr_),
exact mk_space f.value
end
noncomputable def static_space_eval : time_space_eval
| f env_ (time_space_expr.lit sp) := sp
| f env_ (time_space_expr.var v) := env_ f v
| f env_ (time_space_expr.mk) := mk_space f.value
noncomputable def time_space_expr.value {f : time_frame_expr} (expr_ : time_space_expr f) : time_space f.value :=
(static_space_eval f) (default_space_env) expr_
structure transform_var
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) extends var
inductive time_transform_expr
: Π {f1 : time_frame_expr} (sp1 : time_space_expr f1), Π {f2 : time_frame_expr} (sp2 : time_space_expr f2), Type 1
| lit {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2} (p : time_transform sp1.value sp2.value) : time_transform_expr sp1 sp2
| var {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2} (v : transform_var sp1 sp2) : time_transform_expr sp1 sp2
| compose_lit {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame} {sp2 : time_space f2} (t1 : time_transform sp1.value sp2)
{f3 : time_frame_expr} {sp3 : time_space_expr f3} (t2 : time_transform sp2 sp3.value) : time_transform_expr sp1 sp3
| inv_lit {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2} (t : time_transform sp2.value sp1.value) : time_transform_expr sp1 sp2
| compose
{f1 : time_frame_expr} {sp1 : time_space_expr f1}
{f2 : time_frame_expr} {sp2 : time_space_expr f2}
{f3 : time_frame_expr} {sp3 : time_space_expr f3}
(t1 : time_transform_expr sp1 sp3) (t2 : time_transform_expr sp3 sp2) : time_transform_expr sp1 sp2
| inv
{f1 : time_frame_expr} {sp1 : time_space_expr f1}
{f2 : time_frame_expr} {sp2 : time_space_expr f2}
(tr : time_transform_expr sp2 sp1) : time_transform_expr sp1 sp2
class time_transform_has_lit
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) :=
(cast : time_transform sp1.value sp2.value → time_transform_expr sp1 sp2)
notation `|`tlit`|` := time_transform_has_lit.cast tlit
instance time_transform_lit
{f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2} : time_transform_has_lit sp1 sp2 :=
⟨λt, time_transform_expr.lit t⟩
abbreviation transform_env
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) :=
transform_var sp1 sp2 → time_transform sp1.value sp2.value
abbreviation transform_eval
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) :=
transform_env sp1 sp2 → time_transform_expr sp1 sp2 → time_transform sp1.value sp2.value
noncomputable def default_transform_env
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) : transform_env sp1 sp2:=
λv, sp1.value.mk_time_transform_to sp2.value
noncomputable def default_transform_eval
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) : transform_eval sp1 sp2 :=
λenv_, λexpr_, sp1.value.mk_time_transform_to sp2.value
noncomputable def static_transform_eval
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) : transform_eval sp1 sp2
| env_ (time_transform_expr.lit tr) := tr
| env_ (time_transform_expr.var v) := env_ v
| env_ (time_transform_expr.compose_lit t1 t2) := ⟨⟨t1.1.1.trans t2.1.1⟩⟩
| env_ (time_transform_expr.inv_lit t) := ⟨⟨(t.1.1).symm⟩⟩
| env_ expr_ := default_transform_eval sp1 sp2 (default_transform_env sp1 sp2) expr_
noncomputable def time_transform_expr.value {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2}
(expr_ : time_transform_expr sp1 sp2) : time_transform sp1.value sp2.value :=
((static_transform_eval sp1 sp2) (default_transform_env sp1 sp2) expr_)
class transform_has_inv
{f1 : time_frame_expr} (sp1 : time_space_expr f1) {f2 : time_frame_expr} (sp2 : time_space_expr f2) :=
(inv : time_transform_expr sp1 sp2 → time_transform_expr sp2 sp1)
notation tr⁻¹:= transform_has_inv.inv tr
noncomputable instance transform_inv {f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2}
: transform_has_inv sp1 sp2 := ⟨λt,
begin
let lit := t.value,
exact (time_transform_expr.inv_lit lit),
end⟩
noncomputable def time_transform_expr.trans
{f1 : time_frame_expr} {sp1 : time_space_expr f1} {f2 : time_frame_expr} {sp2 : time_space_expr f2}
{f3 : time_frame_expr} {sp3 : time_space_expr f3} (expr_ : time_transform_expr sp1 sp2) : time_transform_expr sp2 sp3 → time_transform_expr sp1 sp3
:= λt2,
time_transform_expr.compose_lit expr_.value t2.value
structure duration_var {f : time_frame_expr} (sp : time_space_expr f) extends var
structure time_var {f : time_frame_expr} (sp : time_space_expr f) extends var
set_option trace.app_builder true --need to fix scalar for this to work
mutual inductive duration_expr, time_expr {f : time_frame_expr} (sp : time_space_expr f)
with duration_expr : Type 1
| zero : duration_expr
| one : duration_expr
| lit (v : duration sp.value) : duration_expr
| var (v : duration_var sp) : duration_expr
| add_dur_dur (d1 : duration_expr) (d2 : duration_expr) : duration_expr
| neg_dur (d : duration_expr) : duration_expr
| sub_dur_dur (d1 : duration_expr) (d2 : duration_expr) : duration_expr
| sub_time_time (t1 : time_expr) (t2 : time_expr) : duration_expr
| smul_dur (k : scalar_expr) (d : duration_expr) : duration_expr
| apply_duration_lit {f2 : time_frame_expr} {sp2 : time_space_expr f2} (v : time_transform_expr sp2 sp)
(d : duration sp2.value) : duration_expr
with time_expr : Type 1
| lit (p : time sp.value) : time_expr
| var (v : time_var sp) : time_expr
| add_dur_time (d : duration_expr) (t : time_expr) : time_expr
| apply_time_lit {f2 : time_frame_expr} {sp2 : time_space_expr f2} (v : time_transform_expr sp2 sp)
(t : time sp2.value) : time_expr
abbreviation duration_env {f : time_frame_expr} (sp : time_space_expr f) :=
duration_var sp → duration sp.value
attribute [elab_as_eliminator]
abbreviation time_env {f : time_frame_expr} (sp : time_space_expr f) :=
time_var sp → time sp.value
abbreviation duration_eval := Π{f : time_frame_expr} (sp : time_space_expr f),
time_env sp → duration_env sp → duration_expr sp → duration sp.value
abbreviation time_eval := Π{f : time_frame_expr} (sp : time_space_expr f),
time_env sp → duration_env sp → time_expr sp → time sp.value
@[simp]
noncomputable def default_duration_env {f : time_frame_expr} (sp : time_space_expr f) : duration_env sp := λv, (mk_duration sp.value 1)
@[simp]
noncomputable def default_duration_eval : duration_eval
:= λf sp, λtenv_, λdenv_, λexpr_,
begin
repeat {exact (mk_duration sp.value 1)}
end
@[simp]
noncomputable def default_time_env {f : time_frame_expr} (sp : time_space_expr f) : time_env sp
:= (λv, (mk_time sp.value 1))
set_option eqn_compiler.max_steps 8192
@[simp, reducible]
noncomputable mutual def static_duration_eval, static_time_eval
with static_duration_eval : duration_eval
| f sp tenv_ denv_ (duration_expr.zero) := 0
| f sp tenv_ denv_ (duration_expr.one) := mk_duration sp.value 1
| f sp tenv_ denv_ (duration_expr.lit d) := d
| f sp tenv_ denv_ (duration_expr.var v) := denv_ v
| f sp tenv_ denv_ (duration_expr.add_dur_dur d1 d2) := (static_duration_eval sp tenv_ denv_ d1) +ᵥ (static_duration_eval sp tenv_ denv_ d2)
| f sp tenv_ denv_ (duration_expr.neg_dur d) := -(static_duration_eval sp tenv_ denv_ d)
| f sp tenv_ denv_ (duration_expr.sub_dur_dur d1 d2) := (static_duration_eval sp tenv_ denv_ d1) -ᵥ (static_duration_eval sp tenv_ denv_ d2)
| f sp tenv_ denv_ (duration_expr.sub_time_time t1 t2) := (static_time_eval sp tenv_ denv_ t1) -ᵥ (static_time_eval sp tenv_ denv_ t2)
| f sp tenv_ denv_ (duration_expr.smul_dur s d) := (static_scalar_eval default_scalar_env s)•(static_duration_eval sp tenv_ denv_ d)
| f sp tenv_ denv_ (duration_expr.apply_duration_lit t d) := t.value.transform_duration d
with static_time_eval : time_eval
| f sp tenv_ denv_ (time_expr.lit p) := p
| f sp tenv_ denv_ (time_expr.var v) := tenv_ v
| f sp tenv_ denv_ (time_expr.add_dur_time d t) := (static_duration_eval sp tenv_ denv_ d) +ᵥ (static_time_eval sp tenv_ denv_ t)
| f sp tenv_ denv_ (time_expr.apply_time_lit tr t) := tr.value.transform_time t
@[simp]
noncomputable def default_time_eval : time_eval := λf sp, λtenv_, λdenv_, λexpr_,
begin
cases expr_,
exact expr_,
exact default_time_env sp expr_,
repeat {exact (mk_time sp.value 1)}
end
@[simp]
noncomputable def time_expr.value {f : time_frame_expr} {sp : time_space_expr f} (expr_ : time_expr sp) : time sp.value :=
(static_time_eval sp) (default_time_env sp) (default_duration_env sp) expr_
@[simp]
noncomputable def duration_expr.value {f : time_frame_expr} {sp : time_space_expr f} (expr_ : duration_expr sp) : duration sp.value :=
(static_duration_eval sp) (default_time_env sp) (default_duration_env sp) expr_
class time_has_lit {f : time_frame_expr} (sp : time_space_expr f) :=
(cast : time sp.value → time_expr sp)
notation `|`tlit`|` := time_has_lit.cast tlit
instance time_lit {f : time_frame_expr} (sp : time_space_expr f) : time_has_lit sp :=
⟨λt : time sp.value, time_expr.lit t⟩
class duration_has_lit {f : time_frame_expr} (sp : time_space_expr f) :=
(cast : duration sp.value → duration_expr sp)
notation `|`tlit`|` := duration_has_lit.cast tlit
instance duration_lit {f : time_frame_expr} (sp : time_space_expr f) : duration_has_lit sp :=
⟨λt : duration sp.value, duration_expr.lit t⟩
class time_frame_has_lit :=
(cast : time_frame → time_frame_expr)
notation `|`flit`|` := time_frame_has_lit.cast flit
instance time_frame_lit : time_frame_has_lit :=
⟨λf, time_frame_expr.lit f⟩
class time_space_has_lit (f : time_frame_expr ) :=
(cast : time_space f.value → time_space_expr f)
notation `|`slit`|` := time_space_has_lit.cast slit
instance time_space_lit {f : time_frame_expr} : time_space_has_lit f :=
⟨λs, time_space_expr.lit s⟩
variables {f : time_frame_expr} {sp : time_space_expr f}
#check mk_frame
noncomputable def mk_time_frame_expr {f : time_frame_expr} {sp : time_space_expr f} (o : time_expr sp) (b : duration_expr sp) : time_frame_expr :=
|(mk_time_frame o.value b.value)|
def mk_time_space_expr (f : time_frame_expr) : time_space_expr f :=
time_space_expr.mk
instance has_one_dur_expr : has_one (duration_expr sp) := ⟨duration_expr.one⟩
instance has_add_dur_expr : has_add (duration_expr sp) := ⟨λ v1 v2, duration_expr.add_dur_dur v1 v2 ⟩
instance has_zero_dur_expr : has_zero (duration_expr sp) := ⟨duration_expr.zero⟩
instance has_neg_dur_expr : has_neg (duration_expr sp) := ⟨λv1, duration_expr.neg_dur v1⟩
instance has_sub_dur_expr : has_sub (duration_expr sp) := ⟨λ v1 v2, duration_expr.sub_dur_dur v1 v2⟩
instance : has_vadd (duration_expr sp) (time_expr sp) := ⟨λv p, time_expr.add_dur_time v p⟩
instance : has_vsub (duration_expr sp) (time_expr sp) := ⟨λt1 t2, duration_expr.sub_time_time t1 t2⟩
notation t+ᵥv := has_vadd.vadd v t
notation k•d := duration_expr.smul_dur k d
notation d•k := duration_expr.smul_dur k d
notation tr⬝d := duration_expr.apply_duration_lit tr d
notation tr⬝t := time_expr.apply_time_lit tr t
notation tr∘tr := time_transform_expr.compose_lit tr tr
class time_transform_has_complit
{f1 : time_frame_expr} (sp1 : time_space_expr f1)
{f2 : time_frame_expr} (sp2 : time_space_expr f2)
{f3 : time_frame_expr} (sp3 : time_space_expr f3)
:=
(cast :
time_transform sp1.value sp2.value →
time_transform sp2.value sp3.value →
time_transform_expr sp1 sp3)
notation tr1`∘`tr2 := time_transform_has_complit.cast tr1 tr2
noncomputable instance timetrcomplit
{f1 : time_frame_expr} {sp1 : time_space_expr f1}
{f2 : time_frame_expr} {sp2 : time_space_expr f2}
{f3 : time_frame_expr} {sp3 : time_space_expr f3} : time_transform_has_complit sp1 sp2 sp3 :=
⟨λt1 t2, time_transform_expr.compose_lit t1 t2⟩
class time_transform_has_comp
{f1 : time_frame_expr} (sp1 : time_space_expr f1)
{f2 : time_frame_expr} (sp2 : time_space_expr f2)
{f3 : time_frame_expr} (sp3 : time_space_expr f3)
:=
(cast :
time_transform_expr sp1 sp2 →
time_transform_expr sp2 sp3 →
time_transform_expr sp1 sp3)
notation tr1`∘`tr2 := time_transform_has_comp.cast tr1 tr2
instance timetrcomp
{f1 : time_frame_expr} {sp1 : time_space_expr f1}
{f2 : time_frame_expr} {sp2 : time_space_expr f2}
{f3 : time_frame_expr} {sp3 : time_space_expr f3} : time_transform_has_comp sp1 sp2 sp3 :=
⟨λt1 t2, time_transform_expr.compose t1 t2⟩
end lang.time
|
e11ca274ff0a3d7eeddacc94fae438e8e9a03a9d | 675b8263050a5d74b89ceab381ac81ce70535688 | /src/order/bounded_lattice.lean | 9feb8e7c83aeb4071d2530e0e37b61e1c362afb3 | [
"Apache-2.0"
] | permissive | vozor/mathlib | 5921f55235ff60c05f4a48a90d616ea167068adf | f7e728ad8a6ebf90291df2a4d2f9255a6576b529 | refs/heads/master | 1,675,607,702,231 | 1,609,023,279,000 | 1,609,023,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 42,111 | 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
Defines bounded lattice type class hierarchy.
Includes the Prop and fun instances.
-/
import order.lattice
import data.option.basic
import tactic.pi_instances
set_option old_structure_cmd true
universes u v
variables {α : Type u} {β : Type v}
/-- Typeclass for the `⊤` (`\top`) notation -/
class has_top (α : Type u) := (top : α)
/-- Typeclass for the `⊥` (`\bot`) notation -/
class has_bot (α : Type u) := (bot : α)
notation `⊤` := has_top.top
notation `⊥` := has_bot.bot
attribute [pattern] has_bot.bot has_top.top
/-- An `order_top` is a partial order with a maximal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_top (α : Type u) extends has_top α, partial_order α :=
(le_top : ∀ a : α, a ≤ ⊤)
section order_top
variables [order_top α] {a b : α}
@[simp] theorem le_top : a ≤ ⊤ :=
order_top.le_top a
theorem top_unique (h : ⊤ ≤ a) : a = ⊤ :=
le_antisymm le_top h
-- TODO: delete in favor of the next?
theorem eq_top_iff : a = ⊤ ↔ ⊤ ≤ a :=
⟨assume eq, eq.symm ▸ le_refl ⊤, top_unique⟩
@[simp] theorem top_le_iff : ⊤ ≤ a ↔ a = ⊤ :=
⟨top_unique, λ h, h.symm ▸ le_refl ⊤⟩
@[simp] theorem not_top_lt : ¬ ⊤ < a :=
assume h, lt_irrefl a (lt_of_le_of_lt le_top h)
theorem eq_top_mono (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ :=
top_le_iff.1 $ h₂ ▸ h
lemma lt_top_iff_ne_top : a < ⊤ ↔ a ≠ ⊤ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (⊤ ≤ a) := decidable_of_iff' _ top_le_iff,
by simp [-top_le_iff, lt_iff_le_not_le, not_iff_not.2 (@top_le_iff _ _ a)]
end
lemma ne_top_of_lt (h : a < b) : a ≠ ⊤ :=
lt_top_iff_ne_top.1 $ lt_of_lt_of_le h le_top
theorem ne_top_of_le_ne_top {a b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ :=
assume ha, hb $ top_unique $ ha ▸ hab
end order_top
lemma strict_mono.top_preimage_top' [linear_order α] [order_top β]
{f : α → β} (H : strict_mono f) {a} (h_top : f a = ⊤) (x : α) :
x ≤ a :=
H.top_preimage_top (λ p, by { rw h_top, exact le_top }) x
theorem order_top.ext_top {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊤ : α) = ⊤ :=
top_unique $ by rw ← H; apply le_top
theorem order_top.ext {α} {A B : order_top α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_top.ext_top H,
casesI A, casesI B,
injection this; congr'
end
/-- An `order_bot` is a partial order with a minimal element.
(We could state this on preorders, but then it wouldn't be unique
so distinguishing one would seem odd.) -/
class order_bot (α : Type u) extends has_bot α, partial_order α :=
(bot_le : ∀ a : α, ⊥ ≤ a)
section order_bot
variables [order_bot α] {a b : α}
@[simp] theorem bot_le : ⊥ ≤ a := order_bot.bot_le a
theorem bot_unique (h : a ≤ ⊥) : a = ⊥ :=
le_antisymm h bot_le
-- TODO: delete?
theorem eq_bot_iff : a = ⊥ ↔ a ≤ ⊥ :=
⟨assume eq, eq.symm ▸ le_refl ⊥, bot_unique⟩
@[simp] theorem le_bot_iff : a ≤ ⊥ ↔ a = ⊥ :=
⟨bot_unique, assume h, h.symm ▸ le_refl ⊥⟩
@[simp] theorem not_lt_bot : ¬ a < ⊥ :=
assume h, lt_irrefl a (lt_of_lt_of_le h bot_le)
theorem ne_bot_of_le_ne_bot {a b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ :=
assume ha, hb $ bot_unique $ ha ▸ hab
theorem eq_bot_mono (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ :=
le_bot_iff.1 $ h₂ ▸ h
lemma bot_lt_iff_ne_bot : ⊥ < a ↔ a ≠ ⊥ :=
begin
haveI := classical.dec_eq α,
haveI : decidable (a ≤ ⊥) := decidable_of_iff' _ le_bot_iff,
simp [-le_bot_iff, lt_iff_le_not_le, not_iff_not.2 (@le_bot_iff _ _ a)]
end
lemma ne_bot_of_gt (h : a < b) : b ≠ ⊥ :=
bot_lt_iff_ne_bot.1 $ lt_of_le_of_lt bot_le h
end order_bot
lemma strict_mono.bot_preimage_bot' [linear_order α] [order_bot β]
{f : α → β} (H : strict_mono f) {a} (h_bot : f a = ⊥) (x : α) :
a ≤ x :=
H.bot_preimage_bot (λ p, by { rw h_bot, exact bot_le }) x
theorem order_bot.ext_bot {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) :
(by haveI := A; exact ⊥ : α) = ⊥ :=
bot_unique $ by rw ← H; apply bot_le
theorem order_bot.ext {α} {A B : order_bot α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have := partial_order.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection this; congr'
end
/-- A `semilattice_sup_top` is a semilattice with top and join. -/
class semilattice_sup_top (α : Type u) extends order_top α, semilattice_sup α
section semilattice_sup_top
variables [semilattice_sup_top α] {a : α}
@[simp] theorem top_sup_eq : ⊤ ⊔ a = ⊤ :=
sup_of_le_left le_top
@[simp] theorem sup_top_eq : a ⊔ ⊤ = ⊤ :=
sup_of_le_right le_top
end semilattice_sup_top
/-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/
class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α
section semilattice_sup_bot
variables [semilattice_sup_bot α] {a b : α}
@[simp] theorem bot_sup_eq : ⊥ ⊔ a = a :=
sup_of_le_right bot_le
@[simp] theorem sup_bot_eq : a ⊔ ⊥ = a :=
sup_of_le_left bot_le
@[simp] theorem sup_eq_bot_iff : a ⊔ b = ⊥ ↔ (a = ⊥ ∧ b = ⊥) :=
by rw [eq_bot_iff, sup_le_iff]; simp
end semilattice_sup_bot
instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ :=
{ bot := 0, bot_le := nat.zero_le, .. nat.distrib_lattice }
/-- A `semilattice_inf_top` is a semilattice with top and meet. -/
class semilattice_inf_top (α : Type u) extends order_top α, semilattice_inf α
section semilattice_inf_top
variables [semilattice_inf_top α] {a b : α}
@[simp] theorem top_inf_eq : ⊤ ⊓ a = a :=
inf_of_le_right le_top
@[simp] theorem inf_top_eq : a ⊓ ⊤ = a :=
inf_of_le_left le_top
@[simp] theorem inf_eq_top_iff : a ⊓ b = ⊤ ↔ (a = ⊤ ∧ b = ⊤) :=
by rw [eq_top_iff, le_inf_iff]; simp
end semilattice_inf_top
/-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/
class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α
section semilattice_inf_bot
variables [semilattice_inf_bot α] {a : α}
@[simp] theorem bot_inf_eq : ⊥ ⊓ a = ⊥ :=
inf_of_le_left bot_le
@[simp] theorem inf_bot_eq : a ⊓ ⊥ = ⊥ :=
inf_of_le_right bot_le
end semilattice_inf_bot
/- Bounded lattices -/
/-- A bounded lattice is a lattice with a top and bottom element,
denoted `⊤` and `⊥` respectively. This allows for the interpretation
of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/
class bounded_lattice (α : Type u) extends lattice α, order_top α, order_bot α
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α :=
{ le_top := assume x, @le_top α _ x, ..bl }
@[priority 100] -- see Note [lower instance priority]
instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α :=
{ bot_le := assume x, @bot_le α _ x, ..bl }
theorem bounded_lattice.ext {α} {A B : bounded_lattice α}
(H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B :=
begin
have H1 : @bounded_lattice.to_lattice α A =
@bounded_lattice.to_lattice α B := lattice.ext H,
have H2 := order_bot.ext H,
have H3 : @bounded_lattice.to_order_top α A =
@bounded_lattice.to_order_top α B := order_top.ext H,
have tt := order_bot.ext_bot H,
casesI A, casesI B,
injection H1; injection H2; injection H3; congr'
end
/-- A bounded distributive lattice is exactly what it sounds like. -/
class bounded_distrib_lattice α extends distrib_lattice α, bounded_lattice α
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨assume : a ⊓ b = ⊥,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [this, inf_le_right],
assume : a ≤ c,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by { rw [inf_comm], exact inf_le_inf_left _ this }
... = ⊥ : h₂⟩
/- Prop instance -/
instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop :=
{ le := λa b, a → b,
le_refl := assume _, id,
le_trans := assume a b c f g, g ∘ f,
le_antisymm := assume a b Hab Hba, propext ⟨Hab, Hba⟩,
sup := or,
le_sup_left := @or.inl,
le_sup_right := @or.inr,
sup_le := assume a b c, or.rec,
inf := and,
inf_le_left := @and.left,
inf_le_right := @and.right,
le_inf := assume a b c Hab Hac Ha, and.intro (Hab Ha) (Hac Ha),
le_sup_inf := assume a b c H, or_iff_not_imp_left.2 $
λ Ha, ⟨H.1.resolve_left Ha, H.2.resolve_left Ha⟩,
top := true,
le_top := assume a Ha, true.intro,
bot := false,
bot_le := @false.elim }
noncomputable instance Prop.linear_order : linear_order Prop :=
{ le_total := by intros p q; change (p → q) ∨ (q → p); tauto!,
decidable_le := classical.dec_rel _,
.. (_ : partial_order Prop) }
@[simp]
lemma le_iff_imp {p q : Prop} : p ≤ q ↔ (p → q) := iff.rfl
section logic
variable [preorder α]
theorem monotone_and {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∧ q x) :=
assume a b h, and.imp (m_p h) (m_q h)
-- Note: by finish [monotone] doesn't work
theorem monotone_or {p q : α → Prop} (m_p : monotone p) (m_q : monotone q) :
monotone (λx, p x ∨ q x) :=
assume a b h, or.imp (m_p h) (m_q h)
end logic
instance pi.order_bot {α : Type*} {β : α → Type*} [∀ a, order_bot $ β a] : order_bot (Π a, β a) :=
{ bot := λ _, ⊥,
bot_le := λ x a, bot_le,
.. pi.partial_order }
/- Function lattices -/
instance pi.has_sup {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] : has_sup (Π i, α i) :=
⟨λ f g i, f i ⊔ g i⟩
@[simp] lemma sup_apply {ι : Type*} {α : ι → Type*} [Π i, has_sup (α i)] (f g : Π i, α i) (i : ι) :
(f ⊔ g) i = f i ⊔ g i :=
rfl
instance pi.has_inf {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] : has_inf (Π i, α i) :=
⟨λ f g i, f i ⊓ g i⟩
@[simp] lemma inf_apply {ι : Type*} {α : ι → Type*} [Π i, has_inf (α i)] (f g : Π i, α i) (i : ι) :
(f ⊓ g) i = f i ⊓ g i :=
rfl
instance pi.has_bot {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] : has_bot (Π i, α i) :=
⟨λ i, ⊥⟩
@[simp] lemma bot_apply {ι : Type*} {α : ι → Type*} [Π i, has_bot (α i)] (i : ι) :
(⊥ : Π i, α i) i = ⊥ :=
rfl
instance pi.has_top {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] : has_top (Π i, α i) :=
⟨λ i, ⊤⟩
@[simp] lemma top_apply {ι : Type*} {α : ι → Type*} [Π i, has_top (α i)] (i : ι) :
(⊤ : Π i, α i) i = ⊤ :=
rfl
instance pi.semilattice_sup {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup (α i)] :
semilattice_sup (Π i, α i) :=
by refine_struct { sup := (⊔), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf (α i)] :
semilattice_inf (Π i, α i) :=
by refine_struct { inf := (⊓), .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_bot (α i)] :
semilattice_inf_bot (Π i, α i) :=
by refine_struct { inf := (⊓), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_inf_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_inf_top (α i)] :
semilattice_inf_top (Π i, α i) :=
by refine_struct { inf := (⊓), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_bot {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_bot (α i)] :
semilattice_sup_bot (Π i, α i) :=
by refine_struct { sup := (⊔), bot := ⊥, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.semilattice_sup_top {ι : Type*} {α : ι → Type*} [Π i, semilattice_sup_top (α i)] :
semilattice_sup_top (Π i, α i) :=
by refine_struct { sup := (⊔), top := ⊤, .. pi.partial_order }; tactic.pi_instance_derive_field
instance pi.lattice {ι : Type*} {α : ι → Type*} [Π i, lattice (α i)] : lattice (Π i, α i) :=
{ .. pi.semilattice_sup, .. pi.semilattice_inf }
instance pi.bounded_lattice {ι : Type*} {α : ι → Type*} [Π i, bounded_lattice (α i)] :
bounded_lattice (Π i, α i) :=
{ .. pi.semilattice_sup_top, .. pi.semilattice_inf_bot }
lemma eq_bot_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊥ : α) :=
eq_bot_mono le_top (eq.symm hα)
lemma eq_top_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = ⊤) (x : α) :
x = (⊤ : α) :=
eq_top_mono bot_le hα
lemma subsingleton_of_top_le_bot {α : Type*} [bounded_lattice α] (h : (⊤ : α) ≤ (⊥ : α)) :
subsingleton α :=
⟨λ a b, le_antisymm (le_trans le_top $ le_trans h bot_le) (le_trans le_top $ le_trans h bot_le)⟩
lemma subsingleton_of_bot_eq_top {α : Type*} [bounded_lattice α] (hα : (⊥ : α) = (⊤ : α)) :
subsingleton α :=
subsingleton_of_top_le_bot (ge_of_eq hα)
/-- Attach `⊥` to a type. -/
def with_bot (α : Type*) := option α
namespace with_bot
meta instance {α} [has_to_format α] : has_to_format (with_bot α) :=
{ to_format := λ x,
match x with
| none := "⊥"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_bot α) := ⟨some⟩
instance has_bot : has_bot (with_bot α) := ⟨none⟩
instance : inhabited (with_bot α) := ⟨⊥⟩
lemma none_eq_bot : (none : with_bot α) = (⊥ : with_bot α) := rfl
lemma some_eq_coe (a : α) : (some a : with_bot α) = (↑a : with_bot α) := rfl
/-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/
@[elab_as_eliminator]
def rec_bot_coe {C : with_bot α → Sort*} (h₁ : C ⊥) (h₂ : Π (a : α), C a) :
Π (n : with_bot α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_bot α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_bot α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₂, ∀ a ∈ o₁, a < b }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_bot α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
lemma bot_lt_some [has_lt α] (a : α) : (⊥ : with_bot α) < some a :=
⟨a, rfl, λ b hb, (option.not_mem_none _ hb).elim⟩
lemma bot_lt_coe [has_lt α] (a : α) : (⊥ : with_bot α) < a := bot_lt_some a
instance [preorder α] : preorder (with_bot α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₁, ∃ b ∈ o₂, a ≤ b,
lt := (<),
lt_iff_le_not_le := by intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<)];
split; refl,
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ a ha,
let ⟨b, hb, ab⟩ := h₁ a ha, ⟨c, hc, bc⟩ := h₂ b hb in
⟨c, hc, le_trans ab bc⟩ }
instance partial_order [partial_order α] : partial_order (with_bot α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₁ with a,
{ cases o₂ with b, {refl},
rcases h₂ b rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ a rfl with ⟨b, ⟨⟩, h₁'⟩,
rcases h₂ b rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_bot.preorder }
instance order_bot [partial_order α] : order_bot (with_bot α) :=
{ bot_le := λ a a' h, option.no_confusion h,
..with_bot.partial_order, ..with_bot.has_bot }
@[simp, norm_cast] theorem coe_le_coe [preorder α] {a b : α} :
(a : with_bot α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h a rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨b, rfl, h⟩⟩
@[simp] theorem some_le_some [preorder α] {a b : α} :
@has_le.le (with_bot α) _ (some a) (some b) ↔ a ≤ b := coe_le_coe
theorem coe_le [partial_order α] {a b : α} :
∀ {o : option α}, b ∈ o → ((a : with_bot α) ≤ o ↔ a ≤ b)
| _ rfl := coe_le_coe
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_bot α) < b ↔ a < b := some_lt_some
lemma le_coe_get_or_else [preorder α] : ∀ (a : with_bot α) (b : α), a ≤ a.get_or_else b
| (some a) b := le_refl a
| none b := λ _ h, option.no_confusion h
@[simp] lemma get_or_else_bot (a : α) : option.get_or_else (⊥ : with_bot α) a = a := rfl
lemma get_or_else_bot_le_iff [order_bot α] {a : with_bot α} {b : α} :
a.get_or_else ⊥ ≤ b ↔ a ≤ b :=
by cases a; simp [none_eq_bot, some_eq_coe]
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_bot α) (≤)
| none x := is_true $ λ a h, option.no_confusion h
| (some x) (some y) :=
if h : x ≤ y
then is_true (some_le_some.2 h)
else is_false $ by simp *
| (some x) none := is_false $ λ h, by rcases h x rfl with ⟨y, ⟨_⟩, _⟩
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_bot α) (<)
| none (some x) := is_true $ by existsi [x,rfl]; rintros _ ⟨⟩
| (some x) (some y) :=
if h : x < y
then is_true $ by simp *
else is_false $ by simp *
| x none := is_false $ by rintro ⟨a,⟨⟨⟩⟩⟩
instance linear_order [linear_order α] : linear_order (with_bot α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inl bot_le},
cases o₂ with b, {exact or.inr bot_le},
simp [le_total]
end,
decidable_le := with_bot.decidable_le,
decidable_lt := with_bot.decidable_lt,
..with_bot.partial_order }
instance semilattice_sup [semilattice_sup α] : semilattice_sup_bot (with_bot α) :=
{ sup := option.lift_or_get (⊔),
le_sup_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
le_sup_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₁ with b; cases o₂ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, sup_le h₁' h₂⟩ }
end,
..with_bot.order_bot }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_bot (with_bot α) :=
{ inf := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊓ b)),
inf_le_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_left⟩
end,
inf_le_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, inf_le_right⟩
end,
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, le_inf ab ac⟩
end,
..with_bot.order_bot }
instance lattice [lattice α] : lattice (with_bot α) :=
{ ..with_bot.semilattice_sup, ..with_bot.semilattice_inf }
theorem lattice_eq_DLO [linear_order α] :
lattice_of_linear_order = @with_bot.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [linear_order α] (x y : with_bot α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [linear_order α] (x y : with_bot α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_top [order_top α] : order_top (with_bot α) :=
{ top := some ⊤,
le_top := λ o a ha, by cases ha; exact ⟨_, rfl, le_top⟩,
..with_bot.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_bot α) :=
{ ..with_bot.lattice, ..with_bot.order_top, ..with_bot.order_bot }
lemma well_founded_lt [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_bot α → with_bot α → Prop) :=
have acc_bot : acc ((<) : with_bot α → with_bot α → Prop) ⊥ :=
acc.intro _ (λ a ha, (not_le_of_gt ha bot_le).elim),
⟨λ a, option.rec_on a acc_bot (λ a, acc.intro _ (λ b, option.rec_on b (λ _, acc_bot)
(λ b, well_founded.induction h b
(show ∀ b : α, (∀ c, c < b → (c : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) c) → (b : with_bot α) < a →
acc ((<) : with_bot α → with_bot α → Prop) b,
from λ b ih hba, acc.intro _ (λ c, option.rec_on c (λ _, acc_bot)
(λ c hc, ih _ (some_lt_some.1 hc) (lt_trans hc hba)))))))⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_bot_order α] :
densely_ordered (with_bot α) :=
⟨ assume a b,
match a, b with
| a, none := assume h : a < ⊥, (not_lt_bot h).elim
| none, some b := assume h, let ⟨a, ha⟩ := no_bot b in ⟨a, bot_lt_coe a, coe_lt_coe.2 ha⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
end with_bot
--TODO(Mario): Construct using order dual on with_bot
/-- Attach `⊤` to a type. -/
def with_top (α : Type*) := option α
namespace with_top
meta instance {α} [has_to_format α] : has_to_format (with_top α) :=
{ to_format := λ x,
match x with
| none := "⊤"
| (some x) := to_fmt x
end }
instance : has_coe_t α (with_top α) := ⟨some⟩
instance has_top : has_top (with_top α) := ⟨none⟩
instance : inhabited (with_top α) := ⟨⊤⟩
lemma none_eq_top : (none : with_top α) = (⊤ : with_top α) := rfl
lemma some_eq_coe (a : α) : (some a : with_top α) = (↑a : with_top α) := rfl
/-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/
@[elab_as_eliminator]
def rec_top_coe {C : with_top α → Sort*} (h₁ : C ⊤) (h₂ : Π (a : α), C a) :
Π (n : with_top α), C n :=
option.rec h₁ h₂
@[norm_cast]
theorem coe_eq_coe {a b : α} : (a : with_top α) = b ↔ a = b :=
by rw [← option.some.inj_eq a b]; refl
@[simp] theorem top_ne_coe {a : α} : ⊤ ≠ (a : with_top α) .
@[simp] theorem coe_ne_top {a : α} : (a : with_top α) ≠ ⊤ .
@[priority 10]
instance has_lt [has_lt α] : has_lt (with_top α) :=
{ lt := λ o₁ o₂ : option α, ∃ b ∈ o₁, ∀ a ∈ o₂, b < a }
@[priority 10]
instance has_le [has_le α] : has_le (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a }
@[simp] theorem some_lt_some [has_lt α] {a b : α} :
@has_lt.lt (with_top α) _ (some a) (some b) ↔ a < b :=
by simp [(<)]
@[simp] theorem some_le_some [has_le α] {a b : α} :
@has_le.le (with_top α) _ (some a) (some b) ↔ a ≤ b :=
by simp [(≤)]
@[simp] theorem le_none [has_le α] {a : with_top α} :
@has_le.le (with_top α) _ a none :=
by simp [(≤)]
@[simp] theorem some_lt_none [has_lt α] {a : α} :
@has_lt.lt (with_top α) _ (some a) none :=
by simp [(<)]; existsi a; refl
instance [preorder α] : preorder (with_top α) :=
{ le := λ o₁ o₂ : option α, ∀ a ∈ o₂, ∃ b ∈ o₁, b ≤ a,
lt := (<),
lt_iff_le_not_le := by { intros; cases a; cases b;
simp [lt_iff_le_not_le]; simp [(<),(≤)] },
le_refl := λ o a ha, ⟨a, ha, le_refl _⟩,
le_trans := λ o₁ o₂ o₃ h₁ h₂ c hc,
let ⟨b, hb, bc⟩ := h₂ c hc, ⟨a, ha, ab⟩ := h₁ b hb in
⟨a, ha, le_trans ab bc⟩,
}
instance partial_order [partial_order α] : partial_order (with_top α) :=
{ le_antisymm := λ o₁ o₂ h₁ h₂, begin
cases o₂ with b,
{ cases o₁ with a, {refl},
rcases h₂ a rfl with ⟨_, ⟨⟩, _⟩ },
{ rcases h₁ b rfl with ⟨a, ⟨⟩, h₁'⟩,
rcases h₂ a rfl with ⟨_, ⟨⟩, h₂'⟩,
rw le_antisymm h₁' h₂' }
end,
.. with_top.preorder }
instance order_top [partial_order α] : order_top (with_top α) :=
{ le_top := λ a a' h, option.no_confusion h,
..with_top.partial_order, .. with_top.has_top }
@[simp, norm_cast] theorem coe_le_coe [partial_order α] {a b : α} :
(a : with_top α) ≤ b ↔ a ≤ b :=
⟨λ h, by rcases h b rfl with ⟨_, ⟨⟩, h⟩; exact h,
λ h a' e, option.some_inj.1 e ▸ ⟨a, rfl, h⟩⟩
theorem le_coe [partial_order α] {a b : α} :
∀ {o : option α}, a ∈ o →
(@has_le.le (with_top α) _ o b ↔ a ≤ b)
| _ rfl := coe_le_coe
theorem le_coe_iff [partial_order α] {b : α} : ∀{x : with_top α}, x ≤ b ↔ (∃a:α, x = a ∧ a ≤ b)
| (some a) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem coe_le_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a ≤ x ↔ (∀b:α, x = ↑b → a ≤ b)
| (some b) := by simp [some_eq_coe, coe_eq_coe]
| none := by simp [none_eq_top]
theorem lt_iff_exists_coe [partial_order α] : ∀{a b : with_top α}, a < b ↔ (∃p:α, a = p ∧ ↑p < b)
| (some a) b := by simp [some_eq_coe, coe_eq_coe]
| none b := by simp [none_eq_top]
@[norm_cast]
lemma coe_lt_coe [partial_order α] {a b : α} : (a : with_top α) < b ↔ a < b := some_lt_some
lemma coe_lt_top [partial_order α] (a : α) : (a : with_top α) < ⊤ := some_lt_none
theorem coe_lt_iff [partial_order α] {a : α} : ∀{x : with_top α}, ↑a < x ↔ (∀b:α, x = ↑b → a < b)
| (some b) := by simp [some_eq_coe, coe_eq_coe, coe_lt_coe]
| none := by simp [none_eq_top, coe_lt_top]
lemma not_top_le_coe [partial_order α] (a : α) : ¬ (⊤:with_top α) ≤ ↑a :=
assume h, (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))).elim
instance decidable_le [preorder α] [@decidable_rel α (≤)] : @decidable_rel (with_top α) (≤) :=
λ x y, @with_bot.decidable_le (order_dual α) _ _ y x
instance decidable_lt [has_lt α] [@decidable_rel α (<)] : @decidable_rel (with_top α) (<) :=
λ x y, @with_bot.decidable_lt (order_dual α) _ _ y x
instance linear_order [linear_order α] : linear_order (with_top α) :=
{ le_total := λ o₁ o₂, begin
cases o₁ with a, {exact or.inr le_top},
cases o₂ with b, {exact or.inl le_top},
simp [le_total]
end,
decidable_le := with_top.decidable_le,
decidable_lt := with_top.decidable_lt,
..with_top.partial_order }
instance semilattice_inf [semilattice_inf α] : semilattice_inf_top (with_top α) :=
{ inf := option.lift_or_get (⊓),
inf_le_left := λ o₁ o₂ a ha,
by cases ha; cases o₂; simp [option.lift_or_get],
inf_le_right := λ o₁ o₂ a ha,
by cases ha; cases o₁; simp [option.lift_or_get],
le_inf := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases o₂ with b; cases o₃ with c; cases ha,
{ exact h₂ a rfl },
{ exact h₁ a rfl },
{ rcases h₁ b rfl with ⟨d, ⟨⟩, h₁'⟩,
simp at h₂,
exact ⟨d, rfl, le_inf h₁' h₂⟩ }
end,
..with_top.order_top }
lemma coe_inf [semilattice_inf α] (a b : α) : ((a ⊓ b : α) : with_top α) = a ⊓ b := rfl
instance semilattice_sup [semilattice_sup α] : semilattice_sup_top (with_top α) :=
{ sup := λ o₁ o₂, o₁.bind (λ a, o₂.map (λ b, a ⊔ b)),
le_sup_left := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_left⟩
end,
le_sup_right := λ o₁ o₂ a ha, begin
simp at ha, rcases ha with ⟨b, rfl, c, rfl, rfl⟩,
exact ⟨_, rfl, le_sup_right⟩
end,
sup_le := λ o₁ o₂ o₃ h₁ h₂ a ha, begin
cases ha,
rcases h₁ a rfl with ⟨b, ⟨⟩, ab⟩,
rcases h₂ a rfl with ⟨c, ⟨⟩, ac⟩,
exact ⟨_, rfl, sup_le ab ac⟩
end,
..with_top.order_top }
lemma coe_sup [semilattice_sup α] (a b : α) : ((a ⊔ b : α) : with_top α) = a ⊔ b := rfl
instance lattice [lattice α] : lattice (with_top α) :=
{ ..with_top.semilattice_sup, ..with_top.semilattice_inf }
theorem lattice_eq_DLO [linear_order α] :
lattice_of_linear_order = @with_top.lattice α _ :=
lattice.ext $ λ x y, iff.rfl
theorem sup_eq_max [linear_order α] (x y : with_top α) : x ⊔ y = max x y :=
by rw [← sup_eq_max, lattice_eq_DLO]
theorem inf_eq_min [linear_order α] (x y : with_top α) : x ⊓ y = min x y :=
by rw [← inf_eq_min, lattice_eq_DLO]
instance order_bot [order_bot α] : order_bot (with_top α) :=
{ bot := some ⊥,
bot_le := λ o a ha, by cases ha; exact ⟨_, rfl, bot_le⟩,
..with_top.partial_order }
instance bounded_lattice [bounded_lattice α] : bounded_lattice (with_top α) :=
{ ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma well_founded_lt {α : Type*} [partial_order α] (h : well_founded ((<) : α → α → Prop)) :
well_founded ((<) : with_top α → with_top α → Prop) :=
have acc_some : ∀ a : α, acc ((<) : with_top α → with_top α → Prop) (some a) :=
λ a, acc.intro _ (well_founded.induction h a
(show ∀ b, (∀ c, c < b → ∀ d : with_top α, d < some c → acc (<) d) →
∀ y : with_top α, y < some b → acc (<) y,
from λ b ih c, option.rec_on c (λ hc, (not_lt_of_ge le_top hc).elim)
(λ c hc, acc.intro _ (ih _ (some_lt_some.1 hc))))),
⟨λ a, option.rec_on a (acc.intro _ (λ y, option.rec_on y (λ h, (lt_irrefl _ h).elim)
(λ _ _, acc_some _))) acc_some⟩
instance densely_ordered [partial_order α] [densely_ordered α] [no_top_order α] :
densely_ordered (with_top α) :=
⟨ assume a b,
match a, b with
| none, a := assume h : ⊤ < a, (not_top_lt h).elim
| some a, none := assume h, let ⟨b, hb⟩ := no_top a in ⟨b, coe_lt_coe.2 hb, coe_lt_top b⟩
| some a, some b := assume h, let ⟨a, ha₁, ha₂⟩ := exists_between (coe_lt_coe.1 h) in
⟨a, coe_lt_coe.2 ha₁, coe_lt_coe.2 ha₂⟩
end⟩
lemma lt_iff_exists_coe_btwn [partial_order α] [densely_ordered α] [no_top_order α]
{a b : with_top α} :
(a < b) ↔ (∃ x : α, a < ↑x ∧ ↑x < b) :=
⟨λ h, let ⟨y, hy⟩ := exists_between h, ⟨x, hx⟩ := lt_iff_exists_coe.1 hy.2 in ⟨x, hx.1 ▸ hy⟩,
λ ⟨x, hx⟩, lt_trans hx.1 hx.2⟩
end with_top
namespace subtype
/-- A subtype forms a `⊔`-semilattice if `⊔` preserves the property. -/
protected def semilattice_sup [semilattice_sup α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup {x : α // P x} :=
{ sup := λ x y, ⟨x.1 ⊔ y.1, Psup x.2 y.2⟩,
le_sup_left := λ x y, @le_sup_left _ _ (x : α) y,
le_sup_right := λ x y, @le_sup_right _ _ (x : α) y,
sup_le := λ x y z h1 h2, @sup_le α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊓`-semilattice if `⊓` preserves the property. -/
protected def semilattice_inf [semilattice_inf α] {P : α → Prop}
(Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf {x : α // P x} :=
{ inf := λ x y, ⟨x.1 ⊓ y.1, Pinf x.2 y.2⟩,
inf_le_left := λ x y, @inf_le_left _ _ (x : α) y,
inf_le_right := λ x y, @inf_le_right _ _ (x : α) y,
le_inf := λ x y z h1 h2, @le_inf α _ _ _ _ h1 h2,
..subtype.partial_order P }
/-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/
protected def semilattice_sup_bot [semilattice_sup_bot α] {P : α → Prop}
(Pbot : P ⊥) (Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) : semilattice_sup_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_sup Psup }
/-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/
protected def semilattice_inf_bot [semilattice_inf_bot α] {P : α → Prop}
(Pbot : P ⊥) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) : semilattice_inf_bot {x : α // P x} :=
{ bot := ⟨⊥, Pbot⟩,
bot_le := λ x, @bot_le α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/
protected def semilattice_inf_top [semilattice_inf_top α] {P : α → Prop}
(Ptop : P ⊤) (Pinf : ∀{{x y}}, P x → P y → P (x ⊓ y)) : semilattice_inf_top {x : α // P x} :=
{ top := ⟨⊤, Ptop⟩,
le_top := λ x, @le_top α _ x,
..subtype.semilattice_inf Pinf }
/-- A subtype forms a lattice if `⊔` and `⊓` preserve the property. -/
protected def lattice [lattice α] {P : α → Prop}
(Psup : ∀⦃x y⦄, P x → P y → P (x ⊔ y)) (Pinf : ∀⦃x y⦄, P x → P y → P (x ⊓ y)) :
lattice {x : α // P x} :=
{ ..subtype.semilattice_inf Pinf, ..subtype.semilattice_sup Psup }
end subtype
namespace order_dual
variable (α)
instance [has_bot α] : has_top (order_dual α) := ⟨(⊥ : α)⟩
instance [has_top α] : has_bot (order_dual α) := ⟨(⊤ : α)⟩
instance [order_bot α] : order_top (order_dual α) :=
{ le_top := @bot_le α _,
.. order_dual.partial_order α, .. order_dual.has_top α }
instance [order_top α] : order_bot (order_dual α) :=
{ bot_le := @le_top α _,
.. order_dual.partial_order α, .. order_dual.has_bot α }
instance [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_top α }
instance [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) :=
{ .. order_dual.semilattice_sup α, .. order_dual.order_bot α }
instance [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_top α }
instance [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) :=
{ .. order_dual.semilattice_inf α, .. order_dual.order_bot α }
instance [bounded_lattice α] : bounded_lattice (order_dual α) :=
{ .. order_dual.lattice α, .. order_dual.order_top α, .. order_dual.order_bot α }
instance [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) :=
{ .. order_dual.bounded_lattice α, .. order_dual.distrib_lattice α }
end order_dual
namespace prod
variables (α β)
instance [has_top α] [has_top β] : has_top (α × β) := ⟨⟨⊤, ⊤⟩⟩
instance [has_bot α] [has_bot β] : has_bot (α × β) := ⟨⟨⊥, ⊥⟩⟩
instance [order_top α] [order_top β] : order_top (α × β) :=
{ le_top := assume a, ⟨le_top, le_top⟩,
.. prod.partial_order α β, .. prod.has_top α β }
instance [order_bot α] [order_bot β] : order_bot (α × β) :=
{ bot_le := assume a, ⟨bot_le, bot_le⟩,
.. prod.partial_order α β, .. prod.has_bot α β }
instance [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_top α β }
instance [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_top α β }
instance [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) :=
{ .. prod.semilattice_sup α β, .. prod.order_bot α β }
instance [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) :=
{ .. prod.semilattice_inf α β, .. prod.order_bot α β }
instance [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) :=
{ .. prod.lattice α β, .. prod.order_top α β, .. prod.order_bot α β }
instance [bounded_distrib_lattice α] [bounded_distrib_lattice β] :
bounded_distrib_lattice (α × β) :=
{ .. prod.bounded_lattice α β, .. prod.distrib_lattice α β }
end prod
section disjoint
section semilattice_inf_bot
variable [semilattice_inf_bot α]
/-- Two elements of a lattice are disjoint if their inf is the bottom element.
(This generalizes disjoint sets, viewed as members of the subset lattice.) -/
def disjoint (a b : α) : Prop := a ⊓ b ≤ ⊥
theorem disjoint.eq_bot {a b : α} (h : disjoint a b) : a ⊓ b = ⊥ :=
eq_bot_iff.2 h
theorem disjoint_iff {a b : α} : disjoint a b ↔ a ⊓ b = ⊥ :=
eq_bot_iff.symm
theorem disjoint.comm {a b : α} : disjoint a b ↔ disjoint b a :=
by rw [disjoint, disjoint, inf_comm]
@[symm] theorem disjoint.symm ⦃a b : α⦄ : disjoint a b → disjoint b a :=
disjoint.comm.1
@[simp] theorem disjoint_bot_left {a : α} : disjoint ⊥ a := inf_le_left
@[simp] theorem disjoint_bot_right {a : α} : disjoint a ⊥ := inf_le_right
theorem disjoint.mono {a b c d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) :
disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂)
theorem disjoint.mono_left {a b c : α} (h : a ≤ b) : disjoint b c → disjoint a c :=
disjoint.mono h (le_refl _)
theorem disjoint.mono_right {a b c : α} (h : b ≤ c) : disjoint a c → disjoint a b :=
disjoint.mono (le_refl _) h
@[simp] lemma disjoint_self {a : α} : disjoint a a ↔ a = ⊥ :=
by simp [disjoint]
lemma disjoint.ne {a b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b :=
by { intro h, rw [←h, disjoint_self] at hab, exact ha hab }
end semilattice_inf_bot
section bounded_lattice
variables [bounded_lattice α] {a : α}
@[simp] theorem disjoint_top : disjoint a ⊤ ↔ a = ⊥ := by simp [disjoint_iff]
@[simp] theorem top_disjoint : disjoint ⊤ a ↔ a = ⊥ := by simp [disjoint_iff]
end bounded_lattice
section bounded_distrib_lattice
variables [bounded_distrib_lattice α] {a b c : α}
@[simp] lemma disjoint_sup_left : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c :=
by simp only [disjoint_iff, inf_sup_right, sup_eq_bot_iff]
@[simp] lemma disjoint_sup_right : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c :=
by simp only [disjoint_iff, inf_sup_left, sup_eq_bot_iff]
lemma disjoint.sup_left (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c :=
disjoint_sup_left.2 ⟨ha, hb⟩
lemma disjoint.sup_right (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) :=
disjoint_sup_right.2 ⟨hb, hc⟩
lemma disjoint.left_le_of_le_sup_right {a b c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b :=
(λ x, le_of_inf_le_sup_le x (sup_le h le_sup_right)) ((disjoint_iff.mp hd).symm ▸ bot_le)
lemma disjoint.left_le_of_le_sup_left {a b c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b :=
@le_of_inf_le_sup_le _ _ a b c ((disjoint_iff.mp hd).symm ▸ bot_le)
((@sup_comm _ _ c b) ▸ (sup_le h le_sup_left))
end bounded_distrib_lattice
end disjoint
/-!
### `is_compl` predicate
-/
/-- Two elements `x` and `y` are complements of each other if
`x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/
structure is_compl [bounded_lattice α] (x y : α) : Prop :=
(inf_le_bot : x ⊓ y ≤ ⊥)
(top_le_sup : ⊤ ≤ x ⊔ y)
namespace is_compl
section bounded_lattice
variables [bounded_lattice α] {x y z : α}
protected lemma disjoint (h : is_compl x y) : disjoint x y := h.1
@[symm] protected lemma symm (h : is_compl x y) : is_compl y x :=
⟨by { rw inf_comm, exact h.1 }, by { rw sup_comm, exact h.2 }⟩
lemma of_eq (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y :=
⟨le_of_eq h₁, le_of_eq h₂.symm⟩
lemma inf_eq_bot (h : is_compl x y) : x ⊓ y = ⊥ := h.disjoint.eq_bot
lemma sup_eq_top (h : is_compl x y) : x ⊔ y = ⊤ := top_unique h.top_le_sup
lemma to_order_dual (h : is_compl x y) : @is_compl (order_dual α) _ x y := ⟨h.2, h.1⟩
end bounded_lattice
variables [bounded_distrib_lattice α] {x y z : α}
lemma le_left_iff (h : is_compl x y) : z ≤ x ↔ disjoint z y :=
⟨λ hz, h.disjoint.mono_left hz,
λ hz, le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top h.top_le_sup)⟩
lemma le_right_iff (h : is_compl x y) : z ≤ y ↔ disjoint z x :=
h.symm.le_left_iff
lemma left_le_iff (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y :=
h.to_order_dual.le_left_iff
lemma right_le_iff (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x :=
h.symm.left_le_iff
lemma antimono {x' y'} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') :
y' ≤ y :=
h'.right_le_iff.2 $ le_trans h.symm.top_le_sup (sup_le_sup_left hx _)
lemma right_unique (hxy : is_compl x y) (hxz : is_compl x z) :
y = z :=
le_antisymm (hxz.antimono hxy $ le_refl x) (hxy.antimono hxz $ le_refl x)
lemma left_unique (hxz : is_compl x z) (hyz : is_compl y z) :
x = y :=
hxz.symm.right_unique hyz.symm
lemma sup_inf {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊔ x') (y ⊓ y') :=
of_eq
(by rw [inf_sup_right, ← inf_assoc, h.inf_eq_bot, bot_inf_eq, bot_sup_eq, inf_left_comm,
h'.inf_eq_bot, inf_bot_eq])
(by rw [sup_inf_left, @sup_comm _ _ x, sup_assoc, h.sup_eq_top, sup_top_eq, top_inf_eq,
sup_assoc, sup_left_comm, h'.sup_eq_top, sup_top_eq])
lemma inf_sup {x' y'} (h : is_compl x y) (h' : is_compl x' y') :
is_compl (x ⊓ x') (y ⊔ y') :=
(h.symm.sup_inf h'.symm).symm
lemma inf_left_eq_bot_iff (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z :=
inf_eq_bot_iff_le_compl h.sup_eq_top h.inf_eq_bot
lemma inf_right_eq_bot_iff (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y :=
h.symm.inf_left_eq_bot_iff
lemma disjoint_left_iff (h : is_compl y z) : disjoint x y ↔ x ≤ z :=
disjoint_iff.trans h.inf_left_eq_bot_iff
lemma disjoint_right_iff (h : is_compl y z) : disjoint x z ↔ x ≤ y :=
h.symm.disjoint_left_iff
end is_compl
lemma is_compl_bot_top [bounded_lattice α] : is_compl (⊥ : α) ⊤ :=
is_compl.of_eq bot_inf_eq sup_top_eq
lemma is_compl_top_bot [bounded_lattice α] : is_compl (⊤ : α) ⊥ :=
is_compl.of_eq inf_bot_eq top_sup_eq
|
3380c828b58281678a64fa6926157df132fde595 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/group_theory/group_action/conj_act.lean | 7a5a02f5e22650248f0d3faae3f964977bae36cf | [
"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 | 7,605 | lean | /-
Copyright (c) 2021 . All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import group_theory.group_action.basic
import group_theory.subgroup.basic
import algebra.group_ring_action
/-!
# Conjugation action of a group on itself
This file defines the conjugation action of a group on itself. See also `mul_aut.conj` for
the definition of conjugation as a homomorphism into the automorphism group.
## Main definitions
A type alias `conj_act G` is introduced for a group `G`. The group `conj_act G` acts on `G`
by conjugation. The group `conj_act G` also acts on any normal subgroup of `G` by conjugation.
As a generalization, this also allows:
* `conj_act Mˣ` to act on `M`, when `M` is a `monoid`
* `conj_act G₀` to act on `G₀`, when `G₀` is a `group_with_zero`
## Implementation Notes
The scalar action in defined in this file can also be written using `mul_aut.conj g • h`. This
has the advantage of not using the type alias `conj_act`, but the downside of this approach
is that some theorems about the group actions will not apply when since this
`mul_aut.conj g • h` describes an action of `mul_aut G` on `G`, and not an action of `G`.
-/
variables (M G G₀ R K : Type*)
/-- A type alias for a group `G`. `conj_act G` acts on `G` by conjugation -/
def conj_act : Type* := G
namespace conj_act
open mul_action subgroup
variables {M G G₀ R K}
instance : Π [group G], group (conj_act G) := id
instance : Π [div_inv_monoid G], div_inv_monoid (conj_act G) := id
instance : Π [group_with_zero G], group_with_zero (conj_act G) := id
instance : Π [fintype G], fintype (conj_act G) := id
@[simp] lemma card [fintype G] : fintype.card (conj_act G) = fintype.card G := rfl
section div_inv_monoid
variable [div_inv_monoid G]
instance : inhabited (conj_act G) := ⟨1⟩
/-- Reinterpret `g : conj_act G` as an element of `G`. -/
def of_conj_act : conj_act G ≃* G := ⟨id, id, λ _, rfl, λ _, rfl, λ _ _, rfl⟩
/-- Reinterpret `g : G` as an element of `conj_act G`. -/
def to_conj_act : G ≃* conj_act G := of_conj_act.symm
/-- A recursor for `conj_act`, for use as `induction x using conj_act.rec` when `x : conj_act G`. -/
protected def rec {C : conj_act G → Sort*} (h : Π g, C (to_conj_act g)) : Π g, C g := h
@[simp] lemma of_mul_symm_eq : (@of_conj_act G _).symm = to_conj_act := rfl
@[simp] lemma to_mul_symm_eq : (@to_conj_act G _).symm = of_conj_act := rfl
@[simp] lemma to_conj_act_of_conj_act (x : conj_act G) : to_conj_act (of_conj_act x) = x := rfl
@[simp] lemma of_conj_act_to_conj_act (x : G) : of_conj_act (to_conj_act x) = x := rfl
@[simp] lemma of_conj_act_one : of_conj_act (1 : conj_act G) = 1 := rfl
@[simp] lemma to_conj_act_one : to_conj_act (1 : G) = 1 := rfl
@[simp] lemma of_conj_act_inv (x : conj_act G) : of_conj_act (x⁻¹) = (of_conj_act x)⁻¹ := rfl
@[simp] lemma to_conj_act_inv (x : G) : to_conj_act (x⁻¹) = (to_conj_act x)⁻¹ := rfl
@[simp] lemma of_conj_act_mul (x y : conj_act G) :
of_conj_act (x * y) = of_conj_act x * of_conj_act y := rfl
@[simp] lemma to_conj_act_mul (x y : G) : to_conj_act (x * y) =
to_conj_act x * to_conj_act y := rfl
instance : has_scalar (conj_act G) G :=
{ smul := λ g h, of_conj_act g * h * (of_conj_act g)⁻¹ }
lemma smul_def (g : conj_act G) (h : G) : g • h = of_conj_act g * h * (of_conj_act g)⁻¹ := rfl
@[simp] lemma «forall» (p : conj_act G → Prop) :
(∀ (x : conj_act G), p x) ↔ ∀ x : G, p (to_conj_act x) := iff.rfl
end div_inv_monoid
section units
section monoid
variables [monoid M]
instance has_units_scalar : has_scalar (conj_act Mˣ) M :=
{ smul := λ g h, of_conj_act g * h * ↑(of_conj_act g)⁻¹ }
lemma units_smul_def (g : conj_act Mˣ) (h : M) : g • h = of_conj_act g * h * ↑(of_conj_act g)⁻¹ :=
rfl
instance units_mul_distrib_mul_action : mul_distrib_mul_action (conj_act Mˣ) M :=
{ smul := (•),
one_smul := by simp [units_smul_def],
mul_smul := by simp [units_smul_def, mul_assoc, mul_inv_rev],
smul_mul := by simp [units_smul_def, mul_assoc],
smul_one := by simp [units_smul_def], }
end monoid
section semiring
variables [semiring R]
instance units_mul_semiring_action : mul_semiring_action (conj_act Rˣ) R :=
{ smul := (•),
smul_zero := by simp [units_smul_def],
smul_add := by simp [units_smul_def, mul_add, add_mul],
..conj_act.units_mul_distrib_mul_action}
end semiring
end units
section group_with_zero
variable [group_with_zero G₀]
@[simp] lemma of_conj_act_zero : of_conj_act (0 : conj_act G₀) = 0 := rfl
@[simp] lemma to_conj_act_zero : to_conj_act (0 : G₀) = 0 := rfl
instance mul_action₀ : mul_action (conj_act G₀) G₀ :=
{ smul := (•),
one_smul := by simp [smul_def],
mul_smul := by simp [smul_def, mul_assoc, mul_inv_rev] }
end group_with_zero
section division_ring
variables [division_ring K]
instance distrib_mul_action₀ : distrib_mul_action (conj_act K) K :=
{ smul := (•),
smul_zero := by simp [smul_def],
smul_add := by simp [smul_def, mul_add, add_mul],
..conj_act.mul_action₀ }
end division_ring
variables [group G]
instance : mul_distrib_mul_action (conj_act G) G :=
{ smul := (•),
smul_mul := by simp [smul_def, mul_assoc],
smul_one := by simp [smul_def],
one_smul := by simp [smul_def],
mul_smul := by simp [smul_def, mul_assoc] }
lemma smul_eq_mul_aut_conj (g : conj_act G) (h : G) : g • h = mul_aut.conj (of_conj_act g) h := rfl
/-- The set of fixed points of the conjugation action of `G` on itself is the center of `G`. -/
lemma fixed_points_eq_center : fixed_points (conj_act G) G = center G :=
begin
ext x,
simp [mem_center_iff, smul_def, mul_inv_eq_iff_eq_mul]
end
/-- As normal subgroups are closed under conjugation, they inherit the conjugation action
of the underlying group. -/
instance subgroup.conj_action {H : subgroup G} [hH : H.normal] :
has_scalar (conj_act G) H :=
⟨λ g h, ⟨g • h, hH.conj_mem h.1 h.2 (of_conj_act g)⟩⟩
lemma subgroup.coe_conj_smul {H : subgroup G} [hH : H.normal] (g : conj_act G) (h : H) :
↑(g • h) = g • (h : G) := rfl
instance subgroup.conj_mul_distrib_mul_action {H : subgroup G} [hH : H.normal] :
mul_distrib_mul_action (conj_act G) H :=
(subtype.coe_injective).mul_distrib_mul_action H.subtype subgroup.coe_conj_smul
/-- Group conjugation on a normal subgroup. Analogous to `mul_aut.conj`. -/
def _root_.mul_aut.conj_normal {H : subgroup G} [hH : H.normal] : G →* mul_aut H :=
(mul_distrib_mul_action.to_mul_aut (conj_act G) H).comp to_conj_act.to_monoid_hom
@[simp] lemma _root_.mul_aut.conj_normal_apply {H : subgroup G} [H.normal] (g : G) (h : H) :
↑(mul_aut.conj_normal g h) = g * h * g⁻¹ := rfl
@[simp] lemma _root_.mul_aut.conj_normal_symm_apply {H : subgroup G} [H.normal] (g : G) (h : H) :
↑((mul_aut.conj_normal g).symm h) = g⁻¹ * h * g :=
by { change _ * (_)⁻¹⁻¹ = _, rw inv_inv, refl }
@[simp] lemma _root_.mul_aut.conj_normal_inv_apply {H : subgroup G} [H.normal] (g : G) (h : H) :
↑((mul_aut.conj_normal g)⁻¹ h) = g⁻¹ * h * g :=
mul_aut.conj_normal_symm_apply g h
lemma _root_.mul_aut.conj_normal_coe {H : subgroup G} [H.normal] {h : H} :
mul_aut.conj_normal ↑h = mul_aut.conj h :=
mul_equiv.ext (λ x, rfl)
instance normal_of_characteristic_of_normal {H : subgroup G} [hH : H.normal]
{K : subgroup H} [h : K.characteristic] : (K.map H.subtype).normal :=
⟨λ a ha b, by
{ obtain ⟨a, ha, rfl⟩ := ha,
exact K.apply_coe_mem_map H.subtype
⟨_, ((set_like.ext_iff.mp (h.fixed (mul_aut.conj_normal b)) a).mpr ha)⟩ }⟩
end conj_act
|
95179e41803c7e539621a6b0c45fda0593155791 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/group_theory/group_action/sub_mul_action.lean | 76123b99045e3974a106dc568cfb5fab1cbcfce9 | [
"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,403 | lean | /-
Copyright (c) 2020 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.group_action_hom
import algebra.module.basic
import data.set_like
import group_theory.group_action.basic
/-!
# Sets invariant to a `mul_action`
In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with
respect to scalar multiplication.
For most uses, typically `submodule R M` is more powerful.
## Main definitions
* `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype.
* `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when
`is_scalar_tower S R M`.
* `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype.
## Tags
submodule, mul_action
-/
open function
universes u u' v
variables {S : Type u'} {R : Type u} {M : Type v}
set_option old_structure_cmd true
/-- A sub_mul_action is a set which is closed under scalar multiplication. -/
structure sub_mul_action (R : Type u) (M : Type v) [has_scalar R M] : Type v :=
(carrier : set M)
(smul_mem' : ∀ (c : R) {x : M}, x ∈ carrier → c • x ∈ carrier)
namespace sub_mul_action
variables [has_scalar R M]
instance : set_like (sub_mul_action R M) M :=
⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x ∈ p.carrier ↔ x ∈ (p : set M) :=
iff.rfl
@[ext] theorem ext {p q : sub_mul_action R M} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h
/-- Copy of a sub_mul_action with a new `carrier` equal to the old one. Useful to fix definitional
equalities.-/
protected def copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : sub_mul_action R M :=
{ carrier := s,
smul_mem' := hs.symm ▸ p.smul_mem' }
instance : has_bot (sub_mul_action R M) :=
⟨{ carrier := ∅, smul_mem' := λ c, set.not_mem_empty}⟩
instance : inhabited (sub_mul_action R M) := ⟨⊥⟩
end sub_mul_action
namespace sub_mul_action
section has_scalar
variables [has_scalar R M]
variables (p : sub_mul_action R M)
variables {r : R} {x : M}
lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h
instance : has_scalar R p :=
{ smul := λ c x, ⟨c • x.1, smul_mem _ c x.2⟩ }
variables {p}
@[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl
@[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl
variables (p)
/-- Embedding of a submodule `p` to the ambient space `M`. -/
protected def subtype : p →[R] M :=
by refine {to_fun := coe, ..}; simp [coe_smul]
@[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl
lemma subtype_eq_val : ((sub_mul_action.subtype p) : p → M) = subtype.val := rfl
end has_scalar
section mul_action
variables [monoid S] [monoid R]
variables [mul_action R M]
variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M)
variables {r : R} {x : M}
lemma smul_of_tower_mem (s : S) (h : x ∈ p) : s • x ∈ p :=
by { rw [←one_smul R x, ←smul_assoc], exact p.smul_mem _ h }
instance has_scalar' : has_scalar S p :=
{ smul := λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩ }
instance : is_scalar_tower S R p :=
{ smul_assoc := λ s r x, subtype.ext $ smul_assoc s r ↑x }
@[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s • x : p) : M) = s • ↑x := rfl
@[simp] lemma smul_mem_iff' (u : units S) : (u : S) • x ∈ p ↔ x ∈ p :=
⟨λ h, by simpa only [smul_smul, u.inv_mul, one_smul] using p.smul_of_tower_mem (↑u⁻¹ : S) h,
p.smul_of_tower_mem u⟩
/-- If the scalar product forms a `mul_action`, then the subset inherits this action -/
instance mul_action' : mul_action S p :=
{ smul := (•),
one_smul := λ x, subtype.ext $ one_smul _ x,
mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul c₁ c₂ x }
instance : mul_action R p := p.mul_action'
end mul_action
section module
variables [semiring R] [add_comm_monoid M]
variables [module R M]
variables (p : sub_mul_action R M)
lemma zero_mem (h : (p : set M).nonempty) : (0 : M) ∈ p :=
let ⟨x, hx⟩ := h in zero_smul R (x : M) ▸ p.smul_mem 0 hx
/-- If the scalar product forms a `module`, and the `sub_mul_action` is not `⊥`, then the
subset inherits the zero. -/
instance [n_empty : nonempty p] : has_zero p :=
{ zero := ⟨0, n_empty.elim $ λ x, p.zero_mem ⟨x, x.prop⟩⟩ }
end module
section add_comm_group
variables [ring R] [add_comm_group M]
variables [module R M]
variables (p p' : sub_mul_action R M)
variables {r : R} {x y : M}
lemma neg_mem (hx : x ∈ p) : -x ∈ p := by { rw ← neg_one_smul R, exact p.smul_mem _ hx }
@[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p :=
⟨λ h, by { rw ←neg_neg x, exact neg_mem _ h}, neg_mem _⟩
instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩
@[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl
end add_comm_group
end sub_mul_action
namespace sub_mul_action
variables [division_ring S] [semiring R] [mul_action R M]
variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M]
variables (p : sub_mul_action R M) {s : S} {x y : M}
theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p :=
p.smul_mem_iff' (units.mk0 s s0)
end sub_mul_action
|
89c71084a4ac11de9390cd819e5d44b27b2f291b | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/convex/specific_functions.lean | 0b0513f6b21d657e16b60b4eec3e92cd1066d07f | [
"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 | 13,232 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Sébastien Gouëzel
-/
import analysis.calculus.mean_value
import analysis.special_functions.pow_deriv
import analysis.special_functions.sqrt
/-!
# Collection of convex functions
In this file we prove that the following functions are convex:
* `strict_convex_on_exp` : The exponential function is strictly convex.
* `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : ℕ`, `λ x, x ^ n` is convex
and strictly convex when `2 ≤ n`.
* `convex_on_pow`, `strict_convex_on_pow` : For `n : ℕ`, `λ x, x ^ n` is convex on $[0, +∞)$ and
strictly convex when `2 ≤ n`.
* `convex_on_zpow`, `strict_convex_on_zpow` : For `m : ℤ`, `λ x, x ^ m` is convex on $[0, +∞)$ and
strictly convex when `m ≠ 0, 1`.
* `convex_on_rpow`, `strict_convex_on_rpow` : For `p : ℝ`, `λ x, x ^ p` is convex on $[0, +∞)$ when
`1 ≤ p` and strictly convex when `1 < p`.
* `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on
$(0, +∞)$ and $(-∞, 0)$ respectively.
## TODO
For `p : ℝ`, prove that `λ x, x ^ p` is concave when `0 ≤ p ≤ 1` and strictly concave when
`0 < p < 1`.
-/
open real set
open_locale big_operators nnreal
/-- `exp` is strictly convex on the whole real line. -/
lemma strict_convex_on_exp : strict_convex_on ℝ univ exp :=
strict_convex_on_univ_of_deriv2_pos continuous_exp (λ x, (iter_deriv_exp 2).symm ▸ exp_pos x)
/-- `exp` is convex on the whole real line. -/
lemma convex_on_exp : convex_on ℝ univ exp := strict_convex_on_exp.convex_on
/-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/
lemma even.convex_on_pow {n : ℕ} (hn : even n) : convex_on ℝ set.univ (λ x : ℝ, x^n) :=
begin
apply convex_on_univ_of_deriv2_nonneg (differentiable_pow n),
{ simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] },
{ intro x,
obtain ⟨k, hk⟩ := (hn.tsub $ even_bit0 _).exists_two_nsmul _,
rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, nsmul_eq_mul, pow_mul'],
exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) }
end
/-- `x^n`, `n : ℕ` is strictly convex on the whole real line whenever `n ≠ 0` is even. -/
lemma even.strict_convex_on_pow {n : ℕ} (hn : even n) (h : n ≠ 0) :
strict_convex_on ℝ set.univ (λ x : ℝ, x^n) :=
begin
apply strict_mono.strict_convex_on_univ_of_deriv (continuous_pow n),
rw deriv_pow',
replace h := nat.pos_of_ne_zero h,
exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl)
(nat.cast_pos.2 h),
end
/-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/
lemma convex_on_pow (n : ℕ) : convex_on ℝ (Ici 0) (λ x : ℝ, x^n) :=
begin
apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on
(differentiable_on_pow n),
{ simp only [deriv_pow'], exact (@differentiable_on_pow ℝ _ _ _).const_mul (n : ℝ) },
{ intros x hx,
rw [iter_deriv_pow, finset.prod_range_cast_nat_sub],
exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) }
end
/-- `x^n`, `n : ℕ` is strictly convex on `[0, +∞)` for all `n` greater than `2`. -/
lemma strict_convex_on_pow {n : ℕ} (hn : 2 ≤ n) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^n) :=
begin
apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _),
rw [deriv_pow', interior_Ici],
exact λ x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $
nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn),
end
/-- Specific case of Jensen's inequality for sums of powers -/
lemma real.pow_sum_div_card_le_sum_pow {α : Type*} {s : finset α} {f : α → ℝ} (n : ℕ)
(hf : ∀ a ∈ s, 0 ≤ f a) : (∑ x in s, f x) ^ (n + 1) / s.card ^ n ≤ ∑ x in s, (f x) ^ (n + 1) :=
begin
by_cases hs0 : s = ∅,
{ simp_rw [hs0, finset.sum_empty, zero_pow' _ (nat.succ_ne_zero n), zero_div] },
{ have hs : s.card ≠ 0 := hs0 ∘ finset.card_eq_zero.1,
have hs' : (s.card : ℝ) ≠ 0 := (nat.cast_ne_zero.2 hs),
have hs'' : 0 < (s.card : ℝ) := nat.cast_pos.2 (nat.pos_of_ne_zero hs),
suffices : (∑ x in s, f x / s.card) ^ (n + 1) ≤ ∑ x in s, (f x ^ (n + 1) / s.card),
by rwa [← finset.sum_div, ← finset.sum_div, div_pow, pow_succ' (s.card : ℝ),
← div_div, div_le_iff hs'', div_mul, div_self hs', div_one] at this,
have := @convex_on.map_sum_le ℝ ℝ ℝ α _ _ _ _ _ _ (set.Ici 0) (λ x, x ^ (n + 1)) s
(λ _, 1 / s.card) (coe ∘ f) (convex_on_pow (n + 1)) _ _ (λ i hi, set.mem_Ici.2 (hf i hi)),
{ simpa only [inv_mul_eq_div, one_div, algebra.id.smul_eq_mul] using this },
{ simp only [one_div, inv_nonneg, nat.cast_nonneg, implies_true_iff] },
{ simpa only [one_div, finset.sum_const, nsmul_eq_mul] using mul_inv_cancel hs' }}
end
lemma nnreal.pow_sum_div_card_le_sum_pow {α : Type*} (s : finset α) (f : α → ℝ≥0) (n : ℕ) :
(∑ x in s, f x) ^ (n + 1) / s.card ^ n ≤ ∑ x in s, (f x) ^ (n + 1) :=
by simpa only [← nnreal.coe_le_coe, nnreal.coe_sum, nonneg.coe_div, nnreal.coe_pow] using
@real.pow_sum_div_card_le_sum_pow α s (coe ∘ f) n (λ _ _, nnreal.coe_nonneg _)
lemma finset.prod_nonneg_of_card_nonpos_even
{α β : Type*} [linear_ordered_comm_ring β]
{f : α → β} [decidable_pred (λ x, f x ≤ 0)]
{s : finset α} (h0 : even (s.filter (λ x, f x ≤ 0)).card) :
0 ≤ ∏ x in s, f x :=
calc 0 ≤ (∏ x in s, ((if f x ≤ 0 then (-1:β) else 1) * f x)) :
finset.prod_nonneg (λ x _, by
{ split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx })
... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one,
mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul]
lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : even n) :
0 ≤ ∏ k in finset.range n, (m - k) :=
begin
rcases hn with ⟨n, rfl⟩,
induction n with n ihn, { simp },
rw ← two_mul at ihn,
rw [← two_mul, nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ,
finset.prod_range_succ, mul_assoc],
refine mul_nonneg ihn _, generalize : (1 + 1) * n = k,
cases le_or_lt m k with hmk hmk,
{ have : m ≤ k + 1, from hmk.trans (lt_add_one ↑k).le,
convert mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) _,
convert sub_nonpos_of_le this },
{ exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) }
end
lemma int_prod_range_pos {m : ℤ} {n : ℕ} (hn : even n) (hm : m ∉ Ico (0 : ℤ) n) :
0 < ∏ k in finset.range n, (m - k) :=
begin
refine (int_prod_range_nonneg m n hn).lt_of_ne (λ h, hm _),
rw [eq_comm, finset.prod_eq_zero_iff] at h,
obtain ⟨a, ha, h⟩ := h,
rw sub_eq_zero.1 h,
exact ⟨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 ha⟩,
end
/-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/
lemma convex_on_zpow (m : ℤ) : convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) :=
begin
have : ∀ n : ℤ, differentiable_on ℝ (λ x, x ^ n) (Ioi (0 : ℝ)),
from λ n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _),
apply convex_on_of_deriv2_nonneg (convex_Ioi 0);
try { simp only [interior_Ioi, deriv_zpow'] },
{ exact (this _).continuous_on },
{ exact this _ },
{ exact (this _).const_mul _ },
{ intros x hx,
rw iter_deriv_zpow,
refine mul_nonneg _ (zpow_nonneg (le_of_lt hx) _),
exact_mod_cast int_prod_range_nonneg _ _ (even_bit0 1) }
end
/-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` except `0` and `1`. -/
lemma strict_convex_on_zpow {m : ℤ} (hm₀ : m ≠ 0) (hm₁ : m ≠ 1) :
strict_convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) :=
begin
apply strict_convex_on_of_deriv2_pos' (convex_Ioi 0),
{ exact (continuous_on_zpow₀ m).mono (λ x hx, ne_of_gt hx) },
intros x hx,
rw iter_deriv_zpow,
refine mul_pos _ (zpow_pos_of_pos hx _),
exact_mod_cast int_prod_range_pos (even_bit0 1) (λ hm, _),
norm_cast at hm,
rw ← finset.coe_Ico at hm,
fin_cases hm; cc,
end
lemma convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on ℝ (Ici 0) (λ x : ℝ, x^p) :=
begin
have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp] },
apply convex_on_of_deriv2_nonneg (convex_Ici 0),
{ exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp)) },
{ exact (differentiable_rpow_const hp).differentiable_on },
{ rw A,
assume x hx,
replace hx : x ≠ 0, by { simp at hx, exact ne_of_gt hx },
simp [differentiable_at.differentiable_within_at, hx] },
{ assume x hx,
replace hx : 0 < x, by simpa using hx,
suffices : 0 ≤ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A],
apply mul_nonneg (le_trans zero_le_one hp),
exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) }
end
lemma strict_convex_on_rpow {p : ℝ} (hp : 1 < p) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^p) :=
begin
have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp.le] },
apply strict_convex_on_of_deriv2_pos (convex_Ici 0),
{ exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp.le)) },
rw interior_Ici,
rintro x (hx : 0 < x),
suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A],
exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)),
end
lemma strict_concave_on_log_Ioi : strict_concave_on ℝ (Ioi 0) log :=
begin
have h₁ : Ioi 0 ⊆ ({0} : set ℝ)ᶜ,
{ exact λ x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' },
refine strict_concave_on_of_deriv2_neg' (convex_Ioi 0)
(continuous_on_log.mono h₁) (λ x (hx : 0 < x), _),
rw [function.iterate_succ, function.iterate_one],
change (deriv (deriv log)) x < 0,
rw [deriv_log', deriv_inv],
exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'),
end
lemma strict_concave_on_log_Iio : strict_concave_on ℝ (Iio 0) log :=
begin
have h₁ : Iio 0 ⊆ ({0} : set ℝ)ᶜ,
{ exact λ x (hx : x < 0) (hx' : x = 0), hx.ne hx' },
refine strict_concave_on_of_deriv2_neg' (convex_Iio 0)
(continuous_on_log.mono h₁) (λ x (hx : x < 0), _),
rw [function.iterate_succ, function.iterate_one],
change (deriv (deriv log)) x < 0,
rw [deriv_log', deriv_inv],
exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne),
end
section sqrt_mul_log
lemma has_deriv_at_sqrt_mul_log {x : ℝ} (hx : x ≠ 0) :
has_deriv_at (λ x, sqrt x * log x) ((2 + log x) / (2 * sqrt x)) x :=
begin
convert (has_deriv_at_sqrt hx).mul (has_deriv_at_log hx),
rw [add_div, div_mul_right (sqrt x) two_ne_zero, ←div_eq_mul_inv, sqrt_div_self',
add_comm, div_eq_mul_one_div, mul_comm],
end
lemma deriv_sqrt_mul_log (x : ℝ) : deriv (λ x, sqrt x * log x) x = (2 + log x) / (2 * sqrt x) :=
begin
cases lt_or_le 0 x with hx hx,
{ exact (has_deriv_at_sqrt_mul_log hx.ne').deriv },
{ rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero],
refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx),
refine (has_deriv_within_at_const x _ 0).congr_of_mem (λ x hx, _) hx,
rw [sqrt_eq_zero_of_nonpos hx, zero_mul] },
end
lemma deriv_sqrt_mul_log' : deriv (λ x, sqrt x * log x) = λ x, (2 + log x) / (2 * sqrt x) :=
funext deriv_sqrt_mul_log
lemma deriv2_sqrt_mul_log (x : ℝ) :
deriv^[2] (λ x, sqrt x * log x) x = -log x / (4 * sqrt x ^ 3) :=
begin
simp only [nat.iterate, deriv_sqrt_mul_log'],
cases le_or_lt x 0 with hx hx,
{ rw [sqrt_eq_zero_of_nonpos hx, zero_pow zero_lt_three, mul_zero, div_zero],
refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx),
refine (has_deriv_within_at_const _ _ 0).congr_of_mem (λ x hx, _) hx,
rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero] },
{ have h₀ : sqrt x ≠ 0, from sqrt_ne_zero'.2 hx,
convert (((has_deriv_at_log hx.ne').const_add 2).div
((has_deriv_at_sqrt hx.ne').const_mul 2) $ mul_ne_zero two_ne_zero h₀).deriv using 1,
nth_rewrite 2 [← mul_self_sqrt hx.le],
field_simp, ring },
end
lemma strict_concave_on_sqrt_mul_log_Ioi : strict_concave_on ℝ (set.Ioi 1) (λ x, sqrt x * log x) :=
begin
apply strict_concave_on_of_deriv2_neg' (convex_Ioi 1) _ (λ x hx, _),
{ exact continuous_sqrt.continuous_on.mul
(continuous_on_log.mono (λ x hx, ne_of_gt (zero_lt_one.trans hx))) },
{ rw [deriv2_sqrt_mul_log x],
exact div_neg_of_neg_of_pos (neg_neg_of_pos (log_pos hx))
(mul_pos four_pos (pow_pos (sqrt_pos.mpr (zero_lt_one.trans hx)) 3)) },
end
end sqrt_mul_log
open_locale real
lemma strict_concave_on_sin_Icc : strict_concave_on ℝ (Icc 0 π) sin :=
begin
apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_sin (λ x hx, _),
rw interior_Icc at hx,
simp [sin_pos_of_mem_Ioo hx],
end
lemma strict_concave_on_cos_Icc : strict_concave_on ℝ (Icc (-(π/2)) (π/2)) cos :=
begin
apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_cos (λ x hx, _),
rw interior_Icc at hx,
simp [cos_pos_of_mem_Ioo hx],
end
|
89b8308ae7cc95cad55f16067236a6863094e42f | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/bench/binarytrees.lean | 9e48dcb6b002b1ff81aab1ed7e9fbfb7ba3e42e7 | [
"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,718 | lean | #lang lean4
inductive Tree
| Nil
| Node (l r : Tree) : Tree
open Tree
instance : Inhabited Tree := ⟨Nil⟩
-- This Function has an extra argument to suppress the
-- common sub-expression elimination optimization
partial def make' : UInt32 -> UInt32 -> Tree
| n, d =>
if d = 0 then Node Nil Nil
else Node (make' n (d - 1)) (make' (n + 1) (d - 1))
-- build a tree
def make (d : UInt32) := make' d d
def check : Tree → UInt32
| Nil => 0
| Node l r => 1 + check l + check r
def minN := 4
def out (s : String) (n : Nat) (t : UInt32) : IO Unit :=
IO.println (s ++ " of depth " ++ toString n ++ "\t check: " ++ toString t)
-- allocate and check lots of trees
partial def sumT : UInt32 -> UInt32 -> UInt32 -> UInt32
| d, i, t =>
if i = 0 then t
else
let a := check (make d);
sumT d (i-1) (t + a)
-- generate many trees
partial def depth : Nat -> Nat -> List (Nat × Nat × Task UInt32)
| d, m => if d ≤ m then
let n := 2 ^ (m - d + minN);
(n, d, Task.spawn (fun _ => sumT (UInt32.ofNat d) (UInt32.ofNat n) 0)) :: depth (d+2) m
else []
def main : List String → IO UInt32
| [s] => do
let n := s.toNat!;
let maxN := Nat.max (minN + 2) n;
let stretchN := maxN + 1;
-- stretch memory tree
let c := check (make $ UInt32.ofNat stretchN);
out "stretch tree" stretchN c;
-- allocate a long lived tree
let long := make $ UInt32.ofNat maxN;
-- allocate, walk, and deallocate many bottom-up binary trees
let vs := (depth minN maxN); -- `using` (parList $ evalTuple3 r0 r0 rseq)
vs.forM (fun (m, d, i) => out (toString m ++ "\t trees") d i.get);
-- confirm the the long-lived binary tree still exists
out "long lived tree" maxN (check long);
pure 0
| _ => pure 1
|
43b6aedadbb5803e921489b6dcec67f7487e03c7 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/category_theory/limits/filtered_colimit_commutes_finite_limit.lean | 15a1f3bb86d861040baad5754e7770e894abce18 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 13,425 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.limits.colimit_limit
import category_theory.limits.shapes.finite_limits
/-!
# Filtered colimits commute with finite limits.
We show that for a functor `F : J × K ⥤ Type v`, when `J` is finite and `K` is filtered,
the universal morphism `colimit_limit_to_limit_colimit F` comparing the
colimit (over `K`) of the limits (over `J`) with the limit of the colimits is an isomorphism.
(In fact, to prove that it is injective only requires that `J` has finitely many objects.)
## References
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
* [Stacks: Filtered colimits](https://stacks.math.columbia.edu/tag/002W)
-/
universes v u
open category_theory
open category_theory.category
open category_theory.limits.types
open category_theory.limits.types.filtered_colimit
namespace category_theory.limits
variables {J K : Type v} [small_category J] [small_category K]
variables (F : J × K ⥤ Type v)
open category_theory.prod
variables [is_filtered K]
section
/-!
Injectivity doesn't need that we have finitely many morphisms in `J`,
only that there are finitely many objects.
-/
variables [fintype J]
/--
This follows this proof from
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
-/
lemma colimit_limit_to_limit_colimit_injective :
function.injective (colimit_limit_to_limit_colimit F) :=
begin
classical,
-- Suppose we have two terms `x y` in the colimit (over `K`) of the limits (over `J`),
-- and that these have the same image under `colimit_limit_to_limit_colimit F`.
intros x y h,
-- These elements of the colimit have representatives somewhere:
obtain ⟨kx, x, rfl⟩ := jointly_surjective' x,
obtain ⟨ky, y, rfl⟩ := jointly_surjective' y,
dsimp at x y,
-- Since the images of `x` and `y` are equal in a limit, they are equal componentwise
-- (indexed by `j : J`),
replace h := λ j, congr_arg (limit.π ((curry.obj F) ⋙ colim) j) h,
-- and they are equations in a filtered colimit,
-- so for each `j` we have some place `k j` to the right of both `kx` and `ky`
simp [colimit_eq_iff] at h,
let k := λ j, (h j).some,
let f : Π j, kx ⟶ k j := λ j, (h j).some_spec.some,
let g : Π j, ky ⟶ k j := λ j, (h j).some_spec.some_spec.some,
-- where the images of the components of the representatives become equal:
have w : Π j,
F.map ((𝟙 j, f j) : (j, kx) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj kx) j x) =
F.map ((𝟙 j, g j) : (j, ky) ⟶ (j, k j)) (limit.π ((curry.obj (swap K J ⋙ F)).obj ky) j y) :=
λ j, (h j).some_spec.some_spec.some_spec,
-- We now use that `K` is filtered, picking some point to the right of all these
-- morphisms `f j` and `g j`.
let O : finset K := (finset.univ).image k ∪ {kx, ky},
have kxO : kx ∈ O := finset.mem_union.mpr (or.inr (by simp)),
have kyO : ky ∈ O := finset.mem_union.mpr (or.inr (by simp)),
have kjO : ∀ j, k j ∈ O := λ j, finset.mem_union.mpr (or.inl (by simp)),
let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
(finset.univ).image (λ j : J, ⟨kx, k j, kxO,
finset.mem_union.mpr (or.inl (by simp)),
f j⟩) ∪
(finset.univ).image (λ j : J, ⟨ky, k j, kyO,
finset.mem_union.mpr (or.inl (by simp)),
g j⟩),
obtain ⟨S, T, W⟩ := is_filtered.sup_exists O H,
have fH : ∀ j, (⟨kx, k j, kxO, kjO j, f j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H :=
λ j, (finset.mem_union.mpr (or.inl
begin
simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true,
finset.mem_image, heq_iff_eq],
refine ⟨j, rfl, _⟩,
simp only [heq_iff_eq],
exact ⟨rfl, rfl, rfl⟩,
end)),
have gH : ∀ j, (⟨ky, k j, kyO, kjO j, g j⟩ : (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y)) ∈ H :=
λ j, (finset.mem_union.mpr (or.inr
begin
simp only [true_and, finset.mem_univ, eq_self_iff_true, exists_prop_of_true,
finset.mem_image, heq_iff_eq],
refine ⟨j, rfl, _⟩,
simp only [heq_iff_eq],
exact ⟨rfl, rfl, rfl⟩,
end)),
-- Our goal is now an equation between equivalence classes of representatives of a colimit,
-- and so it suffices to show those representative become equal somewhere, in particular at `S`.
apply colimit_sound' (T kxO) (T kyO),
-- We can check if two elements of a limit (in `Type`) are equal by comparing them componentwise.
ext,
-- Now it's just a calculation using `W` and `w`.
simp only [functor.comp_map, limit.map_π_apply, curry.obj_map_app, swap_map],
rw ←W _ _ (fH j),
rw ←W _ _ (gH j),
simp [w],
end
end
variables [fin_category J]
/--
This follows this proof from
* Borceux, Handbook of categorical algebra 1, Theorem 2.13.4
although with different names.
-/
lemma colimit_limit_to_limit_colimit_surjective :
function.surjective (colimit_limit_to_limit_colimit F) :=
begin
classical,
-- We begin with some element `x` in the limit (over J) over the colimits (over K),
intro x,
-- This consists of some coherent family of elements in the various colimits,
-- and so our first task is to pick representatives of these elements.
have z := λ j, jointly_surjective' (limit.π (curry.obj F ⋙ limits.colim) j x),
-- `k : J ⟶ K` records where the representative of the element in the `j`-th element of `x` lives
let k : J → K := λ j, (z j).some,
-- `y j : F.obj (j, k j)` is the representative
let y : Π j, F.obj (j, k j) := λ j, (z j).some_spec.some,
-- and we record that these representatives, when mapped back into the relevant colimits,
-- are actually the components of `x`.
have e : ∀ j,
colimit.ι ((curry.obj F).obj j) (k j) (y j) =
limit.π (curry.obj F ⋙ limits.colim) j x := λ j, (z j).some_spec.some_spec,
clear_value k y, -- A little tidying up of things we no longer need.
clear z,
-- As a first step, we use that `K` is filtered to pick some point `k' : K` above all the `k j`
let k' : K := is_filtered.sup (finset.univ.image k) ∅,
-- and name the morphisms as `g j : k j ⟶ k'`.
have g : Π j, k j ⟶ k' := λ j, is_filtered.to_sup (finset.univ.image k) ∅ (by simp),
clear_value k',
-- Recalling that the components of `x`, which are indexed by `j : J`, are "coherent",
-- in other words preserved by morphisms in the `J` direction,
-- we see that for any morphism `f : j ⟶ j'` in `J`,
-- the images of `y j` and `y j'`, when mapped to `F.obj (j', k')` respectively by
-- `(f, g j)` and `(𝟙 j', g j')`, both represent the same element in the colimit.
have w : ∀ {j j' : J} (f : j ⟶ j'),
colimit.ι ((curry.obj F).obj j') k' (F.map ((𝟙 j', g j') : (j', k j') ⟶ (j', k')) (y j')) =
colimit.ι ((curry.obj F).obj j') k' (F.map ((f, g j) : (j, k j) ⟶ (j', k')) (y j)),
{ intros j j' f,
have t : (f, g j) = (((f, 𝟙 (k j)) : (j, k j) ⟶ (j', k j)) ≫ (𝟙 j', g j) : (j, k j) ⟶ (j', k')),
{ simp only [id_comp, comp_id, prod_comp], },
erw [colimit.w_apply, t, functor_to_types.map_comp_apply, colimit.w_apply, e,
←limit.w_apply f, ←e],
simp, },
-- Because `K` is filtered, we can restate this as saying that
-- for each such `f`, there is some place to the right of `k'`
-- where these images of `y j` and `y j'` become equal.
simp_rw colimit_eq_iff at w,
-- We take a moment to restate `w` more conveniently.
let kf : Π {j j'} (f : j ⟶ j'), K := λ _ _ f, (w f).some,
let gf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some,
let hf : Π {j j'} (f : j ⟶ j'), k' ⟶ kf f := λ _ _ f, (w f).some_spec.some_spec.some,
have wf : Π {j j'} (f : j ⟶ j'),
F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j') =
F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j) := λ j j' f,
begin
have q :
((curry.obj F).obj j').map (gf f) (F.map _ (y j')) =
((curry.obj F).obj j').map (hf f) (F.map _ (y j)) :=
(w f).some_spec.some_spec.some_spec,
dsimp at q,
simp_rw ←functor_to_types.map_comp_apply at q,
convert q; simp only [comp_id],
end,
clear_value kf gf hf, -- and clean up some things that are no longer needed.
clear w,
-- We're now ready to use the fact that `K` is filtered a second time,
-- picking some place to the right of all of
-- the morphisms `gf f : k' ⟶ kh f` and `hf f : k' ⟶ kf f`.
-- At this point we're relying on there being only finitely morphisms in `J`.
let O := finset.univ.bind (λ j, finset.univ.bind (λ j', finset.univ.image (@kf j j'))) ∪ {k'},
have kfO : ∀ {j j'} (f : j ⟶ j'), kf f ∈ O := λ j j' f, finset.mem_union.mpr (or.inl (
begin
rw [finset.mem_bind],
refine ⟨j, finset.mem_univ j, _⟩,
rw [finset.mem_bind],
refine ⟨j', finset.mem_univ j', _⟩,
rw [finset.mem_image],
refine ⟨f, finset.mem_univ _, _⟩,
refl,
end)),
have k'O : k' ∈ O := finset.mem_union.mpr (or.inr (finset.mem_singleton.mpr rfl)),
let H : finset (Σ' (X Y : K) (mX : X ∈ O) (mY : Y ∈ O), X ⟶ Y) :=
finset.univ.bind (λ j : J, finset.univ.bind (λ j' : J, finset.univ.bind (λ f : j ⟶ j',
{⟨k', kf f, k'O, kfO f, gf f⟩, ⟨k', kf f, k'O, kfO f, hf f⟩}))),
obtain ⟨k'', i', s'⟩ := is_filtered.sup_exists O H,
-- We then restate this slightly more conveniently, as a family of morphism `i f : kf f ⟶ k''`,
-- satisfying `gf f ≫ i f = hf f' ≫ i f'`.
let i : Π {j j'} (f : j ⟶ j'), kf f ⟶ k'' := λ j j' f, i' (kfO f),
have s : ∀ {j₁ j₂ j₃ j₄} (f : j₁ ⟶ j₂) (f' : j₃ ⟶ j₄), gf f ≫ i f = hf f' ≫ i f' :=
begin
intros,
rw [s', s'],
swap 2,
exact k'O,
swap 2,
{ rw [finset.mem_bind],
refine ⟨j₁, finset.mem_univ _, _⟩,
rw [finset.mem_bind],
refine ⟨j₂, finset.mem_univ _, _⟩,
rw [finset.mem_bind],
refine ⟨f, finset.mem_univ _, _⟩,
simp only [true_or, eq_self_iff_true, and_self, finset.mem_insert, heq_iff_eq], },
{ rw [finset.mem_bind],
refine ⟨j₃, finset.mem_univ _, _⟩,
rw [finset.mem_bind],
refine ⟨j₄, finset.mem_univ _, _⟩,
rw [finset.mem_bind],
refine ⟨f', finset.mem_univ _, _⟩,
simp only [eq_self_iff_true, or_true, and_self, finset.mem_insert, finset.mem_singleton,
heq_iff_eq], }
end,
clear_value i,
clear s' i' H kfO k'O O,
-- We're finally ready to construct the pre-image, and verify it really maps to `x`.
fsplit,
{ -- We construct the pre-image (which, recall is meant to be a point
-- in the colimit (over `K`) of the limits (over `J`)) via a representative at `k''`.
apply colimit.ι (curry.obj (swap K J ⋙ F) ⋙ limits.lim) k'' _,
dsimp,
-- This representative is meant to be an element of a limit,
-- so we need to construct a family of elements in `F.obj (j, k'')` for varying `j`,
-- then show that are coherent with respect to morphisms in the `j` direction.
ext, swap,
{ -- We construct the elements as the images of the `y j`.
exact λ j, F.map (⟨𝟙 j, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)⟩ : (j, k j) ⟶ (j, k'')) (y j), },
{ -- After which it's just a calculation, using `s` and `wf`, to see they are coherent.
dsimp,
simp only [←functor_to_types.map_comp_apply, prod_comp, id_comp, comp_id],
calc F.map ((f, g j ≫ gf (𝟙 j) ≫ i (𝟙 j)) : (j, k j) ⟶ (j', k'')) (y j)
= F.map ((f, g j ≫ hf f ≫ i f) : (j, k j) ⟶ (j', k'')) (y j)
: by rw s (𝟙 j) f
... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k''))
(F.map ((f, g j ≫ hf f) : (j, k j) ⟶ (j', kf f)) (y j))
: by rw [←functor_to_types.map_comp_apply, prod_comp, comp_id, assoc]
... = F.map ((𝟙 j', i f) : (j', kf f) ⟶ (j', k''))
(F.map ((𝟙 j', g j' ≫ gf f) : (j', k j') ⟶ (j', kf f)) (y j'))
: by rw ←wf f
... = F.map ((𝟙 j', g j' ≫ gf f ≫ i f) : (j', k j') ⟶ (j', k'')) (y j')
: by rw [←functor_to_types.map_comp_apply, prod_comp, id_comp, assoc]
... = F.map ((𝟙 j', g j' ≫ gf (𝟙 j') ≫ i (𝟙 j')) : (j', k j') ⟶ (j', k'')) (y j')
: by rw [s f (𝟙 j'), ←s (𝟙 j') (𝟙 j')], }, },
-- Finally we check that this maps to `x`.
{ -- We can do this componentwise:
apply limit_ext,
intro j,
-- and as each component is an equation in a colimit, we can verify it by
-- pointing out the morphism which carries one representative to the other:
simp only [←e, colimit_eq_iff, curry.obj_obj_map, limit.π_mk,
bifunctor.map_id_comp, id.def, types_comp_apply,
limits.ι_colimit_limit_to_limit_colimit_π_apply],
refine ⟨k'', 𝟙 k'', g j ≫ gf (𝟙 j) ≫ i (𝟙 j), _⟩,
simp only [bifunctor.map_id_comp, types_comp_apply, bifunctor.map_id, types_id_apply], },
end
noncomputable
instance colimit_limit_to_limit_colimit_is_iso :
is_iso (colimit_limit_to_limit_colimit F) :=
(is_iso_equiv_bijective _).symm
⟨colimit_limit_to_limit_colimit_injective F, colimit_limit_to_limit_colimit_surjective F⟩
end category_theory.limits
|
79c8cf18d4747ba5dc08be118cb12cbdb136b330 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/linear_algebra/dimension.lean | e262a9055ccba43e1993120c08ccd3f47281ddee | [
"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 | 53,543 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison
-/
import linear_algebra.dfinsupp
import linear_algebra.invariant_basis_number
import linear_algebra.isomorphisms
import linear_algebra.std_basis
import set_theory.cardinal.cofinality
/-!
# Dimension of modules and vector spaces
## Main definitions
* The rank of a module is defined as `module.rank : cardinal`.
This is defined as the supremum of the cardinalities of linearly independent subsets.
* The rank of a linear map is defined as the rank of its range.
## Main statements
* `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension
at most that of the target.
* `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension
at most that of that source.
* `basis_fintype_of_finite_spans`:
the existence of a finite spanning set implies that any basis is finite.
* `infinite_basis_le_maximal_linear_independent`:
if `b` is an infinite basis for a module `M`,
and `s` is a maximal linearly independent set,
then the cardinality of `b` is bounded by the cardinality of `s`.
For modules over rings satisfying the rank condition
* `basis.le_span`:
the cardinality of a basis is bounded by the cardinality of any spanning set
For modules over rings satisfying the strong rank condition
* `linear_independent_le_span`:
For any linearly independent family `v : ι → M`
and any finite spanning set `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
* `linear_independent_le_basis`:
If `b` is a basis for a module `M`,
and `s` is a linearly independent set,
then the cardinality of `s` is bounded by the cardinality of `b`.
For modules over rings with invariant basis number
(including all commutative rings and all noetherian rings)
* `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same
cardinality.
For vector spaces (i.e. modules over a field), we have
* `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then
`module.rank (V/V₁) + module.rank V₁ = module.rank V`.
* `dim_range_add_dim_ker`: the rank-nullity theorem.
## Implementation notes
There is a naming discrepancy: most of the theorem names refer to `dim`,
even though the definition is of `module.rank`.
This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces.
Many theorems in this file are not universe-generic when they relate dimensions
in different universes. They should be as general as they can be without
inserting `lift`s. The types `V`, `V'`, ... all live in different universes,
and `V₁`, `V₂`, ... all live in the same universe.
-/
noncomputable theory
universes u v v' v'' u₁' w w'
variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''}
variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*}
open_locale classical big_operators cardinal
open basis submodule function set
section module
section
variables [semiring K] [add_comm_monoid V] [module K V]
include K
variables (K V)
/-- The rank of a module, defined as a term of type `cardinal`.
We define this as the supremum of the cardinalities of linearly independent subsets.
For a free module over any ring satisfying the strong rank condition
(e.g. left-noetherian rings, commutative rings, and in particular division rings and fields),
this is the same as the dimension of the space (i.e. the cardinality of any basis).
In particular this agrees with the usual notion of the dimension of a vector space.
The definition is marked as protected to avoid conflicts with `_root_.rank`,
the rank of a linear map.
-/
protected def module.rank : cardinal :=
⨆ ι : {s : set V // linear_independent K (coe : s → V)}, #ι.1
end
section
variables {R : Type u} [ring R]
variables {M : Type v} [add_comm_group M] [module R M]
variables {M' : Type v'} [add_comm_group M'] [module R M']
variables {M₁ : Type v} [add_comm_group M₁] [module R M₁]
theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) :
cardinal.lift.{v'} (module.rank R M) ≤ cardinal.lift.{v} (module.rank R M') :=
begin
dsimp [module.rank],
rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _),
cardinal.lift_supr (cardinal.bdd_above_range.{v v} _)],
apply csupr_mono' (cardinal.bdd_above_range.{v' v} _),
rintro ⟨s, li⟩,
refine ⟨⟨f '' s, _⟩, cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩⟩,
exact (li.map' _ $ linear_map.ker_eq_bot.mpr i).image,
end
theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) :
module.rank R M ≤ module.rank R M₁ :=
cardinal.lift_le.1 (f.lift_dim_le_of_injective i)
theorem dim_le {n : ℕ}
(H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) :
module.rank R M ≤ n :=
begin
apply csupr_le',
rintro ⟨s, li⟩,
exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li,
end
lemma lift_dim_range_le (f : M →ₗ[R] M') :
cardinal.lift.{v} (module.rank R f.range) ≤ cardinal.lift.{v'} (module.rank R M) :=
begin
dsimp [module.rank],
rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _)],
apply csupr_le',
rintro ⟨s, li⟩,
apply le_trans,
swap 2,
apply cardinal.lift_le.mpr,
refine (le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range_splitting f '' s, _⟩),
{ apply linear_independent.of_comp f.range_restrict,
convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, },
{ exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, },
end
lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M :=
by simpa using lift_dim_range_le f
lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) :
cardinal.lift.{v} (module.rank R (p.map f)) ≤ cardinal.lift.{v'} (module.rank R p) :=
begin
have h := lift_dim_range_le (f.comp (submodule.subtype p)),
rwa [linear_map.range_comp, range_subtype] at h,
end
lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p :=
by simpa using lift_dim_map_le f p
lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) :
module.rank R s ≤ module.rank R t :=
(of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq,
subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq
/-- Two linearly equivalent vector spaces have the same dimension, a version with different
universes. -/
theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') :
cardinal.lift.{v'} (module.rank R M) = cardinal.lift.{v} (module.rank R M') :=
begin
apply le_antisymm,
{ exact f.to_linear_map.lift_dim_le_of_injective f.injective, },
{ exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, },
end
/-- Two linearly equivalent vector spaces have the same dimension. -/
theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) :
module.rank R M = module.rank R M₁ :=
cardinal.lift_inj.1 f.lift_dim_eq
lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) :
module.rank R M = module.rank R f.range :=
(linear_equiv.of_injective f h).dim_eq
/-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/
lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) :
module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p :=
(f.submodule_map p).dim_eq.symm
variables (R M)
@[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M :=
begin
have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl,
rw this.dim_eq,
end
variables {R M}
lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) :
module.rank R f.range = module.rank R M' :=
by rw [linear_map.range_eq_top.2 h, dim_top]
lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M :=
begin
rw ←dim_top R M,
exact dim_le_of_submodule _ _ le_top,
end
lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) :
module.rank R M₁ ≤ module.rank R M :=
begin
rw ←dim_range_of_surjective f h,
apply dim_range_le,
end
theorem dim_quotient_le (p : submodule R M) :
module.rank R (M ⧸ p) ≤ module.rank R M :=
(mkq p).dim_le_of_surjective (surjective_quot_mk _)
variables [nontrivial R]
lemma {m} cardinal_lift_le_dim_of_linear_independent
{ι : Type w} {v : ι → M} (hv : linear_independent R v) :
cardinal.lift.{max v m} (#ι) ≤ cardinal.lift.{max w m} (module.rank R M) :=
begin
apply le_trans,
{ exact cardinal.lift_mk_le.mpr
⟨(equiv.of_injective _ hv.injective).to_embedding⟩, },
{ simp only [cardinal.lift_le],
apply le_trans,
swap,
exact le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range v, hv.coe_range⟩,
exact le_rfl, },
end
lemma cardinal_lift_le_dim_of_linear_independent'
{ι : Type w} {v : ι → M} (hv : linear_independent R v) :
cardinal.lift.{v} (#ι) ≤ cardinal.lift.{w} (module.rank R M) :=
cardinal_lift_le_dim_of_linear_independent.{u v w 0} hv
lemma cardinal_le_dim_of_linear_independent
{ι : Type v} {v : ι → M} (hv : linear_independent R v) :
#ι ≤ module.rank R M :=
by simpa using cardinal_lift_le_dim_of_linear_independent hv
lemma cardinal_le_dim_of_linear_independent'
{s : set M} (hs : linear_independent R (λ x, x : s → M)) :
#s ≤ module.rank R M :=
cardinal_le_dim_of_linear_independent hs
variables (R M)
@[simp] lemma dim_punit : module.rank R punit = 0 :=
begin
apply le_bot_iff.mp,
apply csupr_le',
rintro ⟨s, li⟩,
apply le_bot_iff.mpr,
apply cardinal.mk_emptyc_iff.mpr,
simp only [subtype.coe_mk],
by_contradiction h,
have ne : s.nonempty := ne_empty_iff_nonempty.mp h,
simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li,
end
@[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 :=
begin
have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit,
rw [this.dim_eq, dim_punit],
end
variables {R M}
/-- A linearly-independent family of vectors in a module over a non-trivial ring must be finite if
the module is Noetherian. -/
lemma linear_independent.finite_of_is_noetherian [is_noetherian R M]
{v : ι → M} (hv : linear_independent R v) : finite ι :=
begin
have hwf := is_noetherian_iff_well_founded.mp (by apply_instance : is_noetherian R M),
refine complete_lattice.well_founded.finite_of_independent hwf
hv.independent_span_singleton (λ i contra, _),
apply hv.ne_zero i,
have : v i ∈ R ∙ v i := submodule.mem_span_singleton_self (v i),
rwa [contra, submodule.mem_bot] at this,
end
lemma linear_independent.set_finite_of_is_noetherian [is_noetherian R M]
{s : set M} (hi : linear_independent R (coe : s → M)) : s.finite :=
@set.to_finite _ _ hi.finite_of_is_noetherian
/--
Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite.
-/
-- One might hope that a finite spanning set implies that any linearly independent set is finite.
-- While this is true over a division ring
-- (simply because any linearly independent set can be extended to a basis),
-- I'm not certain what more general statements are possible.
def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤)
{ι : Type w} (b : basis ι R M) : fintype ι :=
begin
-- We'll work by contradiction, assuming `ι` is infinite.
apply fintype_of_not_infinite _,
introI i,
-- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`.
-- This is a finite set since `w` is finite.
let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support),
let bS : set M := b '' S,
have h : ∀ x ∈ w, x ∈ span R bS,
{ intros x m,
rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map],
use b.repr x,
simp only [and_true, eq_self_iff_true, finsupp.mem_supported],
change (b.repr x).support ≤ S,
convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)),
refl, },
-- Thus this finite subset of the basis elements spans the entire module.
have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)),
-- Now there is some `x : ι` not in `S`, since `ι` is infinite.
obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S,
-- However it must be in the span of the finite subset,
have k' : b x ∈ span R bS, { rw k, exact mem_top, },
-- giving the desire contradiction.
refine b.linear_independent.not_mem_span_image _ k',
exact nm,
end
/--
Over any ring `R`, if `b` is a basis for a module `M`,
and `s` is a maximal linearly independent set,
then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`.
-/
-- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973]
lemma union_support_maximal_linear_independent_eq_range_basis
{ι : Type w} (b : basis ι R M)
{κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
(⋃ k, ((b.repr (v k)).support : set ι)) = univ :=
begin
-- If that's not the case,
by_contradiction h,
simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not,
finsupp.mem_support_iff, finset.mem_coe] at h,
-- We have some basis element `b b'` which is not in the support of any of the `v i`.
obtain ⟨b', w⟩ := h,
-- Using this, we'll construct a linearly independent family strictly larger than `v`,
-- by also using this `b b'`.
let v' : option κ → M := λ o, o.elim (b b') v,
have r : range v ⊆ range v',
{ rintro - ⟨k, rfl⟩,
use some k,
refl, },
have r' : b b' ∉ range v,
{ rintro ⟨k, p⟩,
simpa [w] using congr_arg (λ m, (b.repr m) b') p, },
have r'' : range v ≠ range v',
{ intro e,
have p : b b' ∈ range v', { use none, refl, },
rw ←e at p,
exact r' p, },
have inj' : injective v',
{ rintros (_|k) (_|k) z,
{ refl, },
{ exfalso, exact r' ⟨k, z.symm⟩, },
{ exfalso, exact r' ⟨k, z⟩, },
{ congr, exact i.injective z, }, },
-- The key step in the proof is checking that this strictly larger family is linearly independent.
have i' : linear_independent R (coe : range v' → M),
{ rw [linear_independent_subtype_range inj', linear_independent_iff],
intros l z,
rw [finsupp.total_option] at z,
simp only [v', option.elim] at z,
change _ + finsupp.total κ M R v l.some = 0 at z,
-- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial.
-- We'll first show the coefficient of `b b'` is zero,
-- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term.
have l₀ : l none = 0,
{ rw ←eq_neg_iff_add_eq_zero at z,
replace z := eq_neg_of_eq_neg z,
apply_fun (λ x, b.repr x b') at z,
simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply,
finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z,
erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z,
simpa [finsupp.total_apply, w] using z, },
-- Then all the other coefficients are zero, because `v` is linear independent.
have l₁ : l.some = 0,
{ rw [l₀, zero_smul, zero_add] at z,
exact linear_independent_iff.mp i _ z, },
-- Finally we put those facts together to show the linear combination is trivial.
ext (_|a),
{ simp only [l₀, finsupp.coe_zero, pi.zero_apply], },
{ erw finsupp.congr_fun l₁ a,
simp only [finsupp.coe_zero, pi.zero_apply], }, },
dsimp [linear_independent.maximal] at m,
specialize m (range v') i' r,
exact r'' m,
end
/--
Over any ring `R`, if `b` is an infinite basis for a module `M`,
and `s` is a maximal linearly independent set,
then the cardinality of `b` is bounded by the cardinality of `s`.
-/
lemma infinite_basis_le_maximal_linear_independent'
{ι : Type w} (b : basis ι R M) [infinite ι]
{κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
cardinal.lift.{w'} (#ι) ≤ cardinal.lift.{w} (#κ) :=
begin
let Φ := λ k : κ, (b.repr (v k)).support,
have w₁ : #ι ≤ #(set.range Φ),
{ apply cardinal.le_range_of_union_finset_eq_top,
exact union_support_maximal_linear_independent_eq_range_basis b v i m, },
have w₂ :
cardinal.lift.{w'} (#(set.range Φ)) ≤ cardinal.lift.{w} (#κ) :=
cardinal.mk_range_le_lift,
exact (cardinal.lift_le.mpr w₁).trans w₂,
end
/--
Over any ring `R`, if `b` is an infinite basis for a module `M`,
and `s` is a maximal linearly independent set,
then the cardinality of `b` is bounded by the cardinality of `s`.
-/
-- (See `infinite_basis_le_maximal_linear_independent'` for the more general version
-- where the index types can live in different universes.)
lemma infinite_basis_le_maximal_linear_independent
{ι : Type w} (b : basis ι R M) [infinite ι]
{κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
#ι ≤ #κ :=
cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m)
lemma complete_lattice.independent.subtype_ne_bot_le_rank [no_zero_smul_divisors R M]
{V : ι → submodule R M} (hV : complete_lattice.independent V) :
cardinal.lift.{v} (#{i : ι // V i ≠ ⊥}) ≤ cardinal.lift.{w} (module.rank R M) :=
begin
set I := {i : ι // V i ≠ ⊥},
have hI : ∀ i : I, ∃ v ∈ V i, v ≠ (0:M),
{ intros i,
rw ← submodule.ne_bot_iff,
exact i.prop },
choose v hvV hv using hI,
have : linear_independent R v,
{ exact (hV.comp subtype.coe_injective).linear_independent _ hvV hv },
exact cardinal_lift_le_dim_of_linear_independent' this
end
end
section rank_zero
variables {R : Type u} {M : Type v}
variables [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M]
lemma dim_zero_iff_forall_zero : module.rank R M = 0 ↔ ∀ x : M, x = 0 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ contrapose! h,
obtain ⟨x, hx⟩ := h,
suffices : 1 ≤ module.rank R M,
{ intro h, exact lt_irrefl _ (lt_of_lt_of_le cardinal.zero_lt_one (h ▸ this)) },
suffices : linear_independent R (λ (y : ({x} : set M)), ↑y),
{ simpa using (cardinal_le_dim_of_linear_independent this), },
exact linear_independent_singleton hx },
{ have : (⊤ : submodule R M) = ⊥,
{ ext x, simp [h x] },
rw [←dim_top, this, dim_bot] }
end
lemma dim_zero_iff : module.rank R M = 0 ↔ subsingleton M :=
dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm
lemma dim_pos_iff_exists_ne_zero : 0 < module.rank R M ↔ ∃ x : M, x ≠ 0 :=
begin
rw ←not_iff_not,
simpa using dim_zero_iff_forall_zero
end
lemma dim_pos_iff_nontrivial : 0 < module.rank R M ↔ nontrivial M :=
dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm
lemma dim_pos [h : nontrivial M] : 0 < module.rank R M :=
dim_pos_iff_nontrivial.2 h
end rank_zero
section invariant_basis_number
variables {R : Type u} [ring R] [invariant_basis_number R]
variables {M : Type v} [add_comm_group M] [module R M]
/-- The dimension theorem: if `v` and `v'` are two bases, their index types
have the same cardinalities. -/
theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) :
cardinal.lift.{w'} (#ι) = cardinal.lift.{w} (#ι') :=
begin
haveI := nontrivial_of_invariant_basis_number R,
casesI fintype_or_infinite ι,
{ -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`.
haveI : fintype (range v) := set.fintype_range v,
haveI := basis_fintype_of_finite_spans _ v.span_eq v',
-- We clean up a little:
rw [cardinal.mk_fintype, cardinal.mk_fintype],
simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj],
-- Now we can use invariant basis number to show they have the same cardinality.
apply card_eq_of_lequiv R,
exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm) ≪≫ₗ
v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_fintype R R ι'), },
{ -- `v` is an infinite basis,
-- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big,
-- and then applying `infinite_basis_le_maximal_linear_independent` again
-- we see they have the same cardinality.
have w₁ :=
infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal,
rcases cardinal.lift_mk_le'.mp w₁ with ⟨f⟩,
haveI : infinite ι' := infinite.of_injective f f.2,
have w₂ :=
infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal,
exact le_antisymm w₁ w₂, }
end
/-- Given two bases indexed by `ι` and `ι'` of an `R`-module, where `R` satisfies the invariant
basis number property, an equiv `ι ≃ ι' `. -/
def basis.index_equiv (v : basis ι R M) (v' : basis ι' R M) : ι ≃ ι' :=
nonempty.some (cardinal.lift_mk_eq.1 (cardinal.lift_umax_eq.2 (mk_eq_mk_of_basis v v')))
theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) :
#ι = #ι' :=
cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v'
end invariant_basis_number
section rank_condition
variables {R : Type u} [ring R] [rank_condition R]
variables {M : Type v} [add_comm_group M] [module R M]
/--
An auxiliary lemma for `basis.le_span`.
If `R` satisfies the rank condition,
then for any finite basis `b : basis ι R M`,
and any finite spanning set `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M)
{w : set M} [fintype w] (s : span R w = ⊤) :
fintype.card ι ≤ fintype.card w :=
begin
-- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`,
-- by expressing a linear combination in `w` as a linear combination in `ι`.
fapply card_le_of_surjective' R,
{ exact b.repr.to_linear_map.comp (finsupp.total w M R coe), },
{ apply surjective.comp,
apply linear_equiv.surjective,
rw [←linear_map.range_eq_top, finsupp.range_total],
simpa using s, },
end
/--
Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite,
but still assumes we have a finite spanning set.
-/
lemma basis_le_span' {ι : Type*} (b : basis ι R M)
{w : set M} [fintype w] (s : span R w = ⊤) :
#ι ≤ fintype.card w :=
begin
haveI := nontrivial_of_invariant_basis_number R,
haveI := basis_fintype_of_finite_spans w s b,
rw cardinal.mk_fintype ι,
simp only [cardinal.nat_cast_le],
exact basis.le_span'' b s,
end
/--
If `R` satisfies the rank condition,
then the cardinality of any basis is bounded by the cardinality of any spanning set.
-/
-- Note that if `R` satisfies the strong rank condition,
-- this also follows from `linear_independent_le_span` below.
theorem basis.le_span {J : set M} (v : basis ι R M)
(hJ : span R J = ⊤) : #(range v) ≤ #J :=
begin
haveI := nontrivial_of_invariant_basis_number R,
casesI fintype_or_infinite J,
{ rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.mk_fintype J],
convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ),
simp, },
{ have := cardinal.mk_range_eq_of_injective v.injective,
let S : J → set ι := λ j, ↑(v.repr j).support,
let S' : J → set M := λ j, v '' S j,
have hs : range v ⊆ ⋃ j, S' j,
{ intros b hb,
rcases mem_range.1 hb with ⟨i, hi⟩,
have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) :=
span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩),
rw hJ at this,
replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial,
rw [v.repr_self, finsupp.mem_supported,
finsupp.support_single_ne_zero _ one_ne_zero] at this,
{ subst b,
rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩,
exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ },
{ apply_instance } },
refine le_of_not_lt (λ IJ, _),
suffices : #(⋃ j, S' j) < #(range v),
{ exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ },
refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk
(cardinal.sum_le_sum _ (λ _, ℵ₀) _)) _,
{ exact λ j, (cardinal.lt_aleph_0_of_finite _).le },
{ simpa } },
end
end rank_condition
section strong_rank_condition
variables {R : Type u} [ring R] [strong_rank_condition R]
variables {M : Type v} [add_comm_group M] [module R M]
open submodule
-- An auxiliary lemma for `linear_independent_le_span'`,
-- with the additional assumption that the linearly independent family is finite.
lemma linear_independent_le_span_aux'
{ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v)
(w : set M) [fintype w] (s : range v ≤ span R w) :
fintype.card ι ≤ fintype.card w :=
begin
-- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`,
-- by thinking of `f : ι → R` as a linear combination of the finite family `v`,
-- and expressing that (using the axiom of choice) as a linear combination over `w`.
-- We can do this linearly by constructing the map on a basis.
fapply card_le_of_injective' R,
{ apply finsupp.total,
exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, },
{ intros f g h,
apply_fun finsupp.total w M R coe at h,
simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h,
rw [←sub_eq_zero, ←linear_map.map_sub] at h,
exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), },
end
/--
If `R` satisfies the strong rank condition,
then any linearly independent family `v : ι → M`
contained in the span of some finite `w : set M`,
is itself finite.
-/
def linear_independent_fintype_of_le_span_fintype
{ι : Type*} (v : ι → M) (i : linear_independent R v)
(w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι :=
fintype_of_finset_card_le (fintype.card w) (λ t, begin
let v' := λ x : (t : set ι), v x,
have i' : linear_independent R v' := i.comp _ subtype.val_injective,
have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s,
simpa using linear_independent_le_span_aux' v' i' w s',
end)
/--
If `R` satisfies the strong rank condition,
then for any linearly independent family `v : ι → M`
contained in the span of some finite `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v)
(w : set M) [fintype w] (s : range v ≤ span R w) :
#ι ≤ fintype.card w :=
begin
haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s,
rw cardinal.mk_fintype,
simp only [cardinal.nat_cast_le],
exact linear_independent_le_span_aux' v i w s,
end
/--
If `R` satisfies the strong rank condition,
then for any linearly independent family `v : ι → M`
and any finite spanning set `w : set M`,
the cardinality of `ι` is bounded by the cardinality of `w`.
-/
lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v)
(w : set M) [fintype w] (s : span R w = ⊤) :
#ι ≤ fintype.card w :=
begin
apply linear_independent_le_span' v i w,
rw s,
exact le_top,
end
/--
An auxiliary lemma for `linear_independent_le_basis`:
we handle the case where the basis `b` is infinite.
-/
lemma linear_independent_le_infinite_basis
{ι : Type*} (b : basis ι R M) [infinite ι]
{κ : Type*} (v : κ → M) (i : linear_independent R v) :
#κ ≤ #ι :=
begin
by_contradiction,
rw [not_le, ← cardinal.mk_finset_of_infinite ι] at h,
let Φ := λ k : κ, (b.repr (v k)).support,
obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by apply_instance),
let v' := λ k : Φ ⁻¹' {s}, v k,
have i' : linear_independent R v' := i.comp _ subtype.val_injective,
have w' : fintype (Φ ⁻¹' {s}),
{ apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b),
rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩,
simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image],
apply basis.mem_span_repr_support, },
exactI w.false,
end
/--
Over any ring `R` satisfying the strong rank condition,
if `b` is a basis for a module `M`,
and `s` is a linearly independent set,
then the cardinality of `s` is bounded by the cardinality of `b`.
-/
lemma linear_independent_le_basis
{ι : Type*} (b : basis ι R M)
{κ : Type*} (v : κ → M) (i : linear_independent R v) :
#κ ≤ #ι :=
begin
-- We split into cases depending on whether `ι` is infinite.
cases fintype_or_infinite ι; resetI,
{ -- When `ι` is finite, we have `linear_independent_le_span`,
rw cardinal.mk_fintype ι,
haveI : nontrivial R := nontrivial_of_invariant_basis_number R,
rw fintype.card_congr (equiv.of_injective b b.injective),
exact linear_independent_le_span v i (range b) b.span_eq, },
{ -- and otherwise we have `linear_indepedent_le_infinite_basis`.
exact linear_independent_le_infinite_basis b v i, },
end
/-- In an `n`-dimensional space, the rank is at most `m`. -/
lemma basis.card_le_card_of_linear_independent_aux
{R : Type*} [ring R] [strong_rank_condition R]
(n : ℕ) {m : ℕ} (v : fin m → fin n → R) :
linear_independent R v → m ≤ n :=
λ h, by simpa using (linear_independent_le_basis (pi.basis_fun R (fin n)) v h)
/--
Over any ring `R` satisfying the strong rank condition,
if `b` is an infinite basis for a module `M`,
then every maximal linearly independent set has the same cardinality as `b`.
This proof (along with some of the lemmas above) comes from
[Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973]
-/
-- When the basis is not infinite this need not be true!
lemma maximal_linear_independent_eq_infinite_basis
{ι : Type*} (b : basis ι R M) [infinite ι]
{κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) :
#κ = #ι :=
begin
apply le_antisymm,
{ exact linear_independent_le_basis b v i, },
{ haveI : nontrivial R := nontrivial_of_invariant_basis_number R,
exact infinite_basis_le_maximal_linear_independent b v i m, }
end
theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) :
#ι = module.rank R M :=
begin
haveI := nontrivial_of_invariant_basis_number R,
apply le_antisymm,
{ transitivity,
swap,
apply le_csupr (cardinal.bdd_above_range.{v v} _),
exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩,
exact (cardinal.mk_range_eq v v.injective).ge, },
{ apply csupr_le',
rintro ⟨s, li⟩,
apply linear_independent_le_basis v _ li, },
end
-- By this stage we want to have a complete API for `module.rank`,
-- so we set it `irreducible` here, to keep ourselves honest.
attribute [irreducible] module.rank
theorem basis.mk_range_eq_dim (v : basis ι R M) :
#(range v) = module.rank R M :=
v.reindex_range.mk_eq_dim''
/-- 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 ι] (h : basis ι R M) :
module.rank R M = fintype.card ι :=
by {haveI := nontrivial_of_invariant_basis_number R,
rw [←h.mk_range_eq_dim, cardinal.mk_fintype, set.card_range_of_injective h.injective] }
lemma basis.card_le_card_of_linear_independent {ι : Type*} [fintype ι]
(b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) :
fintype.card ι' ≤ fintype.card ι :=
begin
letI := nontrivial_of_invariant_basis_number R,
simpa [dim_eq_card_basis b, cardinal.mk_fintype] using
cardinal_lift_le_dim_of_linear_independent' hv
end
lemma basis.card_le_card_of_submodule (N : submodule R M) [fintype ι] (b : basis ι R M)
[fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι :=
b.card_le_card_of_linear_independent (b'.linear_independent.map' N.subtype N.ker_subtype)
lemma basis.card_le_card_of_le
{N O : submodule R M} (hNO : N ≤ O) [fintype ι] (b : basis ι R O) [fintype ι']
(b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι :=
b.card_le_card_of_linear_independent
(b'.linear_independent.map' (submodule.of_le hNO) (N.ker_of_le O _))
theorem basis.mk_eq_dim (v : basis ι R M) :
cardinal.lift.{v} (#ι) = cardinal.lift.{w} (module.rank R M) :=
begin
haveI := nontrivial_of_invariant_basis_number R,
rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective]
end
theorem {m} basis.mk_eq_dim' (v : basis ι R M) :
cardinal.lift.{max v m} (#ι) = cardinal.lift.{max w m} (module.rank R M) :=
by simpa using v.mk_eq_dim
/-- If a module has a finite dimension, all bases are indexed by a finite type. -/
lemma basis.nonempty_fintype_index_of_dim_lt_aleph_0 {ι : Type*}
(b : basis ι R M) (h : module.rank R M < ℵ₀) :
nonempty (fintype ι) :=
by rwa [← cardinal.lift_lt, ← b.mk_eq_dim,
-- ensure `aleph_0` has the correct universe
cardinal.lift_aleph_0, ← cardinal.lift_aleph_0.{u_1 v},
cardinal.lift_lt, cardinal.lt_aleph_0_iff_fintype] at h
/-- If a module has a finite dimension, all bases are indexed by a finite type. -/
noncomputable def basis.fintype_index_of_dim_lt_aleph_0 {ι : Type*}
(b : basis ι R M) (h : module.rank R M < ℵ₀) :
fintype ι :=
classical.choice (b.nonempty_fintype_index_of_dim_lt_aleph_0 h)
/-- If a module has a finite dimension, all bases are indexed by a finite set. -/
lemma basis.finite_index_of_dim_lt_aleph_0 {ι : Type*} {s : set ι}
(b : basis s R M) (h : module.rank R M < ℵ₀) :
s.finite :=
finite_def.2 (b.nonempty_fintype_index_of_dim_lt_aleph_0 h)
lemma dim_span {v : ι → M} (hv : linear_independent R v) :
module.rank R ↥(span R (range v)) = #(range v) :=
begin
haveI := nontrivial_of_invariant_basis_number R,
rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim,
cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)]
end
lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) :
module.rank R ↥(span R s) = #s :=
by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs }
/-- If `N` is a submodule in a free, finitely generated module,
do induction on adjoining a linear independent element to a submodule. -/
def submodule.induction_on_rank [is_domain R] [fintype ι] (b : basis ι R M)
(P : submodule R M → Sort*) (ih : ∀ (N : submodule R M),
(∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') →
P N)
(N : submodule R M) : P N :=
submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli,
by simpa using b.card_le_card_of_linear_independent hli)
/-- If `S` a finite-dimensional ring extension of `R` which is free as an `R`-module,
then the rank of an ideal `I` of `S` over `R` is the same as the rank of `S`.
-/
lemma ideal.rank_eq {R S : Type*} [comm_ring R] [strong_rank_condition R] [ring S] [is_domain S]
[algebra R S] {n m : Type*} [fintype n] [fintype m]
(b : basis n R S) {I : ideal S} (hI : I ≠ ⊥) (c : basis m R I) :
fintype.card m = fintype.card n :=
begin
obtain ⟨a, ha⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr hI),
have : linear_independent R (λ i, b i • a),
{ have hb := b.linear_independent,
rw fintype.linear_independent_iff at ⊢ hb,
intros g hg,
apply hb g,
simp only [← smul_assoc, ← finset.sum_smul, smul_eq_zero] at hg,
exact hg.resolve_right ha },
exact le_antisymm
(b.card_le_card_of_linear_independent (c.linear_independent.map' (submodule.subtype I)
(linear_map.ker_eq_bot.mpr subtype.coe_injective)))
(c.card_le_card_of_linear_independent this),
end
variables (R)
@[simp] lemma dim_self : module.rank R R = 1 :=
by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit]
end strong_rank_condition
section division_ring
variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables {K V}
/-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/
lemma basis.finite_of_vector_space_index_of_dim_lt_aleph_0 (h : module.rank K V < ℵ₀) :
(basis.of_vector_space_index K V).finite :=
finite_def.2 $ (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_aleph_0 h
variables [add_comm_group V'] [module K V']
/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_lift_dim_eq
(cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) :
nonempty (V ≃ₗ[K] V') :=
begin
let B := basis.of_vector_space K V,
let B' := basis.of_vector_space K V',
have : cardinal.lift.{v' v} (#_) = cardinal.lift.{v v'} (#_),
by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''],
exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B')
end
/-- Two vector spaces are isomorphic if they have the same dimension. -/
theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) :
nonempty (V ≃ₗ[K] V₁) :=
nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond
section
variables (V V' V₁)
/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_lift_dim_eq
(cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) :
V ≃ₗ[K] V' :=
classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond)
/-- Two vector spaces are isomorphic if they have the same dimension. -/
def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ :=
classical.choice (nonempty_linear_equiv_of_dim_eq cond)
end
/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq :
nonempty (V ≃ₗ[K] V') ↔
cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V') :=
⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩
/-- Two vector spaces are isomorphic if and only if they have the same dimension. -/
theorem linear_equiv.nonempty_equiv_iff_dim_eq :
nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ :=
⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩
-- TODO how far can we generalise this?
-- When `s` is finite, we could prove this for any ring satisfying the strong rank condition
-- using `linear_independent_le_span'`
lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ #s :=
begin
obtain ⟨b, hb, hsab, hlib⟩ := exists_linear_independent K s,
convert cardinal.mk_le_mk_of_subset hb,
rw [← hsab, dim_span_set hlib]
end
lemma dim_span_of_finset (s : finset V) :
module.rank K (span K (↑s : set V)) < ℵ₀ :=
calc module.rank K (span K (↑s : set V)) ≤ #(↑s : set V) : dim_span_le ↑s
... = s.card : by rw [finset.coe_sort_coe, cardinal.mk_coe_finset]
... < ℵ₀ : cardinal.nat_lt_aleph_0 _
theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ :=
begin
let b := basis.of_vector_space K V,
let c := basis.of_vector_space K V₁,
rw [← cardinal.lift_inj,
← (basis.prod b c).mk_eq_dim,
cardinal.lift_add, ← cardinal.mk_ulift,
← b.mk_eq_dim, ← c.mk_eq_dim,
← cardinal.mk_ulift, ← cardinal.mk_ulift,
cardinal.add_def (ulift _)],
exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2
⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩),
end
section fintype
variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)]
open linear_map
lemma dim_pi [finite η] : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) :=
begin
casesI nonempty_fintype η,
let b := assume i, basis.of_vector_space K (φ i),
let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b,
rw [← cardinal.lift_inj, ← this.mk_eq_dim],
simp [← (b _).mk_range_eq_dim]
end
variable [fintype η]
lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] :
module.rank K (η → V) = fintype.card η * module.rank K V :=
by rw [dim_pi, cardinal.sum_const', cardinal.mk_fintype]
lemma dim_fun_eq_lift_mul :
module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) *
cardinal.lift.{u₁'} (module.rank K V) :=
by rw [dim_pi, cardinal.sum_const, cardinal.mk_fintype, cardinal.lift_nat_cast]
lemma dim_fun' : module.rank K (η → K) = fintype.card η :=
by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj]
lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n :=
by simp [dim_fun']
end fintype
end division_ring
section field
variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables [add_comm_group V'] [module K V']
theorem dim_quotient_add_dim (p : submodule K V) :
module.rank K (V ⧸ p) + module.rank K p = module.rank K V :=
by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq
/-- rank-nullity theorem -/
theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) :
module.rank K f.range + module.rank K f.ker = module.rank K V :=
begin
haveI := λ (p : submodule K V), classical.dec_eq (V ⧸ p),
rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim]
end
lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) :
module.rank K V = module.rank K V₁ + module.rank K f.ker :=
by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h]
section
variables [add_comm_group V₂] [module K V₂]
variables [add_comm_group V₃] [module K V₃]
open linear_map
/-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/
lemma dim_add_dim_split
(db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃)
(hde : ⊤ ≤ db.range ⊔ eb.range)
(hgd : ker cd = ⊥)
(eq : db.comp cd = eb.comp ce)
(eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) :
module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ :=
have hf : surjective (coprod db eb),
by rwa [←range_eq_top, range_coprod, eq_top_iff],
begin
conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] },
congr' 1,
apply linear_equiv.dim_eq,
refine linear_equiv.of_bijective _ _ _,
{ refine cod_restrict _ (prod cd (- ce)) _,
{ assume c,
simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, pi.prod,
coprod_apply, neg_neg, map_neg, neg_apply],
exact linear_map.ext_iff.1 eq c } },
{ rw [← ker_eq_bot, ker_cod_restrict, ker_prod, hgd, bot_inf_eq] },
{ rw [← range_eq_top, eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap,
map_top, range_subtype],
rintros ⟨d, e⟩,
have h := eq₂ d (-e),
simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe,
prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range, pi.prod] at ⊢ h,
assume hde,
rcases h hde with ⟨c, h₁, h₂⟩,
refine ⟨c, h₁, _⟩,
rw [h₂, _root_.neg_neg] }
end
lemma dim_sup_add_dim_inf_eq (s t : submodule K V) :
module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) =
module.rank K s + module.rank K t :=
dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right)
begin
rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top,
← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le,
range_subtype, range_subtype, range_subtype],
exact le_rfl
end
(ker_of_le _ _ _)
begin ext ⟨x, hx⟩, refl end
begin
rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq,
obtain rfl : b₁ = b₂ := congr_arg subtype.val eq,
exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩
end
lemma dim_add_le_dim_add_dim (s t : submodule K V) :
module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t :=
by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ }
end
lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) :
∃ b : V, b ∈ s ∧ b ≠ 0 :=
exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h
end field
section rank
section
variables [ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables [add_comm_group V'] [module K V']
/-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/
def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range
lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ :=
dim_submodule_le _
@[simp] lemma rank_zero [nontrivial K] : rank (0 : V →ₗ[K] V') = 0 :=
by rw [rank, linear_map.range_zero, dim_bot]
variables [add_comm_group V''] [module K V'']
lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f :=
begin
refine dim_le_of_submodule _ _ _,
rw [linear_map.range_comp],
exact linear_map.map_le_range,
end
variables [add_comm_group V'₁] [module K V'₁]
lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g :=
by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _
end
section field
variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁]
variables [add_comm_group V'] [module K V']
lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V :=
by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ }
lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g :=
calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') :
begin
refine dim_le_of_submodule _ _ _,
exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $
assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from
mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩)
end
... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _
lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') :
rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) :=
@finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero)
(λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _))
end field
end rank
section division_ring
variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V'] [module K V']
/-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional.
See also `finite_dimensional.fin_basis`.
-/
def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) :
basis ι K V :=
begin
haveI : subsingleton V := dim_zero_iff.1 hV,
exact basis.empty _
end
@[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι]
(hV : module.rank K V = 0) (i : ι) :
basis.of_dim_eq_zero hV i = 0 :=
rfl
lemma le_dim_iff_exists_linear_independent {c : cardinal} :
c ≤ module.rank K V ↔ ∃ s : set V, #s = c ∧ linear_independent K (coe : s → V) :=
begin
split,
{ intro h,
let t := basis.of_vector_space K V,
rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h,
rcases h with ⟨s, hst, hsc⟩,
exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ },
{ rintro ⟨s, rfl, si⟩,
exact cardinal_le_dim_of_linear_independent si }
end
lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} :
↑n ≤ module.rank K V ↔
∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) :=
begin
simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset],
split,
{ rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩,
exact ⟨t, rfl, si⟩ },
{ rintro ⟨s, rfl, si⟩,
exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ }
end
/-- A vector space has dimension at most `1` if and only if there is a
single vector of which all vectors are multiples. -/
lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v :=
begin
let b := basis.of_vector_space K V,
split,
{ intro hd,
rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd,
rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩,
{ use 0,
have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm },
intro v,
simp [h' v] },
{ use v₀,
have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq },
intro v,
have hv : v ∈ (⊤ : submodule K V) := mem_top,
rwa [←h', mem_span_singleton] at hv } },
{ rintros ⟨v₀, hv₀⟩,
have h : (K ∙ v₀) = ⊤,
{ ext, simp [mem_span_singleton, hv₀] },
rw [←dim_top, ←h],
convert dim_span_le _,
simp }
end
/-- A submodule has dimension at most `1` if and only if there is a
single vector in the submodule such that the submodule is contained in
its span. -/
lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ :=
begin
simp_rw [dim_le_one_iff, le_span_singleton_iff],
split,
{ rintro ⟨⟨v₀, hv₀⟩, h⟩,
use [v₀, hv₀],
intros v hv,
obtain ⟨r, hr⟩ := h ⟨v, hv⟩,
use r,
simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr,
exact hr },
{ rintro ⟨v₀, hv₀, h⟩,
use ⟨v₀, hv₀⟩,
rintro ⟨v, hv⟩,
obtain ⟨r, hr⟩ := h v hv,
use r,
simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk],
exact hr }
end
/-- A submodule has dimension at most `1` if and only if there is a
single vector, not necessarily in the submodule, such that the
submodule is contained in its span. -/
lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ :=
begin
rw dim_submodule_le_one_iff,
split,
{ rintros ⟨v₀, hv₀, h⟩,
exact ⟨v₀, h⟩ },
{ rintros ⟨v₀, h⟩,
by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0,
{ rcases hw with ⟨w, hw, hw0⟩,
use [w, hw],
rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩,
have h0 : r' ≠ 0,
{ rintro rfl,
simpa using hw0 },
rwa span_singleton_smul_eq (is_unit.mk0 _ h0) _ },
{ push_neg at hw,
rw ←submodule.eq_bot_iff at hw,
simp [hw] } }
end
lemma submodule.rank_le_one_iff_is_principal (W : submodule K V) :
module.rank K W ≤ 1 ↔ W.is_principal :=
begin
simp only [dim_le_one_iff, submodule.is_principal_iff, le_antisymm_iff,
le_span_singleton_iff, span_singleton_le_iff_mem],
split,
{ rintro ⟨⟨m, hm⟩, hm'⟩,
choose f hf using hm',
exact ⟨m, ⟨λ v hv, ⟨f ⟨v, hv⟩, congr_arg coe (hf ⟨v, hv⟩)⟩, hm⟩⟩ },
{ rintro ⟨a, ⟨h, ha⟩⟩,
choose f hf using h,
exact ⟨⟨a, ha⟩, λ v, ⟨f v.1 v.2, subtype.ext (hf v.1 v.2)⟩⟩ }
end
lemma module.rank_le_one_iff_top_is_principal :
module.rank K V ≤ 1 ↔ (⊤ : submodule K V).is_principal :=
by rw [← submodule.rank_le_one_iff_is_principal, dim_top]
end division_ring
section field
variables [field K] [add_comm_group V] [module K V] [add_comm_group V'] [module K V']
lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} :
c ≤ rank f ↔
∃ s : set V, cardinal.lift.{v'} (#s) = cardinal.lift.{v} c ∧
linear_independent K (λ x : s, f x) :=
begin
rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩,
have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg,
refine ⟨λ h, _, _⟩,
{ rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩,
refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩,
replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) },
replace si : linear_independent K (λ x : s, f (g x)),
by simpa only [fg] using si.map' _ (ker_subtype _),
exact si.image_of_comp s g f },
{ rintro ⟨s, hsc, si⟩,
have : linear_independent K (λ x : s, f.range_restrict x),
from linear_independent.of_comp (f.range.subtype) (by convert si),
convert cardinal_le_dim_of_linear_independent this.image,
rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift],
exact inj_on_iff_injective.2 this.injective }
end
lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} :
↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) :=
begin
simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast,
cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset],
split,
{ rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩,
exact ⟨t, rfl, si⟩ },
{ rintro ⟨s, rfl, si⟩,
exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ }
end
end field
end module
|
c2787bfd292d3127bf5dace01b05c1f1fda2055f | 5412d79aa1dc0b521605c38bef9f0d4557b5a29d | /stage0/src/Lean/Meta/Tactic/Simp/Rewrite.lean | c6ce9f657bdaaaad7cf7b4ac5ee00660e062609f | [
"Apache-2.0"
] | permissive | smunix/lean4 | a450ec0927dc1c74816a1bf2818bf8600c9fc9bf | 3407202436c141e3243eafbecb4b8720599b970a | refs/heads/master | 1,676,334,875,188 | 1,610,128,510,000 | 1,610,128,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,138 | 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.SynthInstance
import Lean.Meta.Tactic.Simp.Types
namespace Lean.Meta.Simp
/-
Remark: the parameter tag is used for creating trace messages. It is irrelevant otherwise.
-/
def rewrite (e : Expr) (s : DiscrTree SimpLemma) (discharge? : Expr → SimpM σ (Option Expr)) (tag : String) : SimpM σ Result := do
let lemmas ← s.getMatch e
if lemmas.isEmpty then
trace[Meta.Tactic.simp]! "no lemmas found for {tag}-rewriting {e}"
return { expr := e }
else
let lemmas := lemmas.insertionSort fun e₁ e₂ => e₁.priority < e₂.priority
for lemma in lemmas do
if let some result ← tryLemma? lemma then
return result
return { expr := e }
where
getLHS (kind : SimpLemmaKind) (type : Expr) : MetaM Expr :=
match kind with
| SimpLemmaKind.pos => return type
| SimpLemmaKind.neg => return type.appArg!
| SimpLemmaKind.eq => return type.appFn!.appArg!
| SimpLemmaKind.iff => return type.appFn!.appArg!
getRHS (kind : SimpLemmaKind) (type : Expr) : MetaM Expr :=
match kind with
| SimpLemmaKind.pos => return mkConst `True
| SimpLemmaKind.neg => return mkConst `False
| SimpLemmaKind.eq => return type.appArg!
| SimpLemmaKind.iff => return type.appArg!
synthesizeArgs (lemma : SimpLemma) (xs : Array Expr) (bis : Array BinderInfo) : SimpM σ Bool := do
for x in xs, bi in bis do
let type ← inferType x
if bi.isInstImplicit then
match ← trySynthInstance type with
| LOption.some val =>
unless (← isDefEq x val) do
trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to assign instance{indentExpr type}"
return false
| _ =>
trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to synthesize instance{indentExpr type}"
return false
else if (← isProp type <&&> (← instantiateMVars x).isMVar) then
match ← discharge? type with
| some proof =>
unless (← isDefEq x proof) do
trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to assign proof{indentExpr type}"
return false
| none =>
trace[Meta.Tactic.simp.discharge]! "{lemma}, failed to discharge hypotheses{indentExpr type}"
return false
return true
finalizeProof (kind : SimpLemmaKind) (proof : Expr) : MetaM Expr :=
match kind with
| SimpLemmaKind.eq => return proof
| SimpLemmaKind.iff => mkPropExt proof
| SimpLemmaKind.pos => mkEqTrue proof
| SimpLemmaKind.neg => mkEqFalse proof
tryLemma? (lemma : SimpLemma) : SimpM σ (Option Result) :=
withNewMCtxDepth do
let val ← lemma.getValue
let type ← inferType val
let (xs, bis, type) ← forallMetaTelescopeReducing type
let lhs ← getLHS lemma.kind type
if (← isDefEq lhs e) then
unless (← synthesizeArgs lemma xs bis) do
return none
let proof ← instantiateMVars (mkAppN val xs)
if ← hasAssignableMVar proof then
return none
let rhs ← instantiateMVars (← getRHS lemma.kind type)
if lemma.perm && !Expr.lt rhs e then
trace[Meta.Tactic.simp.unify]! "{lemma}, perm rejected {e} ==> {rhs}"
return none
let proof ← finalizeProof lemma.kind proof
trace[Meta.Tactic.simp.rewrite]! "{lemma}, {e} ==> {rhs}"
return some { expr := rhs, proof? := proof }
else
trace[Meta.Tactic.simp.unify]! "{lemma}, failed to unify {lhs} with {e}"
return none
def preDefault (e : Expr) (discharge? : Expr → SimpM σ (Option Expr)) : SimpM σ Step := do
let lemmas ← (← read).simpLemmas
return Step.visit (← rewrite e lemmas.pre discharge? (tag := "pre"))
def postDefault (e : Expr) (discharge? : Expr → SimpM σ (Option Expr)) : SimpM σ Step := do
let lemmas ← (← read).simpLemmas
return Step.visit (← rewrite e lemmas.post discharge? (tag := "post"))
end Lean.Meta.Simp
|
6d95a2c825ec2fdf097a35a56d83d638ef5bb811 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/topology/algebra/uniform_ring.lean | 352133201aa6bfb6b8869b411ba606b70909ebbd | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 10,190 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import algebra.algebra.basic
import topology.algebra.group_completion
import topology.algebra.ring
/-!
# Completion of topological rings:
This files endows the completion of a topological ring with a ring structure.
More precisely the instance `uniform_space.completion.ring` builds a ring structure
on the completion of a ring endowed with a compatible uniform structure in the sense of
`uniform_add_group`. There is also a commutative version when the original ring is commutative.
Moreover, if a topological ring is an algebra over a commutative semiring, then so is its
`uniform_space.completion`.
The last part of the file builds a ring structure on the biggest separated quotient of a ring.
## Main declarations:
Beyond the instances explained above (that don't have to be explicitly invoked),
the main constructions deal with continuous ring morphisms.
* `uniform_space.completion.extension_hom`: extends a continuous ring morphism from `R`
to a complete separated group `S` to `completion R`.
* `uniform_space.completion.map_ring_hom` : promotes a continuous ring morphism
from `R` to `S` into a continuous ring morphism from `completion R` to `completion S`.
TODO: Generalise the results here from the concrete `completion` to any `abstract_completion`.
-/
open classical set filter topological_space add_comm_group
open_locale classical
noncomputable theory
universes u
namespace uniform_space.completion
open dense_inducing uniform_space function
variables (α : Type*) [ring α] [uniform_space α]
instance : has_one (completion α) := ⟨(1:α)⟩
instance : has_mul (completion α) :=
⟨curry $ (dense_inducing_coe.prod dense_inducing_coe).extend (coe ∘ uncurry (*))⟩
@[norm_cast] lemma coe_one : ((1 : α) : completion α) = 1 := rfl
variables {α} [topological_ring α]
@[norm_cast]
lemma coe_mul (a b : α) : ((a * b : α) : completion α) = a * b :=
((dense_inducing_coe.prod dense_inducing_coe).extend_eq
((continuous_coe α).comp (@continuous_mul α _ _ _)) (a, b)).symm
variables [uniform_add_group α]
lemma continuous_mul : continuous (λ p : completion α × completion α, p.1 * p.2) :=
begin
let m := (add_monoid_hom.mul : α →+ α →+ α).compr₂ to_compl,
have : continuous (λ p : α × α, m p.1 p.2),
from (continuous_coe α).comp continuous_mul,
have di : dense_inducing (to_compl : α → completion α),
from dense_inducing_coe,
convert di.extend_Z_bilin di this,
ext ⟨x, y⟩,
refl
end
lemma continuous.mul {β : Type*} [topological_space β] {f g : β → completion α}
(hf : continuous f) (hg : continuous g) : continuous (λb, f b * g b) :=
continuous_mul.comp (hf.prod_mk hg : _)
instance : ring (completion α) :=
{ one_mul := assume a, completion.induction_on a
(is_closed_eq (continuous.mul continuous_const continuous_id) continuous_id)
(assume a, by rw [← coe_one, ← coe_mul, one_mul]),
mul_one := assume a, completion.induction_on a
(is_closed_eq (continuous.mul continuous_id continuous_const) continuous_id)
(assume a, by rw [← coe_one, ← coe_mul, mul_one]),
mul_assoc := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul (continuous.mul continuous_fst (continuous_fst.comp continuous_snd))
(continuous_snd.comp continuous_snd))
(continuous.mul continuous_fst
(continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_mul, ← coe_mul, ← coe_mul, ← coe_mul, mul_assoc]),
left_distrib := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul continuous_fst (continuous.add
(continuous_fst.comp continuous_snd)
(continuous_snd.comp continuous_snd)))
(continuous.add
(continuous.mul continuous_fst (continuous_fst.comp continuous_snd))
(continuous.mul continuous_fst (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, mul_add]),
right_distrib := assume a b c, completion.induction_on₃ a b c
(is_closed_eq
(continuous.mul (continuous.add continuous_fst
(continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd))
(continuous.add
(continuous.mul continuous_fst (continuous_snd.comp continuous_snd))
(continuous.mul (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd))))
(assume a b c, by rw [← coe_add, ← coe_mul, ← coe_mul, ← coe_mul, ←coe_add, add_mul]),
.. add_monoid_with_one.unary,
..completion.add_comm_group, ..completion.has_mul α, ..completion.has_one α }
/-- The map from a uniform ring to its completion, as a ring homomorphism. -/
def coe_ring_hom : α →+* completion α :=
⟨coe, coe_one α, assume a b, coe_mul a b, coe_zero, assume a b, coe_add a b⟩
lemma continuous_coe_ring_hom : continuous (coe_ring_hom : α → completion α) :=
continuous_coe α
variables {β : Type u} [uniform_space β] [ring β] [uniform_add_group β] [topological_ring β]
(f : α →+* β) (hf : continuous f)
/-- The completion extension as a ring morphism. -/
def extension_hom [complete_space β] [separated_space β] :
completion α →+* β :=
have hf' : continuous (f : α →+ β), from hf, -- helping the elaborator
have hf : uniform_continuous f, from uniform_continuous_add_monoid_hom_of_continuous hf',
{ to_fun := completion.extension f,
map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero],
map_add' := assume a b, completion.induction_on₂ a b
(is_closed_eq
(continuous_extension.comp continuous_add)
((continuous_extension.comp continuous_fst).add
(continuous_extension.comp continuous_snd)))
(assume a b,
by rw [← coe_add, extension_coe hf, extension_coe hf, extension_coe hf,
f.map_add]),
map_one' := by rw [← coe_one, extension_coe hf, f.map_one],
map_mul' := assume a b, completion.induction_on₂ a b
(is_closed_eq
(continuous_extension.comp continuous_mul)
((continuous_extension.comp continuous_fst).mul (continuous_extension.comp continuous_snd)))
(assume a b,
by rw [← coe_mul, extension_coe hf, extension_coe hf, extension_coe hf, f.map_mul]) }
instance top_ring_compl : topological_ring (completion α) :=
{ continuous_add := continuous_add,
continuous_mul := continuous_mul }
/-- The completion map as a ring morphism. -/
def map_ring_hom (hf : continuous f) : completion α →+* completion β :=
extension_hom (coe_ring_hom.comp f) (continuous_coe_ring_hom.comp hf)
section algebra
variables (A : Type*) [ring A] [uniform_space A] [uniform_add_group A] [topological_ring A]
(R : Type*) [comm_semiring R] [algebra R A] [has_uniform_continuous_const_smul R A]
@[simp] lemma map_smul_eq_mul_coe (r : R) :
completion.map ((•) r) = (*) (algebra_map R A r : completion A) :=
begin
ext x,
refine completion.induction_on x _ (λ a, _),
{ exact is_closed_eq (completion.continuous_map) (continuous_mul_left _) },
{ rw [map_coe (uniform_continuous_const_smul r) a, algebra.smul_def, coe_mul] },
end
instance : algebra R (completion A) :=
{ commutes' := λ r x, completion.induction_on x
(is_closed_eq (continuous_mul_left _) (continuous_mul_right _)) $ λ a,
by simpa only [coe_mul] using congr_arg (coe : A → completion A) (algebra.commutes r a),
smul_def' := λ r x, congr_fun (map_smul_eq_mul_coe A R r) x,
..((uniform_space.completion.coe_ring_hom : A →+* completion A).comp (algebra_map R A)) }
lemma algebra_map_def (r : R) :
algebra_map R (completion A) r = (algebra_map R A r : completion A) :=
rfl
end algebra
section comm_ring
variables (R : Type*) [comm_ring R] [uniform_space R] [uniform_add_group R] [topological_ring R]
instance : comm_ring (completion R) :=
{ mul_comm := assume a b, completion.induction_on₂ a b
(is_closed_eq (continuous_fst.mul continuous_snd)
(continuous_snd.mul continuous_fst))
(assume a b, by rw [← coe_mul, ← coe_mul, mul_comm]),
..completion.ring }
/-- A shortcut instance for the common case -/
instance algebra' : algebra R (completion R) :=
by apply_instance
end comm_ring
end uniform_space.completion
namespace uniform_space
variables {α : Type*}
lemma ring_sep_rel (α) [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
separation_setoid α = submodule.quotient_rel (ideal.closure ⊥) :=
setoid.ext $ λ x y, (add_group_separation_rel x y).trans $
iff.trans (by refl) (submodule.quotient_rel_r_def _).symm
lemma ring_sep_quot
(α : Type u) [r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
quotient (separation_setoid α) = (α ⧸ (⊥ : ideal α).closure) :=
by rw [@ring_sep_rel α r]; refl
/-- Given a topological ring `α` equipped with a uniform structure that makes subtraction uniformly
continuous, get an equivalence between the separated quotient of `α` and the quotient ring
corresponding to the closure of zero. -/
def sep_quot_equiv_ring_quot (α)
[r : comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
quotient (separation_setoid α) ≃ (α ⧸ (⊥ : ideal α).closure) :=
quotient.congr_right $ λ x y, (add_group_separation_rel x y).trans $
iff.trans (by refl) (submodule.quotient_rel_r_def _).symm
/- TODO: use a form of transport a.k.a. lift definition a.k.a. transfer -/
instance comm_ring [comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
comm_ring (quotient (separation_setoid α)) :=
by rw ring_sep_quot α; apply_instance
instance topological_ring
[comm_ring α] [uniform_space α] [uniform_add_group α] [topological_ring α] :
topological_ring (quotient (separation_setoid α)) :=
begin
convert topological_ring_quotient (⊥ : ideal α).closure; try {apply ring_sep_rel},
simp [uniform_space.comm_ring]
end
end uniform_space
|
584a3715b032563f87cbebf2d7e2d016ee2c2df7 | df561f413cfe0a88b1056655515399c546ff32a5 | /3-function-world/l8.lean | ec09c42cf4cea1f758c43309403c15904612f5f2 | [] | no_license | nicholaspun/natural-number-game-solutions | 31d5158415c6f582694680044c5c6469032c2a06 | 1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0 | refs/heads/main | 1,675,123,625,012 | 1,607,633,548,000 | 1,607,633,548,000 | 318,933,860 | 3 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 112 | lean | example (P Q : Type) : (P → Q) → ((Q → empty) → (P → empty)) :=
begin
intros f g p,
exact g(f(p)),
end |
e73b8316dd026d6f51165c4ed414c68050fb1d97 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /tests/lean/run/ind7.lean | fae5f6192b1ad76de7cff564519e52b2e688b611 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 196 | lean | namespace list
inductive list (A : Type) : Type :=
nil : list A,
cons : A → list A → list A
check list.{1}
check list.cons.{1}
check list.rec.{1 1}
end list
check list.list.{1}
|
1d7257397b2badb6edd9a902153b538c382ec068 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/convex/measure.lean | cf1486d21fdaa6617d594b629dee1aa2648da493 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 4,354 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.convex.topology
import analysis.normed_space.add_torsor_bases
import measure_theory.measure.haar_lebesgue
/-!
# Convex sets are null-measurable
Let `E` be a finite dimensional real vector space, let `μ` be a Haar measure on `E`, let `s` be a
convex set in `E`. Then the frontier of `s` has measure zero (see `convex.add_haar_frontier`), hence
`s` is a `measure_theory.null_measurable_set` (see `convex.null_measurable_set`).
-/
open measure_theory measure_theory.measure set metric filter finite_dimensional (finrank)
open_locale topological_space nnreal ennreal
variables {E : Type*} [normed_group E] [normed_space ℝ E] [measurable_space E] [borel_space E]
[finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {s : set E}
namespace convex
/-- Haar measure of the frontier of a convex set is zero. -/
lemma add_haar_frontier (hs : convex ℝ s) : μ (frontier s) = 0 :=
begin
/- If `s` is included in a hyperplane, then `frontier s ⊆ closure s` is included in the same
hyperplane, hence it has measure zero. -/
cases ne_or_eq (affine_span ℝ s) ⊤ with hspan hspan,
{ refine measure_mono_null _ (add_haar_affine_subspace _ _ hspan),
exact frontier_subset_closure.trans (closure_minimal (subset_affine_span _ _)
(affine_span ℝ s).closed_of_finite_dimensional) },
rw ← hs.interior_nonempty_iff_affine_span_eq_top at hspan,
rcases hspan with ⟨x, hx⟩,
/- Without loss of generality, `s` is bounded. Indeed, `∂s ⊆ ⋃ n, ∂(s ∩ ball x (n + 1))`, hence it
suffices to prove that `∀ n, μ (s ∩ ball x (n + 1)) = 0`; the latter set is bounded.
-/
suffices H : ∀ t : set E, convex ℝ t → x ∈ interior t → bounded t → μ (frontier t) = 0,
{ set B : ℕ → set E := λ n, ball x (n + 1),
have : μ (⋃ n : ℕ, frontier (s ∩ B n)) = 0,
{ refine measure_Union_null (λ n, H _ (hs.inter (convex_ball _ _)) _
(bounded_ball.mono (inter_subset_right _ _))),
rw [interior_inter, is_open_ball.interior_eq],
exact ⟨hx, mem_ball_self (add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one)⟩ },
refine measure_mono_null (λ y hy, _) this, clear this,
set N : ℕ := ⌊dist y x⌋₊,
refine mem_Union.2 ⟨N, _⟩,
have hN : y ∈ B N, by { simp only [B, N], simp [nat.lt_floor_add_one] },
suffices : y ∈ frontier (s ∩ B N) ∩ B N, from this.1,
rw [frontier_inter_open_inter is_open_ball],
exact ⟨hy, hN⟩ },
clear hx hs s, intros s hs hx hb,
/- Since `s` is bounded, we have `μ (interior s) ≠ ∞`, hence it suffices to prove
`μ (closure s) ≤ μ (interior s)`. -/
replace hb : μ (interior s) ≠ ∞, from (hb.mono interior_subset).measure_lt_top.ne,
suffices : μ (closure s) ≤ μ (interior s),
{ rwa [frontier, measure_diff interior_subset_closure is_open_interior.measurable_set hb,
tsub_eq_zero_iff_le] },
/- Due to `convex.closure_subset_image_homothety_interior_of_one_lt`, for any `r > 1` we have
`closure s ⊆ homothety x r '' interior s`, hence `μ (closure s) ≤ r ^ d * μ (interior s)`,
where `d = finrank ℝ E`. -/
set d : ℕ := finite_dimensional.finrank ℝ E,
have : ∀ r : ℝ≥0, 1 < r → μ (closure s) ≤ ↑(r ^ d) * μ (interior s),
{ intros r hr,
refine (measure_mono $ hs.closure_subset_image_homothety_interior_of_one_lt hx r hr).trans_eq _,
rw [add_haar_image_homothety, ← nnreal.coe_pow, nnreal.abs_eq, ennreal.of_real_coe_nnreal] },
have : ∀ᶠ r in 𝓝[>] (1 : ℝ≥0), μ (closure s) ≤ ↑(r ^ d) * μ (interior s),
from mem_of_superset self_mem_nhds_within this,
/- Taking the limit as `r → 1`, we get `μ (closure s) ≤ μ (interior s)`. -/
refine ge_of_tendsto _ this,
refine (((ennreal.continuous_mul_const hb).comp
(ennreal.continuous_coe.comp (continuous_pow d))).tendsto' _ _ _).mono_left nhds_within_le_nhds,
simp
end
/-- A convex set in a finite dimensional real vector space is null measurable with respect to an
additive Haar measure on this space. -/
protected lemma null_measurable_set (hs : convex ℝ s) : null_measurable_set s μ :=
null_measurable_set_of_null_frontier (hs.add_haar_frontier μ)
end convex
|
decd6879c5873992c589cc4f6ce80013f4b2baad | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/topology/constructions.lean | 93b682eaf84334f6b1a1e3c55edb8f7051a8ac04 | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 34,846 | 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, Patrick Massot
-/
import topology.maps
/-!
# Constructions of new topological spaces from old ones
This file constructs products, sums, subtypes and quotients of topological spaces
and sets up their basic theory, such as criteria for maps into or out of these
constructions to be continuous; descriptions of the open sets, neighborhood filters,
and generators of these constructions; and their behavior with respect to embeddings
and other specific classes of maps.
## Implementation note
The constructed topologies are defined using induced and coinduced topologies
along with the complete lattice structure on topologies. Their universal properties
(for example, a map `X → Y × Z` is continuous if and only if both projections
`X → Y`, `X → Z` are) follow easily using order-theoretic descriptions of
continuity. With more work we can also extract descriptions of the open sets,
neighborhood filters and so on.
## Tags
product, sum, disjoint union, subspace, quotient space
-/
noncomputable theory
open topological_space set filter
open_locale classical topological_space filter
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
section constructions
instance {p : α → Prop} [t : topological_space α] : topological_space (subtype p) :=
induced coe t
instance {r : α → α → Prop} [t : topological_space α] : topological_space (quot r) :=
coinduced (quot.mk r) t
instance {s : setoid α} [t : topological_space α] : topological_space (quotient s) :=
coinduced quotient.mk t
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α × β) :=
induced prod.fst t₁ ⊓ induced prod.snd t₂
instance [t₁ : topological_space α] [t₂ : topological_space β] : topological_space (α ⊕ β) :=
coinduced sum.inl t₁ ⊔ coinduced sum.inr t₂
instance {β : α → Type v} [t₂ : Πa, topological_space (β a)] : topological_space (sigma β) :=
⨆a, coinduced (sigma.mk a) (t₂ a)
instance Pi.topological_space {β : α → Type v} [t₂ : Πa, topological_space (β a)] :
topological_space (Πa, β a) :=
⨅a, induced (λf, f a) (t₂ a)
instance ulift.topological_space [t : topological_space α] : topological_space (ulift.{v u} α) :=
t.induced ulift.down
/-- The image of a dense set under `quotient.mk` is a dense set. -/
lemma dense.quotient [setoid α] [topological_space α] {s : set α} (H : dense s) :
dense (quotient.mk '' s) :=
(surjective_quotient_mk α).dense_range.dense_image continuous_coinduced_rng H
/-- The composition of `quotient.mk` and a function with dense range has dense range. -/
lemma dense_range.quotient [setoid α] [topological_space α] {f : β → α} (hf : dense_range f) :
dense_range (quotient.mk ∘ f) :=
(surjective_quotient_mk α).dense_range.comp hf continuous_coinduced_rng
instance {p : α → Prop} [topological_space α] [discrete_topology α] :
discrete_topology (subtype p) :=
⟨bot_unique $ assume s hs,
⟨coe '' s, is_open_discrete _, (set.preimage_image_eq _ subtype.coe_injective)⟩⟩
instance sum.discrete_topology [topological_space α] [topological_space β]
[hα : discrete_topology α] [hβ : discrete_topology β] : discrete_topology (α ⊕ β) :=
⟨by unfold sum.topological_space; simp [hα.eq_bot, hβ.eq_bot]⟩
instance sigma.discrete_topology {β : α → Type v} [Πa, topological_space (β a)]
[h : Πa, discrete_topology (β a)] : discrete_topology (sigma β) :=
⟨by { unfold sigma.topological_space, simp [λ a, (h a).eq_bot] }⟩
section topα
variable [topological_space α]
/-
The 𝓝 filter and the subspace topology.
-/
theorem mem_nhds_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) :
t ∈ 𝓝 a ↔ ∃ u ∈ 𝓝 (a : α), coe ⁻¹' u ⊆ t :=
mem_nhds_induced coe a t
theorem nhds_subtype (s : set α) (a : {x // x ∈ s}) :
𝓝 a = comap coe (𝓝 (a : α)) :=
nhds_induced coe a
end topα
end constructions
section prod
variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ]
@[continuity] lemma continuous_fst : continuous (@prod.fst α β) :=
continuous_inf_dom_left continuous_induced_dom
lemma continuous_at_fst {p : α × β} : continuous_at prod.fst p :=
continuous_fst.continuous_at
@[continuity] lemma continuous_snd : continuous (@prod.snd α β) :=
continuous_inf_dom_right continuous_induced_dom
lemma continuous_at_snd {p : α × β} : continuous_at prod.snd p :=
continuous_snd.continuous_at
@[continuity] lemma continuous.prod_mk {f : γ → α} {g : γ → β}
(hf : continuous f) (hg : continuous g) : continuous (λx, (f x, g x)) :=
continuous_inf_rng (continuous_induced_rng hf) (continuous_induced_rng hg)
lemma continuous.prod_map {f : γ → α} {g : δ → β} (hf : continuous f) (hg : continuous g) :
continuous (λ x : γ × δ, (f x.1, g x.2)) :=
(hf.comp continuous_fst).prod_mk (hg.comp continuous_snd)
lemma filter.eventually.prod_inl_nhds {p : α → Prop} {a : α} (h : ∀ᶠ x in 𝓝 a, p x) (b : β) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).1 :=
continuous_at_fst h
lemma filter.eventually.prod_inr_nhds {p : β → Prop} {b : β} (h : ∀ᶠ x in 𝓝 b, p x) (a : α) :
∀ᶠ x in 𝓝 (a, b), p (x : α × β).2 :=
continuous_at_snd h
lemma filter.eventually.prod_mk_nhds {pa : α → Prop} {a} (ha : ∀ᶠ x in 𝓝 a, pa x)
{pb : β → Prop} {b} (hb : ∀ᶠ y in 𝓝 b, pb y) :
∀ᶠ p in 𝓝 (a, b), pa (p : α × β).1 ∧ pb p.2 :=
(ha.prod_inl_nhds b).and (hb.prod_inr_nhds a)
lemma continuous_swap : continuous (prod.swap : α × β → β × α) :=
continuous.prod_mk continuous_snd continuous_fst
lemma is_open.prod {s : set α} {t : set β} (hs : is_open s) (ht : is_open t) :
is_open (set.prod s t) :=
is_open_inter (hs.preimage continuous_fst) (ht.preimage continuous_snd)
lemma nhds_prod_eq {a : α} {b : β} : 𝓝 (a, b) = 𝓝 a ×ᶠ 𝓝 b :=
by rw [filter.prod, prod.topological_space, nhds_inf, nhds_induced, nhds_induced]
lemma mem_nhds_prod_iff {a : α} {b : β} {s : set (α × β)} :
s ∈ 𝓝 (a, b) ↔ ∃ (u ∈ 𝓝 a) (v ∈ 𝓝 b), set.prod u v ⊆ s :=
by rw [nhds_prod_eq, mem_prod_iff]
lemma filter.has_basis.prod_nhds {ιa ιb : Type*} {pa : ιa → Prop} {pb : ιb → Prop}
{sa : ιa → set α} {sb : ιb → set β} {a : α} {b : β} (ha : (𝓝 a).has_basis pa sa)
(hb : (𝓝 b).has_basis pb sb) :
(𝓝 (a, b)).has_basis (λ i : ιa × ιb, pa i.1 ∧ pb i.2) (λ i, (sa i.1).prod (sb i.2)) :=
by { rw nhds_prod_eq, exact ha.prod hb }
instance [discrete_topology α] [discrete_topology β] : discrete_topology (α × β) :=
⟨eq_of_nhds_eq_nhds $ assume ⟨a, b⟩,
by rw [nhds_prod_eq, nhds_discrete α, nhds_discrete β, nhds_bot, filter.prod_pure_pure]⟩
lemma prod_mem_nhds_sets {s : set α} {t : set β} {a : α} {b : β}
(ha : s ∈ 𝓝 a) (hb : t ∈ 𝓝 b) : set.prod s t ∈ 𝓝 (a, b) :=
by rw [nhds_prod_eq]; exact prod_mem_prod ha hb
lemma nhds_swap (a : α) (b : β) : 𝓝 (a, b) = (𝓝 (b, a)).map prod.swap :=
by rw [nhds_prod_eq, filter.prod_comm, nhds_prod_eq]; refl
lemma filter.tendsto.prod_mk_nhds {γ} {a : α} {b : β} {f : filter γ} {ma : γ → α} {mb : γ → β}
(ha : tendsto ma f (𝓝 a)) (hb : tendsto mb f (𝓝 b)) :
tendsto (λc, (ma c, mb c)) f (𝓝 (a, b)) :=
by rw [nhds_prod_eq]; exact filter.tendsto.prod_mk ha hb
lemma filter.eventually.curry_nhds {p : α × β → Prop} {x : α} {y : β} (h : ∀ᶠ x in 𝓝 (x, y), p x) :
∀ᶠ x' in 𝓝 x, ∀ᶠ y' in 𝓝 y, p (x', y') :=
by { rw [nhds_prod_eq] at h, exact h.curry }
lemma continuous_at.prod {f : α → β} {g : α → γ} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λx, (f x, g x)) x :=
hf.prod_mk_nhds hg
lemma continuous_at.prod_map {f : α → γ} {g : β → δ} {p : α × β}
(hf : continuous_at f p.fst) (hg : continuous_at g p.snd) :
continuous_at (λ p : α × β, (f p.1, g p.2)) p :=
(hf.comp continuous_fst.continuous_at).prod (hg.comp continuous_snd.continuous_at)
lemma continuous_at.prod_map' {f : α → γ} {g : β → δ} {x : α} {y : β}
(hf : continuous_at f x) (hg : continuous_at g y) :
continuous_at (λ p : α × β, (f p.1, g p.2)) (x, y) :=
have hf : continuous_at f (x, y).fst, from hf,
have hg : continuous_at g (x, y).snd, from hg,
hf.prod_map hg
lemma prod_generate_from_generate_from_eq {α : Type*} {β : Type*} {s : set (set α)} {t : set (set β)}
(hs : ⋃₀ s = univ) (ht : ⋃₀ t = univ) :
@prod.topological_space α β (generate_from s) (generate_from t) =
generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} :=
let G := generate_from {g | ∃u∈s, ∃v∈t, g = set.prod u v} in
le_antisymm
(le_generate_from $ assume g ⟨u, hu, v, hv, g_eq⟩, g_eq.symm ▸
@is_open.prod _ _ (generate_from s) (generate_from t) _ _
(generate_open.basic _ hu) (generate_open.basic _ hv))
(le_inf
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume u hu,
have (⋃v∈t, set.prod u v) = prod.fst ⁻¹' u,
from calc (⋃v∈t, set.prod u v) = set.prod u univ :
set.ext $ assume ⟨a, b⟩, by rw ← ht; simp [and.left_comm] {contextual:=tt}
... = prod.fst ⁻¹' u : by simp [set.prod, preimage],
show G.is_open (prod.fst ⁻¹' u),
from this ▸ @is_open_Union _ _ G _ $ assume v, @is_open_Union _ _ G _ $ assume hv,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩)
(coinduced_le_iff_le_induced.mp $ le_generate_from $ assume v hv,
have (⋃u∈s, set.prod u v) = prod.snd ⁻¹' v,
from calc (⋃u∈s, set.prod u v) = set.prod univ v:
set.ext $ assume ⟨a, b⟩, by rw [←hs]; by_cases b ∈ v; simp [h] {contextual:=tt}
... = prod.snd ⁻¹' v : by simp [set.prod, preimage],
show G.is_open (prod.snd ⁻¹' v),
from this ▸ @is_open_Union _ _ G _ $ assume u, @is_open_Union _ _ G _ $ assume hu,
generate_open.basic _ ⟨_, hu, _, hv, rfl⟩))
lemma prod_eq_generate_from :
prod.topological_space =
generate_from {g | ∃(s:set α) (t:set β), is_open s ∧ is_open t ∧ g = set.prod s t} :=
le_antisymm
(le_generate_from $ assume g ⟨s, t, hs, ht, g_eq⟩, g_eq.symm ▸ hs.prod ht)
(le_inf
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨t, univ, by simpa [set.prod_eq] using ht⟩)
(ball_image_of_ball $ λt ht, generate_open.basic _ ⟨univ, t, by simpa [set.prod_eq] using ht⟩))
lemma is_open_prod_iff {s : set (α×β)} : is_open s ↔
(∀a b, (a, b) ∈ s → ∃u v, is_open u ∧ is_open v ∧ a ∈ u ∧ b ∈ v ∧ set.prod u v ⊆ s) :=
begin
rw [is_open_iff_nhds],
simp_rw [le_principal_iff, prod.forall,
((nhds_basis_opens _).prod_nhds (nhds_basis_opens _)).mem_iff, prod.exists, exists_prop],
simp only [and_assoc, and.left_comm]
end
/-- Given a neighborhood `s` of `(x, x)`, then `(x, x)` has a square open neighborhood
that is a subset of `s`. -/
lemma exists_nhds_square {s : set (α × α)} {x : α} (hx : s ∈ 𝓝 (x, x)) :
∃U, is_open U ∧ x ∈ U ∧ set.prod U U ⊆ s :=
by simpa [nhds_prod_eq, (nhds_basis_opens x).prod_self.mem_iff, and.assoc, and.left_comm] using hx
/-- The first projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_fst : is_open_map (@prod.fst α β) :=
begin
rw is_open_map_iff_nhds_le,
rintro ⟨x, y⟩ s hs,
rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset htx (λ x hx, ht x y ⟨hx, mem_of_nhds hty⟩)
end
/-- The second projection in a product of topological spaces sends open sets to open sets. -/
lemma is_open_map_snd : is_open_map (@prod.snd α β) :=
begin
/- This lemma could be proved by composing the fact that the first projection is open, and
exchanging coordinates is a homeomorphism, hence open. As the `prod_comm` homeomorphism is defined
later, we rather go for the direct proof, copy-pasting the proof for the first projection. -/
rw is_open_map_iff_nhds_le,
rintro ⟨x, y⟩ s hs,
rcases mem_nhds_prod_iff.1 hs with ⟨tx, htx, ty, hty, ht⟩,
simp only [subset_def, prod.forall, mem_prod] at ht,
exact mem_sets_of_superset hty (λ y hy, ht x y ⟨mem_of_nhds htx, hy⟩)
end
/-- A product set is open in a product space if and only if each factor is open, or one of them is
empty -/
lemma is_open_prod_iff' {s : set α} {t : set β} :
is_open (set.prod s t) ↔ (is_open s ∧ is_open t) ∨ (s = ∅) ∨ (t = ∅) :=
begin
cases (set.prod s t).eq_empty_or_nonempty with h h,
{ simp [h, prod_eq_empty_iff.1 h] },
{ have st : s.nonempty ∧ t.nonempty, from prod_nonempty_iff.1 h,
split,
{ assume H : is_open (set.prod s t),
refine or.inl ⟨_, _⟩,
show is_open s,
{ rw ← fst_image_prod s st.2,
exact is_open_map_fst _ H },
show is_open t,
{ rw ← snd_image_prod st.1 t,
exact is_open_map_snd _ H } },
{ assume H,
simp only [st.1.ne_empty, st.2.ne_empty, not_false_iff, or_false] at H,
exact H.1.prod H.2 } }
end
lemma closure_prod_eq {s : set α} {t : set β} :
closure (set.prod s t) = set.prod (closure s) (closure t) :=
set.ext $ assume ⟨a, b⟩,
have (𝓝 a ×ᶠ 𝓝 b) ⊓ 𝓟 (set.prod s t) = (𝓝 a ⊓ 𝓟 s) ×ᶠ (𝓝 b ⊓ 𝓟 t),
by rw [←prod_inf_prod, prod_principal_principal],
by simp [closure_eq_cluster_pts, cluster_pt, nhds_prod_eq, this]; exact prod_ne_bot
lemma map_mem_closure2 {s : set α} {t : set β} {u : set γ} {f : α → β → γ} {a : α} {b : β}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(hu : ∀a b, a ∈ s → b ∈ t → f a b ∈ u) :
f a b ∈ closure u :=
have (a, b) ∈ closure (set.prod s t), by rw [closure_prod_eq]; from ⟨ha, hb⟩,
show (λp:α×β, f p.1 p.2) (a, b) ∈ closure u, from
map_mem_closure hf this $ assume ⟨a, b⟩ ⟨ha, hb⟩, hu a b ha hb
lemma is_closed.prod {s₁ : set α} {s₂ : set β} (h₁ : is_closed s₁) (h₂ : is_closed s₂) :
is_closed (set.prod s₁ s₂) :=
closure_eq_iff_is_closed.mp $ by simp only [h₁.closure_eq, h₂.closure_eq, closure_prod_eq]
/-- The product of two dense sets is a dense set. -/
lemma dense.prod {s : set α} {t : set β} (hs : dense s) (ht : dense t) :
dense (s.prod t) :=
λ x, by { rw closure_prod_eq, exact ⟨hs x.1, ht x.2⟩ }
/-- If `f` and `g` are maps with dense range, then `prod.map f g` has dense range. -/
lemma dense_range.prod_map {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ}
(hf : dense_range f) (hg : dense_range g) : dense_range (prod.map f g) :=
by simpa only [dense_range, prod_range_range_eq] using hf.prod hg
lemma inducing.prod_mk {f : α → β} {g : γ → δ} (hf : inducing f) (hg : inducing g) :
inducing (λx:α×γ, (f x.1, g x.2)) :=
⟨by rw [prod.topological_space, prod.topological_space, hf.induced, hg.induced,
induced_compose, induced_compose, induced_inf, induced_compose, induced_compose]⟩
lemma embedding.prod_mk {f : α → β} {g : γ → δ} (hf : embedding f) (hg : embedding g) :
embedding (λx:α×γ, (f x.1, g x.2)) :=
{ inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨hf.inj h₁, hg.inj h₂⟩,
..hf.to_inducing.prod_mk hg.to_inducing }
protected lemma is_open_map.prod {f : α → β} {g : γ → δ} (hf : is_open_map f) (hg : is_open_map g) :
is_open_map (λ p : α × γ, (f p.1, g p.2)) :=
begin
rw [is_open_map_iff_nhds_le],
rintros ⟨a, b⟩,
rw [nhds_prod_eq, nhds_prod_eq, ← filter.prod_map_map_eq],
exact filter.prod_mono (is_open_map_iff_nhds_le.1 hf a) (is_open_map_iff_nhds_le.1 hg b)
end
protected lemma open_embedding.prod {f : α → β} {g : γ → δ}
(hf : open_embedding f) (hg : open_embedding g) : open_embedding (λx:α×γ, (f x.1, g x.2)) :=
open_embedding_of_embedding_open (hf.1.prod_mk hg.1)
(hf.is_open_map.prod hg.is_open_map)
lemma embedding_graph {f : α → β} (hf : continuous f) : embedding (λx, (x, f x)) :=
embedding_of_embedding_compose (continuous_id.prod_mk hf) continuous_fst embedding_id
end prod
section sum
open sum
variables [topological_space α] [topological_space β] [topological_space γ]
@[continuity] lemma continuous_inl : continuous (@inl α β) :=
continuous_sup_rng_left continuous_coinduced_rng
@[continuity] lemma continuous_inr : continuous (@inr α β) :=
continuous_sup_rng_right continuous_coinduced_rng
@[continuity] lemma continuous_sum_rec {f : α → γ} {g : β → γ}
(hf : continuous f) (hg : continuous g) : @continuous (α ⊕ β) γ _ _ (@sum.rec α β (λ_, γ) f g) :=
begin
apply continuous_sup_dom;
rw continuous_def at hf hg ⊢;
assumption
end
lemma is_open_sum_iff {s : set (α ⊕ β)} :
is_open s ↔ is_open (inl ⁻¹' s) ∧ is_open (inr ⁻¹' s) :=
iff.rfl
lemma is_open_map_sum {f : α ⊕ β → γ}
(h₁ : is_open_map (λ a, f (inl a))) (h₂ : is_open_map (λ b, f (inr b))) :
is_open_map f :=
begin
intros u hu,
rw is_open_sum_iff at hu,
cases hu with hu₁ hu₂,
have : u = inl '' (inl ⁻¹' u) ∪ inr '' (inr ⁻¹' u),
{ ext (_|_); simp },
rw [this, set.image_union, set.image_image, set.image_image],
exact is_open_union (h₁ _ hu₁) (h₂ _ hu₂)
end
lemma embedding_inl : embedding (@inl α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_left },
{ intros u hu, existsi (inl '' u),
change
(is_open (inl ⁻¹' (@inl α β '' u)) ∧
is_open (inr ⁻¹' (@inl α β '' u))) ∧
inl ⁻¹' (inl '' u) = u,
have : inl ⁻¹' (@inl α β '' u) = u :=
preimage_image_eq u (λ _ _, inl.inj_iff.mp), rw this,
have : inr ⁻¹' (@inl α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume a ⟨b, _, h⟩, inl_ne_inr h), rw this,
exact ⟨⟨hu, is_open_empty⟩, rfl⟩ }
end,
inj := λ _ _, inl.inj_iff.mp }
lemma embedding_inr : embedding (@inr α β) :=
{ induced := begin
unfold sum.topological_space,
apply le_antisymm,
{ rw ← coinduced_le_iff_le_induced, exact le_sup_right },
{ intros u hu, existsi (inr '' u),
change
(is_open (inl ⁻¹' (@inr α β '' u)) ∧
is_open (inr ⁻¹' (@inr α β '' u))) ∧
inr ⁻¹' (inr '' u) = u,
have : inl ⁻¹' (@inr α β '' u) = ∅ :=
eq_empty_iff_forall_not_mem.mpr (assume b ⟨a, _, h⟩, inr_ne_inl h), rw this,
have : inr ⁻¹' (@inr α β '' u) = u :=
preimage_image_eq u (λ _ _, inr.inj_iff.mp), rw this,
exact ⟨⟨is_open_empty, hu⟩, rfl⟩ }
end,
inj := λ _ _, inr.inj_iff.mp }
lemma open_embedding_inl : open_embedding (inl : α → α ⊕ β) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_univ is_open_empty;
{ ext, simp }
end,
.. embedding_inl }
lemma open_embedding_inr : open_embedding (inr : β → α ⊕ β) :=
{ open_range := begin
rw is_open_sum_iff,
convert and.intro is_open_empty is_open_univ;
{ ext, simp }
end,
.. embedding_inr }
end sum
section subtype
variables [topological_space α] [topological_space β] [topological_space γ] {p : α → Prop}
lemma embedding_subtype_coe : embedding (coe : subtype p → α) :=
⟨⟨rfl⟩, subtype.coe_injective⟩
@[continuity] lemma continuous_subtype_val : continuous (@subtype.val α p) :=
continuous_induced_dom
lemma continuous_subtype_coe : continuous (coe : subtype p → α) :=
continuous_subtype_val
lemma is_open.open_embedding_subtype_coe {s : set α} (hs : is_open s) :
open_embedding (coe : s → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
open_range := (subtype.range_coe : range coe = s).symm ▸ hs }
lemma is_open.is_open_map_subtype_coe {s : set α} (hs : is_open s) :
is_open_map (coe : s → α) :=
hs.open_embedding_subtype_coe.is_open_map
lemma is_open_map.restrict {f : α → β} (hf : is_open_map f) {s : set α} (hs : is_open s) :
is_open_map (s.restrict f) :=
hf.comp hs.is_open_map_subtype_coe
lemma is_closed.closed_embedding_subtype_coe {s : set α} (hs : is_closed s) :
closed_embedding (coe : {x // x ∈ s} → α) :=
{ induced := rfl,
inj := subtype.coe_injective,
closed_range := (subtype.range_coe : range coe = s).symm ▸ hs }
@[continuity] lemma continuous_subtype_mk {f : β → α}
(hp : ∀x, p (f x)) (h : continuous f) : continuous (λx, (⟨f x, hp x⟩ : subtype p)) :=
continuous_induced_rng h
lemma continuous_inclusion {s t : set α} (h : s ⊆ t) : continuous (inclusion h) :=
continuous_subtype_mk _ continuous_subtype_coe
lemma continuous_at_subtype_coe {p : α → Prop} {a : subtype p} :
continuous_at (coe : subtype p → α) a :=
continuous_iff_continuous_at.mp continuous_subtype_coe _
lemma map_nhds_subtype_coe_eq {a : α} (ha : p a) (h : {a | p a} ∈ 𝓝 a) :
map (coe : subtype p → α) (𝓝 ⟨a, ha⟩) = 𝓝 a :=
map_nhds_induced_eq $ by simpa only [subtype.coe_mk, subtype.range_coe] using h
lemma nhds_subtype_eq_comap {a : α} {h : p a} :
𝓝 (⟨a, h⟩ : subtype p) = comap coe (𝓝 a) :=
nhds_induced _ _
lemma tendsto_subtype_rng {β : Type*} {p : α → Prop} {b : filter β} {f : β → subtype p} :
∀{a:subtype p}, tendsto f b (𝓝 a) ↔ tendsto (λx, (f x : α)) b (𝓝 (a : α))
| ⟨a, ha⟩ := by rw [nhds_subtype_eq_comap, tendsto_comap_iff, subtype.coe_mk]
lemma continuous_subtype_nhds_cover {ι : Sort*} {f : α → β} {c : ι → α → Prop}
(c_cover : ∀x:α, ∃i, {x | c i x} ∈ 𝓝 x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_continuous_at.mpr $ assume x,
let ⟨i, (c_sets : {x | c i x} ∈ 𝓝 x)⟩ := c_cover x in
let x' : subtype (c i) := ⟨x, mem_of_nhds c_sets⟩ in
calc map f (𝓝 x) = map f (map coe (𝓝 x')) :
congr_arg (map f) (map_nhds_subtype_coe_eq _ $ c_sets).symm
... = map (λx:subtype (c i), f x) (𝓝 x') : rfl
... ≤ 𝓝 (f x) : continuous_iff_continuous_at.mp (f_cont i) x'
lemma continuous_subtype_is_closed_cover {ι : Sort*} {f : α → β} (c : ι → α → Prop)
(h_lf : locally_finite (λi, {x | c i x}))
(h_is_closed : ∀i, is_closed {x | c i x})
(h_cover : ∀x, ∃i, c i x)
(f_cont : ∀i, continuous (λ(x : subtype (c i)), f x)) :
continuous f :=
continuous_iff_is_closed.mpr $
assume s hs,
have ∀i, is_closed ((coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from assume i,
embedding_is_closed embedding_subtype_coe
(by simp [subtype.range_coe]; exact h_is_closed i)
(continuous_iff_is_closed.mp (f_cont i) _ hs),
have is_closed (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
from is_closed_Union_of_locally_finite
(locally_finite_subset h_lf $ assume i x ⟨⟨x', hx'⟩, _, heq⟩, heq ▸ hx')
this,
have f ⁻¹' s = (⋃i, (coe : {x | c i x} → α) '' (f ∘ coe ⁻¹' s)),
begin
apply set.ext,
have : ∀ (x : α), f x ∈ s ↔ ∃ (i : ι), c i x ∧ f x ∈ s :=
λ x, ⟨λ hx, let ⟨i, hi⟩ := h_cover x in ⟨i, hi, hx⟩,
λ ⟨i, hi, hx⟩, hx⟩,
simpa [and.comm, @and.left_comm (c _ _), ← exists_and_distrib_right],
end,
by rwa [this]
lemma closure_subtype {x : {a // p a}} {s : set {a // p a}}:
x ∈ closure s ↔ (x : α) ∈ closure ((coe : _ → α) '' s) :=
closure_induced $ assume x y, subtype.eq
end subtype
section quotient
variables [topological_space α] [topological_space β] [topological_space γ]
variables {r : α → α → Prop} {s : setoid α}
lemma quotient_map_quot_mk : quotient_map (@quot.mk α r) :=
⟨quot.exists_rep, rfl⟩
@[continuity] lemma continuous_quot_mk : continuous (@quot.mk α r) :=
continuous_coinduced_rng
@[continuity] lemma continuous_quot_lift {f : α → β} (hr : ∀ a b, r a b → f a = f b)
(h : continuous f) : continuous (quot.lift f hr : quot r → β) :=
continuous_coinduced_dom h
lemma quotient_map_quotient_mk : quotient_map (@quotient.mk α s) :=
quotient_map_quot_mk
lemma continuous_quotient_mk : continuous (@quotient.mk α s) :=
continuous_coinduced_rng
lemma continuous_quotient_lift {f : α → β} (hs : ∀ a b, a ≈ b → f a = f b)
(h : continuous f) : continuous (quotient.lift f hs : quotient s → β) :=
continuous_coinduced_dom h
end quotient
section pi
variables {ι : Type*} {π : ι → Type*}
@[continuity]
lemma continuous_pi [topological_space α] [∀i, topological_space (π i)] {f : α → Πi:ι, π i}
(h : ∀i, continuous (λa, f a i)) : continuous f :=
continuous_infi_rng $ assume i, continuous_induced_rng $ h i
@[continuity]
lemma continuous_apply [∀i, topological_space (π i)] (i : ι) :
continuous (λp:Πi, π i, p i) :=
continuous_infi_dom continuous_induced_dom
/-- Embedding a factor into a product space (by fixing arbitrarily all the other coordinates) is
continuous. -/
@[continuity]
lemma continuous_update [decidable_eq ι] [∀i, topological_space (π i)] {i : ι} {f : Πi:ι, π i} :
continuous (λ x : π i, function.update f i x) :=
begin
refine continuous_pi (λj, _),
by_cases h : j = i,
{ rw h,
simpa using continuous_id },
{ simpa [h] using continuous_const }
end
lemma nhds_pi [t : ∀i, topological_space (π i)] {a : Πi, π i} :
𝓝 a = (⨅i, comap (λx, x i) (𝓝 (a i))) :=
calc 𝓝 a = (⨅i, @nhds _ (@topological_space.induced _ _ (λx:Πi, π i, x i) (t i)) a) : nhds_infi
... = (⨅i, comap (λx, x i) (𝓝 (a i))) : by simp [nhds_induced]
lemma tendsto_pi [t : ∀i, topological_space (π i)] {f : α → Πi, π i} {g : Πi, π i} {u : filter α} :
tendsto f u (𝓝 g) ↔ ∀ x, tendsto (λ i, f i x) u (𝓝 (g x)) :=
by simp [nhds_pi, filter.tendsto_comap_iff]
lemma is_open_set_pi [∀a, topological_space (π a)] {i : set ι} {s : Πa, set (π a)}
(hi : finite i) (hs : ∀a∈i, is_open (s a)) : is_open (pi i s) :=
by rw [pi_def]; exact (is_open_bInter hi $ assume a ha, (hs _ ha).preimage (continuous_apply _))
lemma set_pi_mem_nhds [Π a, topological_space (π a)] {i : set ι} {s : Π a, set (π a)}
{x : Π a, π a} (hi : finite i) (hs : ∀ a ∈ i, s a ∈ 𝓝 (x a)) :
pi i s ∈ 𝓝 x :=
by { rw [pi_def], exact Inter_mem_sets hi (λ a ha, (continuous_apply a).continuous_at (hs a ha)) }
lemma pi_eq_generate_from [∀a, topological_space (π a)] :
Pi.topological_space =
generate_from {g | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, is_open (s a)) ∧ g = pi ↑i s} :=
le_antisymm
(le_generate_from $ assume g ⟨s, i, hi, eq⟩, eq.symm ▸ is_open_set_pi (finset.finite_to_set _) hi)
(le_infi $ assume a s ⟨t, ht, s_eq⟩, generate_open.basic _ $
⟨function.update (λa, univ) a t, {a}, by simpa using ht, by ext f; simp [s_eq.symm, pi]⟩)
lemma pi_generate_from_eq {g : Πa, set (set (π a))} :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} :=
let G := {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ g a) ∧ t = pi ↑i s} in
begin
rw [pi_eq_generate_from],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, i, ht, eq⟩, ⟨t, i, assume a ha, generate_open.basic _ (ht a ha), eq⟩,
{ rintros s ⟨t, i, hi, rfl⟩,
rw [pi_def],
apply is_open_bInter (finset.finite_to_set _),
assume a ha, show ((generate_from G).coinduced (λf:Πa, π a, f a)).is_open (t a),
refine le_generate_from _ _ (hi a ha),
exact assume s hs, generate_open.basic _ ⟨function.update (λa, univ) a s, {a}, by simp [hs]⟩ }
end
lemma pi_generate_from_eq_fintype {g : Πa, set (set (π a))} [fintype ι] (hg : ∀a, ⋃₀ g a = univ) :
@Pi.topological_space ι π (λa, generate_from (g a)) =
generate_from {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} :=
let G := {t | ∃(s:Πa, set (π a)), (∀a, s a ∈ g a) ∧ t = pi univ s} in
begin
rw [pi_generate_from_eq],
refine le_antisymm (generate_from_mono _) (le_generate_from _),
exact assume s ⟨t, ht, eq⟩, ⟨t, finset.univ, by simp [ht, eq]⟩,
{ rintros s ⟨t, i, ht, rfl⟩,
apply is_open_iff_forall_mem_open.2 _,
assume f hf,
choose c hc using show ∀a, ∃s, s ∈ g a ∧ f a ∈ s,
{ assume a, have : f a ∈ ⋃₀ g a, { rw [hg], apply mem_univ }, simpa },
refine ⟨pi univ (λa, if a ∈ i then t a else (c : Πa, set (π a)) a), _, _, _⟩,
{ simp [pi_if] },
{ refine generate_open.basic _ ⟨_, assume a, _, rfl⟩,
by_cases a ∈ i; simp [*, pi] at * },
{ have : f ∈ pi {a | a ∉ i} c, { simp [*, pi] at * },
simpa [pi_if, hf] } }
end
end pi
section sigma
variables {ι : Type*} {σ : ι → Type*} [Π i, topological_space (σ i)]
@[continuity]
lemma continuous_sigma_mk {i : ι} : continuous (@sigma.mk ι σ i) :=
continuous_supr_rng continuous_coinduced_rng
lemma is_open_sigma_iff {s : set (sigma σ)} : is_open s ↔ ∀ i, is_open (sigma.mk i ⁻¹' s) :=
by simp only [is_open_supr_iff, is_open_coinduced]
lemma is_closed_sigma_iff {s : set (sigma σ)} : is_closed s ↔ ∀ i, is_closed (sigma.mk i ⁻¹' s) :=
is_open_sigma_iff
lemma is_open_map_sigma_mk {i : ι} : is_open_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_open_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_open_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_open_range_sigma_mk {i : ι} : is_open (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_open_map_sigma_mk _ is_open_univ }
lemma is_closed_map_sigma_mk {i : ι} : is_closed_map (@sigma.mk ι σ i) :=
begin
intros s hs,
rw is_closed_sigma_iff,
intro j,
classical,
by_cases h : i = j,
{ subst j,
convert hs,
exact set.preimage_image_eq _ sigma_mk_injective },
{ convert is_closed_empty,
apply set.eq_empty_of_subset_empty,
rintro x ⟨y, _, hy⟩,
have : i = j, by cc,
contradiction }
end
lemma is_closed_sigma_mk {i : ι} : is_closed (set.range (@sigma.mk ι σ i)) :=
by { rw ←set.image_univ, exact is_closed_map_sigma_mk _ is_closed_univ }
lemma open_embedding_sigma_mk {i : ι} : open_embedding (@sigma.mk ι σ i) :=
open_embedding_of_continuous_injective_open
continuous_sigma_mk sigma_mk_injective is_open_map_sigma_mk
lemma closed_embedding_sigma_mk {i : ι} : closed_embedding (@sigma.mk ι σ i) :=
closed_embedding_of_continuous_injective_closed
continuous_sigma_mk sigma_mk_injective is_closed_map_sigma_mk
lemma embedding_sigma_mk {i : ι} : embedding (@sigma.mk ι σ i) :=
closed_embedding_sigma_mk.1
/-- A map out of a sum type is continuous if its restriction to each summand is. -/
@[continuity]
lemma continuous_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, continuous (λ a, f ⟨i, a⟩)) : continuous f :=
continuous_supr_dom (λ i, continuous_coinduced_dom (h i))
@[continuity]
lemma continuous_sigma_map {κ : Type*} {τ : κ → Type*} [Π k, topological_space (τ k)]
{f₁ : ι → κ} {f₂ : Π i, σ i → τ (f₁ i)} (hf : ∀ i, continuous (f₂ i)) :
continuous (sigma.map f₁ f₂) :=
continuous_sigma $ λ i,
show continuous (λ a, sigma.mk (f₁ i) (f₂ i a)),
from continuous_sigma_mk.comp (hf i)
lemma is_open_map_sigma [topological_space β] {f : sigma σ → β}
(h : ∀ i, is_open_map (λ a, f ⟨i, a⟩)) : is_open_map f :=
begin
intros s hs,
rw is_open_sigma_iff at hs,
have : s = ⋃ i, sigma.mk i '' (sigma.mk i ⁻¹' s),
{ rw Union_image_preimage_sigma_mk_eq_self },
rw this,
rw [image_Union],
apply is_open_Union,
intro i,
rw [image_image],
exact h i _ (hs i)
end
/-- The sum of embeddings is an embedding. -/
lemma embedding_sigma_map {τ : ι → Type*} [Π i, topological_space (τ i)]
{f : Π i, σ i → τ i} (hf : ∀ i, embedding (f i)) : embedding (sigma.map id f) :=
begin
refine ⟨⟨_⟩, function.injective_id.sigma_map (λ i, (hf i).inj)⟩,
refine le_antisymm
(continuous_iff_le_induced.mp (continuous_sigma_map (λ i, (hf i).continuous))) _,
intros s hs,
replace hs := is_open_sigma_iff.mp hs,
have : ∀ i, ∃ t, is_open t ∧ f i ⁻¹' t = sigma.mk i ⁻¹' s,
{ intro i,
apply is_open_induced_iff.mp,
convert hs i,
exact (hf i).induced.symm },
choose t ht using this,
apply is_open_induced_iff.mpr,
refine ⟨⋃ i, sigma.mk i '' t i, is_open_Union (λ i, is_open_map_sigma_mk _ (ht i).1), _⟩,
ext ⟨i, x⟩,
change (sigma.mk i (f i x) ∈ ⋃ (i : ι), sigma.mk i '' t i) ↔ x ∈ sigma.mk i ⁻¹' s,
rw [←(ht i).2, mem_Union],
split,
{ rintro ⟨j, hj⟩,
rw mem_image at hj,
rcases hj with ⟨y, hy₁, hy₂⟩,
rcases sigma.mk.inj_iff.mp hy₂ with ⟨rfl, hy⟩,
replace hy := eq_of_heq hy,
subst y,
exact hy₁ },
{ intro hx,
use i,
rw mem_image,
exact ⟨f i x, hx, rfl⟩ }
end
end sigma
section ulift
@[continuity] lemma continuous_ulift_down [topological_space α] :
continuous (ulift.down : ulift.{v u} α → α) :=
continuous_induced_dom
@[continuity] lemma continuous_ulift_up [topological_space α] :
continuous (ulift.up : α → ulift.{v u} α) :=
continuous_induced_rng continuous_id
end ulift
lemma mem_closure_of_continuous [topological_space α] [topological_space β]
{f : α → β} {a : α} {s : set α} {t : set β}
(hf : continuous f) (ha : a ∈ closure s) (h : maps_to f s (closure t)) :
f a ∈ closure t :=
calc f a ∈ f '' closure s : mem_image_of_mem _ ha
... ⊆ closure (f '' s) : image_closure_subset_closure_image hf
... ⊆ closure t : closure_minimal h.image_subset is_closed_closure
lemma mem_closure_of_continuous2 [topological_space α] [topological_space β] [topological_space γ]
{f : α → β → γ} {a : α} {b : β} {s : set α} {t : set β} {u : set γ}
(hf : continuous (λp:α×β, f p.1 p.2)) (ha : a ∈ closure s) (hb : b ∈ closure t)
(h : ∀a∈s, ∀b∈t, f a b ∈ closure u) :
f a b ∈ closure u :=
have (a,b) ∈ closure (set.prod s t),
by simp [closure_prod_eq, ha, hb],
show f (a, b).1 (a, b).2 ∈ closure u,
from @mem_closure_of_continuous (α×β) _ _ _ (λp:α×β, f p.1 p.2) (a,b) _ u hf this $
assume ⟨p₁, p₂⟩ ⟨h₁, h₂⟩, h p₁ h₁ p₂ h₂
|
c3cce874e9d35ace9a274b5c1817646ed5441aa2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/convex/segment.lean | 6e0d57aed67d8a87cd5739afd0d06a732707b20f | [
"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 | 24,492 | 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 Kudryashov, Yaël Dillies
-/
import algebra.order.invertible
import algebra.order.smul
import linear_algebra.affine_space.midpoint
import linear_algebra.ray
import tactic.positivity
/-!
# Segments in vector spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
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`.
## 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 G ι : Type*} {π : ι → Type*}
open function set
open_locale pointwise
section ordered_semiring
variables [ordered_semiring 𝕜] [add_comm_monoid E]
section has_smul
variables (𝕜) [has_smul 𝕜 E] {s : set E} {x y : 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 (name := segment) `[` 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] ⊆ 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 :
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] {s : set E} {x y z : 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 _ $ λ ha', _),
{ rintro rfl,
rw [← add_zero a, hab, one_smul, zero_smul, add_zero] },
{ rintro rfl,
rw [← zero_add b, hab, one_smul, zero_smul, zero_add] },
{ exact ⟨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 𝕜] [add_comm_group E] [add_comm_group F] [add_comm_group G] [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 _ _ _ }
@[simp] lemma image_segment (f : E →ᵃ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] :=
set.ext $ λ x, by simp_rw [segment_eq_image_line_map, mem_image, exists_exists_and_eq_and,
affine_map.apply_line_map]
@[simp] lemma image_open_segment (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_line_map, mem_image, exists_exists_and_eq_and,
affine_map.apply_line_map]
@[simp] lemma vadd_segment [add_torsor G E] [vadd_comm_class G E E] (a : G) (b c : E) :
a +ᵥ [b -[𝕜] c] = [a +ᵥ b -[𝕜] a +ᵥ c] :=
image_segment 𝕜 ⟨_, linear_map.id, λ _ _, vadd_comm _ _ _⟩ b c
@[simp] lemma vadd_open_segment [add_torsor G E] [vadd_comm_class G E E] (a : G) (b c : E) :
a +ᵥ open_segment 𝕜 b c = open_segment 𝕜 (a +ᵥ b) (a +ᵥ c) :=
image_open_segment 𝕜 ⟨_, linear_map.id, λ _ _, vadd_comm _ _ _⟩ b c
@[simp] lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] :=
by simp_rw [←vadd_eq_add, ←vadd_segment, vadd_mem_vadd_set_iff]
@[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 :=
by simp_rw [←vadd_eq_add, ←vadd_open_segment, vadd_mem_vadd_set_iff]
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 ordered_ring
lemma same_ray_of_mem_segment [strict_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 𝕜] [add_comm_group E] [module 𝕜 E] {x y : E}
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] :=
by { convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _, rw midpoint_sub_add }
lemma mem_segment_add_sub [invertible (2 : 𝕜)] (x y : E) : x ∈ [x + y -[𝕜] x - y] :=
by { convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _, rw midpoint_add_sub }
@[simp] lemma left_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 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] :
y ∈ open_segment 𝕜 x y ↔ x = y :=
by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm]
end linear_ordered_ring
section linear_ordered_semifield
variables [linear_ordered_semifield 𝕜] [add_comm_group E] [module 𝕜 E] {x y z : E}
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 := by positivity,
refine ⟨a / (a + b), b / (a + b), by positivity, by positivity, _, rfl⟩,
rw [←add_div, div_self hab.ne'] }
end
end linear_ordered_semifield
section linear_ordered_field
variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] {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
open affine_map
/-- If `z = line_map x y c` is a point on the line passing through `x` and `y`, then the open
segment `open_segment 𝕜 x y` is included in the union of the open segments `open_segment 𝕜 x z`,
`open_segment 𝕜 z y`, and the point `z`. Informally, `(x, y) ⊆ {z} ∪ (x, z) ∪ (z, y)`. -/
lemma open_segment_subset_union (x y : E) {z : E} (hz : z ∈ range (line_map x y : 𝕜 → E)) :
open_segment 𝕜 x y ⊆ insert z (open_segment 𝕜 x z ∪ open_segment 𝕜 z y) :=
begin
rcases hz with ⟨c, rfl⟩,
simp only [open_segment_eq_image_line_map, ← maps_to'],
rintro a ⟨h₀, h₁⟩,
rcases lt_trichotomy a c with hac|rfl|hca,
{ right, left,
have hc : 0 < c, from h₀.trans hac,
refine ⟨a / c, ⟨div_pos h₀ hc, (div_lt_one hc).2 hac⟩, _⟩,
simp only [← homothety_eq_line_map, ← homothety_mul_apply, div_mul_cancel _ hc.ne'] },
{ left, refl },
{ right, right,
have hc : 0 < 1 - c, from sub_pos.2 (hca.trans h₁),
simp only [← line_map_apply_one_sub y],
refine ⟨(a - c) / (1 - c), ⟨div_pos (sub_pos.2 hca) hc,
(div_lt_one hc).2 $ sub_lt_sub_right h₁ _⟩, _⟩,
simp only [← homothety_eq_line_map, ← homothety_mul_apply, sub_mul, one_mul,
div_mul_cancel _ hc.ne', sub_sub_sub_cancel_right] }
end
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] {x y : E}
lemma segment_subset_Icc (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] {x y : E}
lemma open_segment_subset_Ioo (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] {𝕜} {a b : 𝕜}
lemma segment_subset_uIcc (x y : E) : [x -[𝕜] y] ⊆ uIcc x y :=
begin
cases le_total x y,
{ rw uIcc_of_le h,
exact segment_subset_Icc h },
{ rw [uIcc_of_ge h, segment_symm],
exact segment_subset_Icc h }
end
lemma convex.min_le_combo (x y : E) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
min x y ≤ a • x + b • y :=
(segment_subset_uIcc x y ⟨_, _, ha, hb, hab, rfl⟩).1
lemma convex.combo_le_max (x y : E) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) :
a • x + b • y ≤ max x y :=
(segment_subset_uIcc x y ⟨_, _, ha, hb, hab, rfl⟩).2
end linear_ordered_add_comm_monoid
end ordered_semiring
section linear_ordered_field
variables [linear_ordered_field 𝕜] {x y z : 𝕜}
lemma Icc_subset_segment : 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 (h : x ≤ y) : [x -[𝕜] y] = Icc x y :=
(segment_subset_Icc h).antisymm Icc_subset_segment
lemma Ioo_subset_open_segment : 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 (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' (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_uIcc (x y : 𝕜) : [x -[𝕜] y] = uIcc 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 (h : x ≤ y) :
z ∈ Icc x y ↔ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
by { rw ←segment_eq_Icc h, simp_rw [←exists_prop], refl }
/-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints.
-/
lemma convex.mem_Ioo (h : x < y) :
z ∈ Ioo x y ↔ ∃ a b, 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
by { rw ←open_segment_eq_Ioo h, simp_rw [←exists_prop], refl }
/-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the
endpoints. -/
lemma convex.mem_Ioc (h : x < y) :
z ∈ Ioc x y ↔ ∃ a b, 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
refine ⟨λ 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 (h : x < y) :
z ∈ Ico x y ↔ ∃ a b, 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z :=
begin
refine ⟨λ 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
namespace prod
variables [ordered_semiring 𝕜] [add_comm_monoid E] [add_comm_monoid F] [module 𝕜 E] [module 𝕜 F]
lemma segment_subset (x y : E × F) : segment 𝕜 x y ⊆ segment 𝕜 x.1 y.1 ×ˢ segment 𝕜 x.2 y.2 :=
begin
rintro z ⟨a, b, ha, hb, hab, hz⟩,
exact ⟨⟨a, b, ha, hb, hab, congr_arg prod.fst hz⟩, a, b, ha, hb, hab, congr_arg prod.snd hz⟩,
end
lemma open_segment_subset (x y : E × F) :
open_segment 𝕜 x y ⊆ open_segment 𝕜 x.1 y.1 ×ˢ open_segment 𝕜 x.2 y.2 :=
begin
rintro z ⟨a, b, ha, hb, hab, hz⟩,
exact ⟨⟨a, b, ha, hb, hab, congr_arg prod.fst hz⟩, a, b, ha, hb, hab, congr_arg prod.snd hz⟩,
end
lemma image_mk_segment_left (x₁ x₂ : E) (y : F) :
(λ x, (x, y)) '' [x₁ -[𝕜] x₂] = [(x₁, y) -[𝕜] (x₂, y)] :=
begin
ext ⟨x', y'⟩,
simp_rw [set.mem_image, segment, set.mem_set_of, prod.smul_mk, prod.mk_add_mk,
prod.mk.inj_iff, ←exists_and_distrib_right, @exists_comm E, exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
lemma image_mk_segment_right (x : E) (y₁ y₂ : F) :
(λ y, (x, y)) '' [y₁ -[𝕜] y₂] = [(x, y₁) -[𝕜] (x, y₂)] :=
begin
ext ⟨x', y'⟩,
simp_rw [set.mem_image, segment, set.mem_set_of, prod.smul_mk, prod.mk_add_mk,
prod.mk.inj_iff, ←exists_and_distrib_right, @exists_comm F, exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
lemma image_mk_open_segment_left (x₁ x₂ : E) (y : F) :
(λ x, (x, y)) '' open_segment 𝕜 x₁ x₂ = open_segment 𝕜 (x₁, y) (x₂, y) :=
begin
ext ⟨x', y'⟩,
simp_rw [set.mem_image, open_segment, set.mem_set_of, prod.smul_mk, prod.mk_add_mk,
prod.mk.inj_iff, ←exists_and_distrib_right, @exists_comm E, exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
@[simp] lemma image_mk_open_segment_right (x : E) (y₁ y₂ : F) :
(λ y, (x, y)) '' open_segment 𝕜 y₁ y₂ = open_segment 𝕜 (x, y₁) (x, y₂) :=
begin
ext ⟨x', y'⟩,
simp_rw [set.mem_image, open_segment, set.mem_set_of, prod.smul_mk, prod.mk_add_mk,
prod.mk.inj_iff, ←exists_and_distrib_right, @exists_comm F, exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
end prod
namespace pi
variables [ordered_semiring 𝕜] [Π i, add_comm_monoid (π i)] [Π i, module 𝕜 (π i)] {s : set ι}
lemma segment_subset (x y : Π i, π i) : segment 𝕜 x y ⊆ s.pi (λ i, segment 𝕜 (x i) (y i)) :=
by { rintro z ⟨a, b, ha, hb, hab, hz⟩ i -, exact ⟨a, b, ha, hb, hab, congr_fun hz i⟩ }
lemma open_segment_subset (x y : Π i, π i) :
open_segment 𝕜 x y ⊆ s.pi (λ i, open_segment 𝕜 (x i) (y i)) :=
by { rintro z ⟨a, b, ha, hb, hab, hz⟩ i -, exact ⟨a, b, ha, hb, hab, congr_fun hz i⟩ }
variables [decidable_eq ι]
lemma image_update_segment (i : ι) (x₁ x₂ : π i) (y : Π i, π i) :
update y i '' [x₁ -[𝕜] x₂] = [update y i x₁ -[𝕜] update y i x₂] :=
begin
ext z,
simp_rw [set.mem_image, segment, set.mem_set_of, ←update_smul, ←update_add, update_eq_iff,
←exists_and_distrib_right, @exists_comm (π i), exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
lemma image_update_open_segment (i : ι) (x₁ x₂ : π i) (y : Π i, π i) :
update y i '' open_segment 𝕜 x₁ x₂ = open_segment 𝕜 (update y i x₁) (update y i x₂) :=
begin
ext z,
simp_rw [set.mem_image, open_segment, set.mem_set_of, ←update_smul, ←update_add, update_eq_iff,
←exists_and_distrib_right, @exists_comm (π i), exists_eq_left'],
refine exists₅_congr (λ a b ha hb hab, _),
rw convex.combo_self hab,
end
end pi
|
6d90855e8926c1b110e4b3cde676030d1e5fc97d | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/computability/NFA_auto.lean | 38698e79b894822c0f485ce45005040933cda836 | [] | 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 | 3,803 | lean | /-
Copyright (c) 2020 Fox Thomson. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Fox Thomson
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.fintype.basic
import Mathlib.computability.DFA
import Mathlib.PostPort
universes u v l
namespace Mathlib
/-!
# Nondeterministic Finite Automata
This file contains the definition of a Nondeterministic Finite Automaton (NFA), a state machine
which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular
set by evaluating the string over every possible path.
We show that DFA's are equivalent to NFA's however the construction from NFA to DFA uses an
exponential number of states.
Note that this definition allows for Automaton with infinite states, a `fintype` instance must be
supplied for true NFA's.
-/
/-- An NFA is a set of states (`σ`), a transition function from state to state labelled by the
alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`).
Note the transition function sends a state to a `set` of states. These are the states that it
may be sent to. -/
structure NFA (α : Type u) (σ : Type v) where
step : σ → α → set σ
start : set σ
accept : set σ
namespace NFA
protected instance inhabited {α : Type u} {σ : Type v} : Inhabited (NFA α σ) :=
{ default := mk (fun (_x : σ) (_x : α) => ∅) ∅ ∅ }
/-- `M.step_set S a` is the union of `M.step s a` for all `s ∈ S`. -/
def step_set {α : Type u} {σ : Type v} (M : NFA α σ) : set σ → α → set σ :=
fun (Ss : set σ) (a : α) =>
do
let S ← Ss
step M S a
theorem mem_step_set {α : Type u} {σ : Type v} (M : NFA α σ) (s : σ) (S : set σ) (a : α) :
s ∈ step_set M S a ↔ ∃ (t : σ), ∃ (H : t ∈ S), s ∈ step M t a :=
sorry
/-- `M.eval_from S x` computes all possible paths though `M` with input `x` starting at an element
of `S`. -/
def eval_from {α : Type u} {σ : Type v} (M : NFA α σ) (start : set σ) : List α → set σ :=
list.foldl (step_set M) start
/-- `M.eval x` computes all possible paths though `M` with input `x` starting at an element of
`M.start`. -/
def eval {α : Type u} {σ : Type v} (M : NFA α σ) : List α → set σ := eval_from M (start M)
/-- `M.accepts` is the language of `x` such that there is an accept state in `M.eval x`. -/
def accepts {α : Type u} {σ : Type v} (M : NFA α σ) : language α :=
fun (x : List α) => ∃ (S : σ), ∃ (H : S ∈ accept M), S ∈ eval M x
/-- `M.to_DFA` is an `DFA` constructed from a `NFA` `M` using the subset construction. The
states is the type of `set`s of `M.state` and the step function is `M.step_set`. -/
def to_DFA {α : Type u} {σ : Type v} (M : NFA α σ) : DFA α (set σ) :=
DFA.mk (step_set M) (start M) (set_of fun (S : set σ) => ∃ (s : σ), ∃ (H : s ∈ S), s ∈ accept M)
@[simp] theorem to_DFA_correct {α : Type u} {σ : Type v} (M : NFA α σ) :
DFA.accepts (to_DFA M) = accepts M :=
sorry
end NFA
namespace DFA
/-- `M.to_NFA` is an `NFA` constructed from a `DFA` `M` by using the same start and accept
states and a transition function which sends `s` with input `a` to the singleton `M.step s a`. -/
def to_NFA {α : Type u} {σ' : Type v} (M : DFA α σ') : NFA α σ' :=
NFA.mk (fun (s : σ') (a : α) => singleton (step M s a)) (singleton (start M)) (accept M)
@[simp] theorem to_NFA_eval_from_match {α : Type u} {σ : Type v} (M : DFA α σ) (start : σ)
(s : List α) : NFA.eval_from (to_NFA M) (singleton start) s = singleton (eval_from M start s) :=
sorry
@[simp] theorem to_NFA_correct {α : Type u} {σ : Type v} (M : DFA α σ) :
NFA.accepts (to_NFA M) = accepts M :=
sorry
end Mathlib |
59999343c3e6e466730989402160b2ed56ddac20 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/dedekind_domain/S_integer.lean | ec1944af6e824ab8a89eb19a0789b7ae0b430043 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,943 | lean | /-
Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: David Kurniadi Angdinata
-/
import ring_theory.dedekind_domain.adic_valuation
/-!
# `S`-integers and `S`-units of fraction fields of Dedekind domains
Let `K` be the field of fractions of a Dedekind domain `R`, and let `S` be a set of prime ideals in
the height one spectrum of `R`. An `S`-integer of `K` is defined to have `v`-adic valuation at most
one for all primes ideals `v` away from `S`, whereas an `S`-unit of `Kˣ` is defined to have `v`-adic
valuation exactly one for all prime ideals `v` away from `S`.
This file defines the subalgebra of `S`-integers of `K` and the subgroup of `S`-units of `Kˣ`, where
`K` can be specialised to the case of a number field or a function field separately.
## Main definitions
* `set.integer`: `S`-integers.
* `set.unit`: `S`-units.
* TODO: localised notation for `S`-integers.
## Main statements
* `set.unit_equiv_units_integer`: `S`-units are units of `S`-integers.
* TODO: proof that `S`-units is the kernel of a map to a product.
* TODO: proof that `∅`-integers is the usual ring of integers.
* TODO: finite generation of `S`-units and Dirichlet's `S`-unit theorem.
## References
* [D Marcus, *Number Fields*][marcus1977number]
* [J W S Cassels, A Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
S integer, S-integer, S unit, S-unit
-/
namespace set
noncomputable theory
open is_dedekind_domain
open_locale non_zero_divisors
universes u v
variables {R : Type u} [comm_ring R] [is_domain R] [is_dedekind_domain R]
(S : set $ height_one_spectrum R) (K : Type v) [field K] [algebra R K] [is_fraction_ring R K]
/-! ## `S`-integers -/
/-- The `R`-subalgebra of `S`-integers of `K`. -/
@[simps] def integer : subalgebra R K :=
{ algebra_map_mem' := λ x v _, v.valuation_le_one x,
.. (⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.to_subring).copy
{x : K | ∀ v ∉ S, (v : height_one_spectrum R).valuation x ≤ 1} $ set.ext $ λ _,
by simpa only [set_like.mem_coe, subring.mem_infi] }
lemma integer_eq :
(S.integer K).to_subring
= ⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.to_subring :=
set_like.ext' $ by simpa only [integer, subring.copy_eq]
lemma integer_valuation_le_one (x : S.integer K) {v : height_one_spectrum R} (hv : v ∉ S) :
v.valuation (x : K) ≤ 1 :=
x.property v hv
/-! ## `S`-units -/
/-- The subgroup of `S`-units of `Kˣ`. -/
@[simps] def unit : subgroup Kˣ :=
(⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.unit_group).copy
{x : Kˣ | ∀ v ∉ S, (v : height_one_spectrum R).valuation (x : K) = 1} $ set.ext $ λ _,
by simpa only [set_like.mem_coe, subgroup.mem_infi, valuation.mem_unit_group_iff]
lemma unit_eq :
S.unit K = ⨅ v ∉ S, (v : height_one_spectrum R).valuation.valuation_subring.unit_group :=
subgroup.copy_eq _ _ _
lemma unit_valuation_eq_one (x : S.unit K) {v : height_one_spectrum R} (hv : v ∉ S) :
v.valuation (x : K) = 1 :=
x.property v hv
/-- The group of `S`-units is the group of units of the ring of `S`-integers. -/
@[simps] def unit_equiv_units_integer : S.unit K ≃* (S.integer K)ˣ :=
{ to_fun := λ x, ⟨⟨x, λ v hv, (x.property v hv).le⟩, ⟨↑x⁻¹, λ v hv, ((x⁻¹).property v hv).le⟩,
subtype.ext x.val.val_inv, subtype.ext x.val.inv_val⟩,
inv_fun := λ x, ⟨units.mk0 x $ λ hx, x.ne_zero ((subring.coe_eq_zero_iff _).mp hx),
λ v hv, eq_one_of_one_le_mul_left (x.val.property v hv) (x.inv.property v hv) $ eq.ge $
by { rw [← map_mul], convert v.valuation.map_one, exact subtype.mk_eq_mk.mp x.val_inv }⟩,
left_inv := λ _, by { ext, refl },
right_inv := λ _, by { ext, refl },
map_mul' := λ _ _, by { ext, refl } }
end set
|
031e0590af69ff8e9eb8c962bf485d522d90d2ba | 6df8d5ae3acf20ad0d7f0247d2cee1957ef96df1 | /Exams/cs2102-f19-exam2.lean | 63251a81055a3c8d88822b786a061ad15d5aee23 | [] | no_license | derekjohnsonva/CS2102 | 8ed45daa6658e6121bac0f6691eac6147d08246d | b3f507d4be824a2511838a1054d04fc9aef3304c | refs/heads/master | 1,648,529,162,527 | 1,578,851,859,000 | 1,578,851,859,000 | 233,433,207 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,118 | lean | /- *** I. FORMAL LANGUAGES *** -/
/-
Propositional logic is a formal language
with a syntax and a semantics. Its syntax
is simple: literal true and literal false
are expressions; variables such as P and
Q are are expressions; and if e1 and e2
are expressions, then so are ¬ e1, e1 ∧ e2,
e1 ∨ e2, e1 → e2, and so on.
The semantics of propositional logic are
equally simple. Literal true and false
expressions evaluate to Boolean true and
false values, respectively. Variable
expressions are evalauted with respect
to an interpretation function that, to
each variable, assigns a Boolean value.
Operator expressions are evaluated
recursively. For example, to evaluate
¬ e1, we evaluate e1 (recursively, with
respect to a given interpretation) to
obtain a Boolean value, then we return
the Boolean negation of that value. To
evaluate e1 ∧ e2, we evaluate e1 and
e2 with a given interpretation and then
return the Boolean conjunction (and) of
the resulting Boolean values.
Other formal languages essential for
work in computer science and discrete
mathematics, including predicate logic,
also have a formal syntax and semantics.
Another simple example is the language
of arithmetic expressions involving the
natural numbers.
Expressions in this language include
literal *numeric* values, variable
expressions, and operator expressions.
Consider, for example, the following
arithmetic expressions, written in
everyday mathematical notation:
1 -- literal 1
X -- variable expression
1 + X -- binary operator expression
x! -- unary operator expression
Your task on this question is to
formalize (by implementing in Lean)
a very simple arithmetic expression
language. Your solution can be based
(modeled) on our formalization of the
syntax and semantics of propositional
logic.
-/
/-
A. Variables
To support the formation of
*variable expressions*, and the
definition of *interpretations*
that we can use to evaluate such
expressions, define a type, var,
the values of which we will take
to represent variables.
This type should have just one
constructor. Call it mk. To provide
for an infinite supply of "variables",
define the constructor to take one
argument of type ℕ.
Hint: model your solution on the var
type we defined to specify the syntax
of propositional logic.
-/
inductive var : Type
| mk : ℕ → var
/-
Now define xVar, yVar, zVar, and
wVar, to be identifiers bound to
values of type var, with "indices"
(i values) of 0, 1, 2, and 3,
respectively.
-/
open var
def xVar := mk 0
def yVar := mk 1
def zVar := mk 2
def wVar := mk 3
/-
B. Interpretations
To support the interpretation
of variable expressions (each of
which will "contain" an object of
type var), we will apply functions
of type (var → ℕ) to var values
to "look up" their values "under
the given interpretation".
Here you are to define two such
interpretation functions. The first
will return the natural number, 0
(of type ℕ) for any var. The second
return 3 for xVar (var.mk 0), 5 for
yVar, 7 for zVar, 9 for wVar, and
zero for any other "variable" (var).
You may use whatever style of
function definition you prefer.
Call your interpretation functions
zeroInterp and otherInterp, resp.
-/
-- 1. Define zeroInterp here
def zeroInterp : var → ℕ
| _ := 0
-- 2. Define otherInterp here
def otherInterp : var → ℕ
| (var.mk 0) := 3
| (var.mk 1) := 5
| (var.mk 2) := 7
| (var.mk 3) := 9
| _ := 0
-- Hint: it's easiest to define by cases
-- Hint: put patterns in parentheses
-- etc
/- C. Expressions
Your next task is to specify the
syntax of our arithmetic language.
Do this much as we did for our
syntax for propositional logic: by
defining a type called aExpr, the
values of which are expressions in
our new expression language. Call
the type aExpr.
It should provide four constructors:
litExp, varExp, facExp, plusExp.
The litExp constructor takes a natural
number, n, as an argument and builds
a literal expression for that value.
The varExp constructor should take a
variable (of type var) as a value
and constructs a variable expression
for that var object. FacExp takes one
expression as an argument and yields
an expression that we will understand
to mean e!, that is, "e factorial".
Finally, plusExpr should take two
expressions, e1 and e2, and yield
an expression meaning e1 + e2.
-/
inductive facOp : Type
| factorial
inductive plusOp : Type
| plus
inductive aExpr : Type
| litExp : ℕ → aExpr
| varExp : var → aExpr
| facExp : aExpr → aExpr
| plusExp : aExpr → aExpr → aExpr
-- give the rest
open aExpr
/-
Concrete notation. You may use the
following notation.
-/
notation e1 + e2 := plusExp e1 e2
/-
Now define the following expressions
-/
-- literal expression for 2
def L2 : aExpr := litExp 2
-- literal expression for 4
def L4 : aExpr := litExp 4
-- variable expressions X for xVar,
-- Y for yVar, Z for zVar, W for wVar
def X : aExpr := varExp xVar
def Y : aExpr := varExp yVar
def Z : aExpr := varExp zVar
def W : aExpr := varExp wVar
-- operator plus expressions for the
-- following, using our notations
-- 2 + 4
def L2plusL4 := plusExp L2 L4
-- X + Y + Z + W + 2
def bigSum := plusExp ( plusExp((plusExp X Y) (plusExp Z W))) L2
-- Z!
def zFactorial : aExpr := facExp Z
/- E. Operational Semantics
Now define an "operational semantics"
for our language by defining a function,
aEval, that takes any expression, e, and
an interpretation, i, and reduces e to a
natural number as follows: (i) a literal
expression reduces to the natural number
it "contains"; (2) a variable expression
reduces to the value of the var object it
"contains", "under the interpretation, i";
(3) a plus expression reduces to the
natural number sum of the reduced values
of its two subexpressions (under i); and
(4) a (facExpr e) reduces to the factorial
of the value of e under i.
Before writing the aEval function, itself,
write a fac function that takes any natural
number, n, and that returns the factorial
of n. You'll need this function to finish
your aEval function.
-/
-- Your answer here
open nat
def fac : ℕ → ℕ
| zero := (succ zero)
| (succ n') := (succ n') * (fac n')
-- Write your aEval function here
def aEval : aExpr → (var → ℕ) → ℕ
| (litExp n) _ := n
| (varExp v) i := i v
| (facExp e) i := var.mk (fac e)
| (binOpExp op e1 e2) i :=
( op)
(pEval e1 i)
(pEval e2 i)
-- the rest goes here
/-
Here are some test cases you can use to
check if your aEval function and everything
else is working properly.
-/
#reduce aEval L2plusL4 zeroInterp
#reduce aEval bigSum zeroInterp
#reduce aEval zFactorial zeroInterp
#reduce aEval L2plusL4 otherInterp
#reduce aEval bigSum otherInterp
#reduce aEval zFactorial otherInterp
/- *** II. PREDICATE LOGIC *** -/
/- A. Formalizing natural language
For each of the following propositions
expressed in natural language, make it
formal by expressing it as a proposition
in predicate logic.
-/
/- 1.
There exist three natural numbers, a,
b, and c, such that a^2 + b^2 = c^2.
-/
def py : Prop :
/-
For the following problem, we assume
that Person is a type whose values
represent individual people; that
Nice is a property of people; and
that Likes is a binary relation on
people.
-/
-- Mary, Lu, and Robert are people
inductive Person : Type
| Mary
| Lu
| Robert
open Person
/- 2.
Formalize the concept that (1) Nice
is a property of people and that Mary
and Lu are nice. Hints: formalize this
property as a predicate (proposition
with one argument) on Persons, with
proofs that "Mary is Nice" and "Lu is
Nice." Give (constructor) names to
these proofs: nice_mary and nice_lu.
-/
inductive is_nice : Person → Prop
| nice_mary : is_nice Mary
| nice_lu : is_nice Lu
-- Answer
/- 3.
Formalize the concept that (1) Likes
is a binary relation on people and (2)
Mary like Robert and Robert likes Lu.
Hint: give names to proof constructors.
-/
-- Answer
/- 4.
a. Formalize the proposition that everyone
(every Person) likes someone (some Person).
-/
def everyone_likes_someone : Prop :=
_
/-
b. Formally state (don't try to prove) the
proposition that Likes is a transitive
relation (even though it's not, as defined).
-/
def likes_is_trans : Prop :=
_
/- B. Naturalizing formal language.
Translate each of the following formal
propositions into *natural* natural languages.
Don't just translate the logical symbols into
words, but say what the proposition means in
terms that would be understandable to most
anyone.
-/
def p1 := ∃ (p : Person), ∀ (q : Person), ¬ Likes p q
-- Answer (try to say it in three words): someone likes everyone
def p2 := ¬ ∃ (p : Person), ∀ (q : Person), Likes p q
-- Answer (try to say it in no more than four words): noone likes everyone
def p3 := ∀ (n : ℕ), fac n = 1 → n = 0 ∨ n = 1
-- Here fac means the factorial function.
-- Answer (hint: use if ... then ... ) if the factorial of n is one
-- then n is equal to zero or one
/- *** III. PROOFS *** -/
/- A. Proofs in natural language -/
/-
Let us define "beautiful" as a property of
natural numbers, as follows. First, the
natural number, 1, is beautiful. Second,
if any natural number, n, is beautiful,
then so is 3 * n + 1. Finally, if a natural
number, n, is beautiful, then so is n * 2.
-/
/- 1.
Give a natural language proof that 8 is
beautiful. Hint: Think backwards from 8.
Start as follows: "To show that 8 is
beautiful, our axioms (rules) imply that
it will suffice to show that ____ is a
beautiful number." Then carry on from
there.
-/
/-
Answer:
To show that 8 is
beautiful, our axioms (rules) imply that
it will suffice to show that 4 is a
beautiful number.
To show that 4 is
beautiful, our axioms (rules) imply that
it will suffice to show that 2 is a
beautiful number
To show that 2 is
beautiful, our axioms (rules) imply that
it will suffice to show that 1 is a
beautiful number
We know that 1 is a beautiful number because it is
the first axiom given. One is a beautiful number
therefore, 8 is a natural number
-/
/- 2.
Prove that 13 is beautiful.
To show that 13 is
beautiful, our axioms (rules) imply that
it will suffice to show that 4 is a
beautiful number
To show that 4 is
beautiful, our axioms (rules) imply that
it will suffice to show that 1 is a
beautiful number
We know that 1 is a beautiful number because it is
the first axiom given.
-/
/- 3.
Give a natural language proof of
the following proposition:
(1 = 0 + 1) ∧ (3^2 + 4^2 = 5^2).
Be sure to make clear what inference
(introduction and/or elimination)
rules of natural deduction, and what
other axioms (e.g., of equality), you
are using to prove it.
Using the reflexive property of equality and knowing
that any natural number plus zero will equal itself we can prove
1 = 0 + 1
Using the reflexive property of equality and the 3,4,5 right angle
property of triangles we can prove the second assertion
Since both are true, the proposition is true
-/
/- 4.
Consider the following formal definition
of binary relation on people. A pair of
"Persons", (p1, p2), is in this relation
if and only if p1 is "older than" p2.
Give a natural language proof that this
relation is transitive. As part of your
answer, state precisely what it means
for a relation to be transitive, and then
explain exactly why this relation meets this
definition.
-/
inductive Older : Person → Person → Prop
| m_older_r : Older Mary Robert
| r_older_l : Older Robert Lu
| m_older_l : Older Mary Lu
/-
Natural Language Proof:
if a relationship is transitive it means that
two existences of the relationship can be combined
to show a proof of the new relationship.
if a > b and b>c, a>c
-/
/- B. Formal Proofs -/
/-
Given formal proofs of the following
propositions in predicate logic.
-/
/-
Note: The keyword, "example", in the following
problems is just like theorem but just omits
giving give a name to a proof.
-/
example : ∀ (P Q : Prop), P → Q → (Q ∧ P) :=
begin
intros,
exact and.intro a_1 a
end
example : ∀ (P Q : Prop), P ∧ Q → P :=
begin
intros,
exact and.elim_left a,
end
example : ∀ (P Q R : Prop), (P ∧ Q) → (Q ∧ R) → (P ∧ R) :=
begin
intros P Q R pandq qandr,
have p := and.elim_left pandq,
have r := and.elim_right qandr,
exact and.intro p r,
end
example : ∀ (P Q : Prop), ((P → Q) ∧ P) → Q :=
begin
intros P Q x,
have pimpq := and.elim_left x,
apply pimpq,
apply and.elim_right x,
end
example : ∀ (P Q : Prop), (P ∧ Q) → (Q ∧ P) :=
begin
intros P Q pandq,
apply and.intro (and.elim_right pandq)(and.elim_left pandq)
end
-- Extra credit questions
example : ∀ (a b c : ℕ), a = b → b = c → a = c :=
begin
intros a b c aeqb beqc,
apply eq.subst,
apply beqc,
apply aeqb,
end
example : ∀ (P Q : Prop), (P → Q) → (¬ Q → ¬ P) :=
begin
intros P Q pimpq nq,
end |
ff92c4861dc80232329a0e1790628839debbf590 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebra/hom/iterate.lean | 63b253f5a01b21489ceb040783ffffdf70067b4e | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 6,091 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.group_power.basic
import logic.function.iterate
import group_theory.perm.basic
import group_theory.group_action.opposite
/-!
# Iterates of monoid and ring homomorphisms
Iterate of a monoid/ring homomorphism is a monoid/ring homomorphism but it has a wrong type, so Lean
can't apply lemmas like `monoid_hom.map_one` to `f^[n] 1`. Though it is possible to define
a monoid structure on the endomorphisms, quite often we do not want to convert from
`M →* M` to `monoid.End M` and from `f^[n]` to `f^n` just to apply a simple lemma.
So, we restate standard `*_hom.map_*` lemmas under names `*_hom.iterate_map_*`.
We also prove formulas for iterates of add/mul left/right.
## Tags
homomorphism, iterate
-/
open function
variables {M : Type*} {N : Type*} {G : Type*} {H : Type*}
/-- An auxiliary lemma that can be used to prove `⇑(f ^ n) = (⇑f^[n])`. -/
lemma hom_coe_pow {F : Type*} [monoid F] (c : F → M → M) (h1 : c 1 = id)
(hmul : ∀ f g, c (f * g) = c f ∘ c g) (f : F) : ∀ n, c (f ^ n) = (c f^[n])
| 0 := by { rw [pow_zero, h1], refl }
| (n + 1) := by rw [pow_succ, iterate_succ', hmul, hom_coe_pow]
namespace monoid_hom
section
variables [mul_one_class M] [mul_one_class N]
@[simp, to_additive]
theorem iterate_map_one (f : M →* M) (n : ℕ) : f^[n] 1 = 1 :=
iterate_fixed f.map_one n
@[simp, to_additive]
theorem iterate_map_mul (f : M →* M) (n : ℕ) (x y) :
f^[n] (x * y) = (f^[n] x) * (f^[n] y) :=
semiconj₂.iterate f.map_mul n x y
end
variables [monoid M] [monoid N] [group G] [group H]
@[simp, to_additive]
theorem iterate_map_inv (f : G →* G) (n : ℕ) (x) :
f^[n] (x⁻¹) = (f^[n] x)⁻¹ :=
commute.iterate_left f.map_inv n x
@[simp, to_additive]
theorem iterate_map_div (f : G →* G) (n : ℕ) (x y) :
f^[n] (x / y) = (f^[n] x) / (f^[n] y) :=
semiconj₂.iterate f.map_div n x y
theorem iterate_map_pow (f : M →* M) (n : ℕ) (a) (m : ℕ) : f^[n] (a^m) = (f^[n] a)^m :=
commute.iterate_left (λ x, f.map_pow x m) n a
theorem iterate_map_zpow (f : G →* G) (n : ℕ) (a) (m : ℤ) : f^[n] (a^m) = (f^[n] a)^m :=
commute.iterate_left (λ x, f.map_zpow x m) n a
lemma coe_pow {M} [comm_monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) :=
hom_coe_pow _ rfl (λ f g, rfl) _ _
end monoid_hom
lemma monoid.End.coe_pow {M} [monoid M] (f : monoid.End M) (n : ℕ) : ⇑(f^n) = (f^[n]) :=
hom_coe_pow _ rfl (λ f g, rfl) _ _
-- we define these manually so that we can pick a better argument order
namespace add_monoid_hom
variables [add_monoid M] [add_group G]
theorem iterate_map_smul (f : M →+ M) (n m : ℕ) (x : M) :
f^[n] (m • x) = m • (f^[n] x) :=
f.to_multiplicative.iterate_map_pow n x m
attribute [to_additive, to_additive_reorder 5] monoid_hom.iterate_map_pow
theorem iterate_map_zsmul (f : G →+ G) (n : ℕ) (m : ℤ) (x : G) :
f^[n] (m • x) = m • (f^[n] x) :=
f.to_multiplicative.iterate_map_zpow n x m
attribute [to_additive, to_additive_reorder 5] monoid_hom.iterate_map_zpow
end add_monoid_hom
lemma add_monoid.End.coe_pow {A} [add_monoid A] (f : add_monoid.End A) (n : ℕ) : ⇑(f^n) = (f^[n]) :=
hom_coe_pow _ rfl (λ f g, rfl) _ _
namespace ring_hom
section semiring
variables {R : Type*} [semiring R] (f : R →+* R) (n : ℕ) (x y : R)
lemma coe_pow (n : ℕ) : ⇑(f^n) = (f^[n]) :=
hom_coe_pow _ rfl (λ f g, rfl) f n
theorem iterate_map_one : f^[n] 1 = 1 := f.to_monoid_hom.iterate_map_one n
theorem iterate_map_zero : f^[n] 0 = 0 := f.to_add_monoid_hom.iterate_map_zero n
theorem iterate_map_add : f^[n] (x + y) = (f^[n] x) + (f^[n] y) :=
f.to_add_monoid_hom.iterate_map_add n x y
theorem iterate_map_mul : f^[n] (x * y) = (f^[n] x) * (f^[n] y) :=
f.to_monoid_hom.iterate_map_mul n x y
theorem iterate_map_pow (a) (n m : ℕ) : f^[n] (a^m) = (f^[n] a)^m :=
f.to_monoid_hom.iterate_map_pow n a m
theorem iterate_map_smul (n m : ℕ) (x : R) :
f^[n] (m • x) = m • (f^[n] x) :=
f.to_add_monoid_hom.iterate_map_smul n m x
end semiring
variables {R : Type*} [ring R] (f : R →+* R) (n : ℕ) (x y : R)
theorem iterate_map_sub : f^[n] (x - y) = (f^[n] x) - (f^[n] y) :=
f.to_add_monoid_hom.iterate_map_sub n x y
theorem iterate_map_neg : f^[n] (-x) = -(f^[n] x) :=
f.to_add_monoid_hom.iterate_map_neg n x
theorem iterate_map_zsmul (n : ℕ) (m : ℤ) (x : R) :
f^[n] (m • x) = m • (f^[n] x) :=
f.to_add_monoid_hom.iterate_map_zsmul n m x
end ring_hom
lemma equiv.perm.coe_pow {α : Type*} (f : equiv.perm α) (n : ℕ) : ⇑(f ^ n) = (f^[n]) :=
hom_coe_pow _ rfl (λ _ _, rfl) _ _
--what should be the namespace for this section?
section monoid
variables [monoid G] (a : G) (n : ℕ)
@[simp, to_additive] lemma smul_iterate [mul_action G H] :
((•) a : H → H)^[n] = (•) (a^n) :=
funext (λ b, nat.rec_on n (by rw [iterate_zero, id.def, pow_zero, one_smul])
(λ n ih, by rw [iterate_succ', comp_app, ih, pow_succ, mul_smul]))
@[simp, to_additive] lemma mul_left_iterate : ((*) a)^[n] = (*) (a^n) :=
smul_iterate a n
@[simp, to_additive] lemma mul_right_iterate : (* a)^[n] = (* a ^ n) :=
smul_iterate (mul_opposite.op a) n
@[to_additive]
lemma mul_right_iterate_apply_one : (* a)^[n] 1 = a ^ n :=
by simp [mul_right_iterate]
end monoid
section semigroup
variables [semigroup G] {a b c : G}
@[to_additive]
lemma semiconj_by.function_semiconj_mul_left (h : semiconj_by a b c) :
function.semiconj ((*)a) ((*)b) ((*)c) :=
λ j, by rw [← mul_assoc, h.eq, mul_assoc]
@[to_additive]
lemma commute.function_commute_mul_left (h : commute a b) :
function.commute ((*)a) ((*)b) :=
semiconj_by.function_semiconj_mul_left h
@[to_additive]
lemma semiconj_by.function_semiconj_mul_right_swap (h : semiconj_by a b c) :
function.semiconj (*a) (*c) (*b) :=
λ j, by simp_rw [mul_assoc, ← h.eq]
@[to_additive]
lemma commute.function_commute_mul_right (h : commute a b) :
function.commute (*a) (*b) :=
semiconj_by.function_semiconj_mul_right_swap h
end semigroup
|
0c8e4ea1ec5973e7712242cff1f3901f664d2bb7 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Inductive.lean | 9d376839853476e42d4fdc3fb208cc8fd754180c | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 25,194 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Util.ReplaceLevel
import Lean.Util.ReplaceExpr
import Lean.Util.CollectLevelParams
import Lean.Meta.Constructions
import Lean.Meta.CollectFVars
import Lean.Meta.SizeOf
import Lean.Meta.Injective
import Lean.Meta.IndPredBelow
import Lean.Elab.Command
import Lean.Elab.DefView
import Lean.Elab.DeclUtil
import Lean.Elab.Deriving.Basic
namespace Lean.Elab.Command
open Meta
builtin_initialize
registerTraceClass `Elab.inductive
def checkValidInductiveModifier [Monad m] [MonadError m] (modifiers : Modifiers) : m Unit := do
if modifiers.isNoncomputable then
throwError "invalid use of 'noncomputable' in inductive declaration"
if modifiers.isPartial then
throwError "invalid use of 'partial' in inductive declaration"
def checkValidCtorModifier [Monad m] [MonadError m] (modifiers : Modifiers) : m Unit := do
if modifiers.isNoncomputable then
throwError "invalid use of 'noncomputable' in constructor declaration"
if modifiers.isPartial then
throwError "invalid use of 'partial' in constructor declaration"
if modifiers.isUnsafe then
throwError "invalid use of 'unsafe' in constructor declaration"
if modifiers.attrs.size != 0 then
throwError "invalid use of attributes in constructor declaration"
structure CtorView where
ref : Syntax
modifiers : Modifiers
inferMod : Bool -- true if `{}` is used in the constructor declaration
declName : Name
binders : Syntax
type? : Option Syntax
deriving Inhabited
structure InductiveView where
ref : Syntax
modifiers : Modifiers
shortDeclName : Name
declName : Name
levelNames : List Name
binders : Syntax
type? : Option Syntax
ctors : Array CtorView
derivingClasses : Array DerivingClassView
deriving Inhabited
structure ElabHeaderResult where
view : InductiveView
lctx : LocalContext
localInsts : LocalInstances
params : Array Expr
type : Expr
deriving Inhabited
private partial def elabHeaderAux (views : Array InductiveView) (i : Nat) (acc : Array ElabHeaderResult) : TermElabM (Array ElabHeaderResult) := do
if h : i < views.size then
let view := views.get ⟨i, h⟩
let acc ← Term.withAutoBoundImplicit <| Term.elabBinders view.binders.getArgs fun params => do
match view.type? with
| none =>
let u ← mkFreshLevelMVar
let type := mkSort u
Term.synthesizeSyntheticMVarsNoPostponing
let params ← Term.addAutoBoundImplicits params
pure <| acc.push { lctx := (← getLCtx), localInsts := (← getLocalInstances), params := params, type := type, view := view }
| some typeStx =>
let type ← Term.elabType typeStx
unless (← isTypeFormerType type) do
throwErrorAt typeStx "invalid inductive type, resultant type is not a sort"
Term.synthesizeSyntheticMVarsNoPostponing
let params ← Term.addAutoBoundImplicits params
pure <| acc.push { lctx := (← getLCtx), localInsts := (← getLocalInstances), params := params, type := type, view := view }
elabHeaderAux views (i+1) acc
else
pure acc
private def checkNumParams (rs : Array ElabHeaderResult) : TermElabM Nat := do
let numParams := rs[0].params.size
for r in rs do
unless r.params.size == numParams do
throwErrorAt r.view.ref "invalid inductive type, number of parameters mismatch in mutually inductive datatypes"
pure numParams
private def checkUnsafe (rs : Array ElabHeaderResult) : TermElabM Unit := do
let isUnsafe := rs[0].view.modifiers.isUnsafe
for r in rs do
unless r.view.modifiers.isUnsafe == isUnsafe do
throwErrorAt r.view.ref "invalid inductive type, cannot mix unsafe and safe declarations in a mutually inductive datatypes"
private def checkLevelNames (views : Array InductiveView) : TermElabM Unit := do
if views.size > 1 then
let levelNames := views[0].levelNames
for view in views do
unless view.levelNames == levelNames do
throwErrorAt view.ref "invalid inductive type, universe parameters mismatch in mutually inductive datatypes"
private def mkTypeFor (r : ElabHeaderResult) : TermElabM Expr := do
withLCtx r.lctx r.localInsts do
mkForallFVars r.params r.type
private def throwUnexpectedInductiveType {α} : TermElabM α :=
throwError "unexpected inductive resulting type"
private def eqvFirstTypeResult (firstType type : Expr) : MetaM Bool :=
forallTelescopeReducing firstType fun _ firstTypeResult => isDefEq firstTypeResult type
-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.
private partial def checkParamsAndResultType (type firstType : Expr) (numParams : Nat) : TermElabM Unit := do
try
forallTelescopeCompatible type firstType numParams fun _ type firstType =>
forallTelescopeReducing type fun _ type =>
forallTelescopeReducing firstType fun _ firstType => do
let type ← whnfD type
match type with
| Expr.sort .. =>
unless (← isDefEq firstType type) do
throwError "resulting universe mismatch, given{indentExpr type}\nexpected type{indentExpr firstType}"
| _ =>
throwError "unexpected inductive resulting type"
catch
| Exception.error ref msg => throw (Exception.error ref m!"invalid mutually inductive types, {msg}")
| ex => throw ex
-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.
private def checkHeader (r : ElabHeaderResult) (numParams : Nat) (firstType? : Option Expr) : TermElabM Expr := do
let type ← mkTypeFor r
match firstType? with
| none => pure type
| some firstType =>
withRef r.view.ref $ checkParamsAndResultType type firstType numParams
pure firstType
-- Auxiliary function for checking whether the types in mutually inductive declaration are compatible.
private partial def checkHeaders (rs : Array ElabHeaderResult) (numParams : Nat) (i : Nat) (firstType? : Option Expr) : TermElabM Unit := do
if i < rs.size then
let type ← checkHeader rs[i] numParams firstType?
checkHeaders rs numParams (i+1) type
private def elabHeader (views : Array InductiveView) : TermElabM (Array ElabHeaderResult) := do
let rs ← elabHeaderAux views 0 #[]
if rs.size > 1 then
checkUnsafe rs
let numParams ← checkNumParams rs
checkHeaders rs numParams 0 none
return rs
/- Create a local declaration for each inductive type in `rs`, and execute `x params indFVars`, where `params` are the inductive type parameters and
`indFVars` are the new local declarations.
We use the local context/instances and parameters of rs[0].
Note that this method is executed after we executed `checkHeaders` and established all
parameters are compatible. -/
private partial def withInductiveLocalDecls {α} (rs : Array ElabHeaderResult) (x : Array Expr → Array Expr → TermElabM α) : TermElabM α := do
let namesAndTypes ← rs.mapM fun r => do
let type ← mkTypeFor r
pure (r.view.shortDeclName, type)
let r0 := rs[0]
let params := r0.params
withLCtx r0.lctx r0.localInsts $ withRef r0.view.ref do
let rec loop (i : Nat) (indFVars : Array Expr) := do
if h : i < namesAndTypes.size then
let (id, type) := namesAndTypes.get ⟨i, h⟩
withLocalDeclD id type fun indFVar => loop (i+1) (indFVars.push indFVar)
else
x params indFVars
loop 0 #[]
private def isInductiveFamily (numParams : Nat) (indFVar : Expr) : TermElabM Bool := do
let indFVarType ← inferType indFVar
forallTelescopeReducing indFVarType fun xs _ =>
return xs.size > numParams
/-
Elaborate constructor types.
Remark: we check whether the resulting type is correct, and the parameter occurrences are consistent, but
we currently do not check for:
- Positivity (it is a rare failure, and the kernel already checks for it).
- Universe constraints (the kernel checks for it).
-/
private def elabCtors (indFVars : Array Expr) (indFVar : Expr) (params : Array Expr) (r : ElabHeaderResult) : TermElabM (List Constructor) := withRef r.view.ref do
let indFamily ← isInductiveFamily params.size indFVar
r.view.ctors.toList.mapM fun ctorView =>
Term.withAutoBoundImplicit <| Term.elabBinders ctorView.binders.getArgs fun ctorParams =>
withRef ctorView.ref do
let rec elabCtorType (k : Expr → TermElabM Constructor) : TermElabM Constructor := do
match ctorView.type? with
| none =>
if indFamily then
throwError "constructor resulting type must be specified in inductive family declaration"
k <| mkAppN indFVar params
| some ctorType =>
let type ← Term.elabType ctorType
Term.synthesizeSyntheticMVars (mayPostpone := true)
let type ← instantiateMVars type
let type ← checkParamOccs type
forallTelescopeReducing type fun _ resultingType => do
unless resultingType.getAppFn == indFVar do
throwError "unexpected constructor resulting type{indentExpr resultingType}"
unless (← isType resultingType) do
throwError "unexpected constructor resulting type, type expected{indentExpr resultingType}"
k type
elabCtorType fun type => do
Term.synthesizeSyntheticMVarsNoPostponing
let ctorParams ← Term.addAutoBoundImplicits ctorParams
let type ← mkForallFVars ctorParams type
let type ← mkForallFVars params type
return { name := ctorView.declName, type := type }
where
checkParamOccs (ctorType : Expr) : MetaM Expr :=
let visit (e : Expr) : MetaM TransformStep := do
let f := e.getAppFn
if indFVars.contains f then
let mut args := e.getAppArgs
unless args.size ≥ params.size do
throwError "unexpected inductive type occurrence{indentExpr e}"
for i in [:params.size] do
let param := params[i]
let arg := args[i]
unless (← isDefEq param arg) do
throwError "inductive datatype parameter mismatch{indentExpr arg}\nexpected{indentExpr param}"
args := args.set! i param
return TransformStep.done (mkAppN f args)
else
return TransformStep.visit e
transform ctorType (pre := visit)
/- Convert universe metavariables occurring in the `indTypes` into new parameters.
Remark: if the resulting inductive datatype has universe metavariables, we will fix it later using
`inferResultingUniverse`. -/
private def levelMVarToParamAux (indTypes : List InductiveType) : StateRefT Nat TermElabM (List InductiveType) :=
indTypes.mapM fun indType => do
let type ← Term.levelMVarToParam' indType.type
let ctors ← indType.ctors.mapM fun ctor => do
let ctorType ← Term.levelMVarToParam' ctor.type
pure { ctor with type := ctorType }
pure { indType with ctors := ctors, type := type }
private def levelMVarToParam (indTypes : List InductiveType) : TermElabM (List InductiveType) :=
(levelMVarToParamAux indTypes).run' 1
private def getResultingUniverse : List InductiveType → TermElabM Level
| [] => throwError "unexpected empty inductive declaration"
| indType :: _ => forallTelescopeReducing indType.type fun _ r => do
let r ← whnfD r
match r with
| Expr.sort u _ => pure u
| _ => throwError "unexpected inductive type resulting type{indentExpr r}"
def tmpIndParam := mkLevelParam `_tmp_ind_univ_param
/--
Return true if `u` is of the form `?m + k`.
Return false if `u` does not contain universe metavariables.
Throw exception otherwise. -/
def shouldInferResultUniverse (u : Level) : TermElabM Bool := do
let u ← instantiateLevelMVars u
if u.hasMVar then
match u.getLevelOffset with
| Level.mvar mvarId _ => do
Term.assignLevelMVar mvarId tmpIndParam
pure true
| _ =>
throwError "cannot infer resulting universe level of inductive datatype, given level contains metavariables {mkSort u}, provide universe explicitly"
else
pure false
/-
Auxiliary function for `updateResultingUniverse`
`accLevelAtCtor u r rOffset us` add `u` components to `us` if they are not already there and it is different from the resulting universe level `r+rOffset`.
If `u` is a `max`, then its components are recursively processed.
If `u` is a `succ` and `rOffset > 0`, we process the `u`s child using `rOffset-1`.
This method is used to infer the resulting universe level of an inductive datatype. -/
def accLevelAtCtor : Level → Level → Nat → Array Level → TermElabM (Array Level)
| Level.max u v _, r, rOffset, us => do let us ← accLevelAtCtor u r rOffset us; accLevelAtCtor v r rOffset us
| Level.imax u v _, r, rOffset, us => do let us ← accLevelAtCtor u r rOffset us; accLevelAtCtor v r rOffset us
| Level.zero _, _, _, us => pure us
| Level.succ u _, r, rOffset+1, us => accLevelAtCtor u r rOffset us
| u, r, rOffset, us =>
if rOffset == 0 && u == r then pure us
else if r.occurs u then throwError "failed to compute resulting universe level of inductive datatype, provide universe explicitly"
else if rOffset > 0 then throwError "failed to compute resulting universe level of inductive datatype, provide universe explicitly"
else if us.contains u then pure us
else pure (us.push u)
/- Auxiliary function for `updateResultingUniverse` -/
private partial def collectUniversesFromCtorTypeAux (r : Level) (rOffset : Nat) : Nat → Expr → Array Level → TermElabM (Array Level)
| 0, Expr.forallE n d b c, us => do
let u ← getLevel d
let u ← instantiateLevelMVars u
let us ← accLevelAtCtor u r rOffset us
withLocalDecl n c.binderInfo d fun x =>
let e := b.instantiate1 x
collectUniversesFromCtorTypeAux r rOffset 0 e us
| i+1, Expr.forallE n d b c, us => do
withLocalDecl n c.binderInfo d fun x =>
let e := b.instantiate1 x
collectUniversesFromCtorTypeAux r rOffset i e us
| _, _, us => pure us
/- Auxiliary function for `updateResultingUniverse` -/
private partial def collectUniversesFromCtorType
(r : Level) (rOffset : Nat) (ctorType : Expr) (numParams : Nat) (us : Array Level) : TermElabM (Array Level) :=
collectUniversesFromCtorTypeAux r rOffset numParams ctorType us
/- Auxiliary function for `updateResultingUniverse` -/
private partial def collectUniverses (r : Level) (rOffset : Nat) (numParams : Nat) (indTypes : List InductiveType) : TermElabM (Array Level) := do
let mut us := #[]
for indType in indTypes do
for ctor in indType.ctors do
us ← collectUniversesFromCtorType r rOffset ctor.type numParams us
return us
def mkResultUniverse (us : Array Level) (rOffset : Nat) : Level :=
if us.isEmpty && rOffset == 0 then
levelOne
else
let r := Level.mkNaryMax us.toList
if rOffset == 0 && !r.isZero && !r.isNeverZero then
(mkLevelMax r levelOne).normalize
else
r.normalize
private def updateResultingUniverse (numParams : Nat) (indTypes : List InductiveType) : TermElabM (List InductiveType) := do
let r ← getResultingUniverse indTypes
let rOffset : Nat := r.getOffset
let r : Level := r.getLevelOffset
unless r.isParam do
throwError "failed to compute resulting universe level of inductive datatype, provide universe explicitly"
let us ← collectUniverses r rOffset numParams indTypes
trace[Elab.inductive] "updateResultingUniverse us: {us}, r: {r}, rOffset: {rOffset}"
let rNew := mkResultUniverse us rOffset
let updateLevel (e : Expr) : Expr := e.replaceLevel fun u => if u == tmpIndParam then some rNew else none
return indTypes.map fun indType =>
let type := updateLevel indType.type;
let ctors := indType.ctors.map fun ctor => { ctor with type := updateLevel ctor.type };
{ indType with type := type, ctors := ctors }
register_builtin_option bootstrap.inductiveCheckResultingUniverse : Bool := {
defValue := true,
group := "bootstrap",
descr := "by default the `inductive/structure commands report an error if the resulting universe is not zero, but may be zero for some universe parameters. Reason: unless this type is a subsingleton, it is hardly what the user wants since it can only eliminate into `Prop`. In the `Init` package, we define subsingletons, and we use this option to disable the check. This option may be deleted in the future after we improve the validator"
}
def checkResultingUniverse (u : Level) : TermElabM Unit := do
if bootstrap.inductiveCheckResultingUniverse.get (← getOptions) then
let u ← instantiateLevelMVars u
if !u.isZero && !u.isNeverZero then
throwError "invalid universe polymorphic type, the resultant universe is not Prop (i.e., 0), but it may be Prop for some parameter values (solution: use 'u+1' or 'max 1 u'{indentD u}"
private def checkResultingUniverses (indTypes : List InductiveType) : TermElabM Unit := do
checkResultingUniverse (← getResultingUniverse indTypes)
private def collectUsed (indTypes : List InductiveType) : StateRefT CollectFVars.State MetaM Unit := do
indTypes.forM fun indType => do
Meta.collectUsedFVars indType.type
indType.ctors.forM fun ctor =>
Meta.collectUsedFVars ctor.type
private def removeUnused (vars : Array Expr) (indTypes : List InductiveType) : TermElabM (LocalContext × LocalInstances × Array Expr) := do
let (_, used) ← (collectUsed indTypes).run {}
Meta.removeUnused vars used
private def withUsed {α} (vars : Array Expr) (indTypes : List InductiveType) (k : Array Expr → TermElabM α) : TermElabM α := do
let (lctx, localInsts, vars) ← removeUnused vars indTypes
withLCtx lctx localInsts $ k vars
private def updateParams (vars : Array Expr) (indTypes : List InductiveType) : TermElabM (List InductiveType) :=
indTypes.mapM fun indType => do
let type ← mkForallFVars vars indType.type
let ctors ← indType.ctors.mapM fun ctor => do
let ctorType ← mkForallFVars vars ctor.type
pure { ctor with type := ctorType }
pure { indType with type := type, ctors := ctors }
private def collectLevelParamsInInductive (indTypes : List InductiveType) : Array Name := Id.run <| do
let mut usedParams : CollectLevelParams.State := {}
for indType in indTypes do
usedParams := collectLevelParams usedParams indType.type
for ctor in indType.ctors do
usedParams := collectLevelParams usedParams ctor.type
return usedParams.params
private def mkIndFVar2Const (views : Array InductiveView) (indFVars : Array Expr) (levelNames : List Name) : ExprMap Expr := Id.run <| do
let levelParams := levelNames.map mkLevelParam;
let mut m : ExprMap Expr := {}
for i in [:views.size] do
let view := views[i]
let indFVar := indFVars[i]
m := m.insert indFVar (mkConst view.declName levelParams)
return m
/- Remark: `numVars <= numParams`. `numVars` is the number of context `variables` used in the inductive declaration,
and `numParams` is `numVars` + number of explicit parameters provided in the declaration. -/
private def replaceIndFVarsWithConsts (views : Array InductiveView) (indFVars : Array Expr) (levelNames : List Name)
(numVars : Nat) (numParams : Nat) (indTypes : List InductiveType) : TermElabM (List InductiveType) :=
let indFVar2Const := mkIndFVar2Const views indFVars levelNames
indTypes.mapM fun indType => do
let ctors ← indType.ctors.mapM fun ctor => do
let type ← forallBoundedTelescope ctor.type numParams fun params type => do
let type := type.replace fun e =>
if !e.isFVar then
none
else match indFVar2Const.find? e with
| none => none
| some c => mkAppN c (params.extract 0 numVars)
mkForallFVars params type
pure { ctor with type := type }
pure { indType with ctors := ctors }
abbrev Ctor2InferMod := Std.HashMap Name Bool
private def mkCtor2InferMod (views : Array InductiveView) : Ctor2InferMod := Id.run <| do
let mut m := {}
for view in views do
for ctorView in view.ctors do
m := m.insert ctorView.declName ctorView.inferMod
return m
private def applyInferMod (views : Array InductiveView) (numParams : Nat) (indTypes : List InductiveType) : List InductiveType :=
let ctor2InferMod := mkCtor2InferMod views
indTypes.map fun indType =>
let ctors := indType.ctors.map fun ctor =>
let inferMod := ctor2InferMod.find! ctor.name -- true if `{}` was used
let ctorType := ctor.type.inferImplicit numParams !inferMod
{ ctor with type := ctorType }
{ indType with ctors := ctors }
private def mkAuxConstructions (views : Array InductiveView) : TermElabM Unit := do
let env ← getEnv
let hasEq := env.contains ``Eq
let hasHEq := env.contains ``HEq
let hasUnit := env.contains ``PUnit
let hasProd := env.contains ``Prod
for view in views do
let n := view.declName
mkRecOn n
if hasUnit then mkCasesOn n
if hasUnit && hasEq && hasHEq then mkNoConfusion n
if hasUnit && hasProd then mkBelow n
if hasUnit && hasProd then mkIBelow n
for view in views do
let n := view.declName;
if hasUnit && hasProd then mkBRecOn n
if hasUnit && hasProd then mkBInductionOn n
private def mkInductiveDecl (vars : Array Expr) (views : Array InductiveView) : TermElabM Unit := do
let view0 := views[0]
let scopeLevelNames ← Term.getLevelNames
checkLevelNames views
let allUserLevelNames := view0.levelNames
let isUnsafe := view0.modifiers.isUnsafe
withRef view0.ref <| Term.withLevelNames allUserLevelNames do
let rs ← elabHeader views
withInductiveLocalDecls rs fun params indFVars => do
let numExplicitParams := params.size
let mut indTypesArray := #[]
for i in [:views.size] do
let indFVar := indFVars[i]
let r := rs[i]
let type ← mkForallFVars params r.type
let ctors ← elabCtors indFVars indFVar params r
indTypesArray := indTypesArray.push { name := r.view.declName, type := type, ctors := ctors : InductiveType }
let indTypes := indTypesArray.toList
Term.synthesizeSyntheticMVarsNoPostponing
let u ← getResultingUniverse indTypes
let inferLevel ← shouldInferResultUniverse u
withUsed vars indTypes fun vars => do
let numVars := vars.size
let numParams := numVars + numExplicitParams
let indTypes ← updateParams vars indTypes
let indTypes ← levelMVarToParam indTypes
let indTypes ← if inferLevel then updateResultingUniverse numParams indTypes else checkResultingUniverses indTypes; pure indTypes
let usedLevelNames := collectLevelParamsInInductive indTypes
match sortDeclLevelParams scopeLevelNames allUserLevelNames usedLevelNames with
| Except.error msg => throwError msg
| Except.ok levelParams => do
let indTypes ← replaceIndFVarsWithConsts views indFVars levelParams numVars numParams indTypes
let indTypes := applyInferMod views numParams indTypes
trace[Meta.debug] "levelParams: {levelParams}"
let decl := Declaration.inductDecl levelParams numParams indTypes isUnsafe
Term.ensureNoUnassignedMVars decl
addDecl decl
mkAuxConstructions views
withSaveInfoContext do -- save new env
for view in views do
Term.addTermInfo view.ref[1] (← mkConstWithLevelParams view.declName) (isBinder := true)
for ctor in view.ctors do
Term.addTermInfo ctor.ref[2] (← mkConstWithLevelParams ctor.declName) (isBinder := true)
-- We need to invoke `applyAttributes` because `class` is implemented as an attribute.
Term.applyAttributesAt view.declName view.modifiers.attrs AttributeApplicationTime.afterTypeChecking
private def applyDerivingHandlers (views : Array InductiveView) : CommandElabM Unit := do
let mut processed : NameSet := {}
for view in views do
for classView in view.derivingClasses do
let className := classView.className
unless processed.contains className do
processed := processed.insert className
let mut declNames := #[]
for view in views do
if view.derivingClasses.any fun classView => classView.className == className then
declNames := declNames.push view.declName
classView.applyHandlers declNames
def elabInductiveViews (views : Array InductiveView) : CommandElabM Unit := do
let view0 := views[0]
let ref := view0.ref
runTermElabM view0.declName fun vars => withRef ref do
mkInductiveDecl vars views
mkSizeOfInstances view0.declName
Lean.Meta.IndPredBelow.mkBelow view0.declName
for view in views do
mkInjectiveTheorems view.declName
applyDerivingHandlers views
end Lean.Elab.Command
|
f6b40e4277806bfc4c1335a79e9efc262dff3d37 | 1446f520c1db37e157b631385707cc28a17a595e | /stage0/src/Init/Lean/Environment.lean | ae372c56e5f0149156737cfe211dcb4df149c82a | [
"Apache-2.0"
] | permissive | bdbabiak/lean4 | cab06b8a2606d99a168dd279efdd404edb4e825a | 3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac | refs/heads/master | 1,615,045,275,530 | 1,583,793,696,000 | 1,583,793,696,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 26,262 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import Init.System.IO
import Init.Util
import Init.Data.ByteArray
import Init.Lean.Data.SMap
import Init.Lean.Util.Path
import Init.Lean.Declaration
import Init.Lean.LocalContext
namespace Lean
/- Opaque environment extension state. It is essentially the Lean version of a C `void *`
TODO: mark opaque -/
def EnvExtensionState : Type := NonScalar
instance EnvExtensionState.inhabited : Inhabited EnvExtensionState := inferInstanceAs (Inhabited NonScalar)
/- TODO: mark opaque. -/
def ModuleIdx := Nat
instance ModuleIdx.inhabited : Inhabited ModuleIdx := inferInstanceAs (Inhabited Nat)
abbrev ConstMap := SMap Name ConstantInfo
structure Import :=
(module : Name)
(runtimeOnly : Bool := false)
instance : HasToString Import :=
⟨fun imp => toString imp.module ++ if imp.runtimeOnly then " (runtime)" else ""⟩
/- Environment fields that are not used often. -/
structure EnvironmentHeader :=
(trustLevel : UInt32 := 0)
(quotInit : Bool := false)
(mainModule : Name := arbitrary _)
(imports : Array Import := #[]) -- direct imports
(moduleNames : NameSet := {}) -- all imported .lean modules
/- TODO: mark opaque. -/
structure Environment :=
(const2ModIdx : HashMap Name ModuleIdx)
(constants : ConstMap)
(extensions : Array EnvExtensionState)
(header : EnvironmentHeader := {})
namespace Environment
instance : Inhabited Environment :=
⟨{ const2ModIdx := {}, constants := {}, extensions := #[] }⟩
def addAux (env : Environment) (cinfo : ConstantInfo) : Environment :=
{ constants := env.constants.insert cinfo.name cinfo, .. env }
@[export lean_environment_find]
def find? (env : Environment) (n : Name) : Option ConstantInfo :=
/- It is safe to use `find'` because we never overwrite imported declarations. -/
env.constants.find?' n
def contains (env : Environment) (n : Name) : Bool :=
env.constants.contains n
def imports (env : Environment) : Array Import :=
env.header.imports
def allImportedModuleNames (env : Environment) : NameSet :=
env.header.moduleNames
@[export lean_environment_set_main_module]
def setMainModule (env : Environment) (m : Name) : Environment :=
{ header := { mainModule := m, .. env.header }, .. env }
@[export lean_environment_main_module]
def mainModule (env : Environment) : Name :=
env.header.mainModule
@[export lean_environment_mark_quot_init]
private def markQuotInit (env : Environment) : Environment :=
{ header := { quotInit := true, .. env.header } , .. env }
@[export lean_environment_quot_init]
private def isQuotInit (env : Environment) : Bool :=
env.header.quotInit
@[export lean_environment_trust_level]
private def getTrustLevel (env : Environment) : UInt32 :=
env.header.trustLevel
def getModuleIdxFor? (env : Environment) (c : Name) : Option ModuleIdx :=
env.const2ModIdx.find? c
def isConstructor (env : Environment) (c : Name) : Bool :=
match env.find? c with
| ConstantInfo.ctorInfo _ => true
| _ => false
end Environment
inductive KernelException
| unknownConstant (env : Environment) (name : Name)
| alreadyDeclared (env : Environment) (name : Name)
| declTypeMismatch (env : Environment) (decl : Declaration) (givenType : Expr)
| declHasMVars (env : Environment) (name : Name) (expr : Expr)
| declHasFVars (env : Environment) (name : Name) (expr : Expr)
| funExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| typeExpected (env : Environment) (lctx : LocalContext) (expr : Expr)
| letTypeMismatch (env : Environment) (lctx : LocalContext) (name : Name) (givenType : Expr) (expectedType : Expr)
| exprTypeMismatch (env : Environment) (lctx : LocalContext) (expr : Expr) (expectedType : Expr)
| appTypeMismatch (env : Environment) (lctx : LocalContext) (app : Expr) (funType : Expr) (argType : Expr)
| invalidProj (env : Environment) (lctx : LocalContext) (proj : Expr)
| other (msg : String)
namespace Environment
/- Type check given declaration and add it to the environment -/
@[extern "lean_add_decl"]
constant addDecl (env : Environment) (decl : @& Declaration) : Except KernelException Environment := arbitrary _
/- Compile the given declaration, it assumes the declaration has already been added to the environment using `addDecl`. -/
@[extern "lean_compile_decl"]
constant compileDecl (env : Environment) (opt : @& Options) (decl : @& Declaration) : Except KernelException Environment := arbitrary _
def addAndCompile (env : Environment) (opt : Options) (decl : Declaration) : Except KernelException Environment := do
env ← addDecl env decl;
compileDecl env opt decl
end Environment
/- "Raw" environment extension.
TODO: mark opaque. -/
structure EnvExtension (σ : Type) :=
(idx : Nat)
(mkInitial : IO σ)
(stateInh : σ)
namespace EnvExtension
unsafe def setStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment :=
{ extensions := env.extensions.set! ext.idx (unsafeCast s), .. env }
@[implementedBy setStateUnsafe]
constant setState {σ : Type} (ext : EnvExtension σ) (env : Environment) (s : σ) : Environment := arbitrary _
unsafe def getStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ :=
let s : EnvExtensionState := env.extensions.get! ext.idx;
@unsafeCast _ _ ⟨ext.stateInh⟩ s
@[implementedBy getStateUnsafe]
constant getState {σ : Type} (ext : EnvExtension σ) (env : Environment) : σ := ext.stateInh
@[inline] unsafe def modifyStateUnsafe {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment :=
{ extensions := env.extensions.modify ext.idx $ fun s =>
let s : σ := (@unsafeCast _ _ ⟨ext.stateInh⟩ s);
let s : σ := f s;
unsafeCast s,
.. env }
@[implementedBy modifyStateUnsafe]
constant modifyState {σ : Type} (ext : EnvExtension σ) (env : Environment) (f : σ → σ) : Environment := arbitrary _
end EnvExtension
private def mkEnvExtensionsRef : IO (IO.Ref (Array (EnvExtension EnvExtensionState))) :=
IO.mkRef #[]
@[init mkEnvExtensionsRef]
private constant envExtensionsRef : IO.Ref (Array (EnvExtension EnvExtensionState)) := arbitrary _
instance EnvExtension.Inhabited (σ : Type) [Inhabited σ] : Inhabited (EnvExtension σ) :=
⟨{ idx := 0, stateInh := arbitrary _, mkInitial := arbitrary _ }⟩
unsafe def registerEnvExtensionUnsafe {σ : Type} [Inhabited σ] (mkInitial : IO σ) : IO (EnvExtension σ) := do
initializing ← IO.initializing;
unless initializing $ throw (IO.userError ("failed to register environment, extensions can only be registered during initialization"));
exts ← envExtensionsRef.get;
let idx := exts.size;
let ext : EnvExtension σ := {
idx := idx,
mkInitial := mkInitial,
stateInh := arbitrary _
};
envExtensionsRef.modify (fun exts => exts.push (unsafeCast ext));
pure ext
/- Environment extensions can only be registered during initialization.
Reasons:
1- Our implementation assumes the number of extensions does not change after an environment object is created.
2- We do not use any synchronization primitive to access `envExtensionsRef`. -/
@[implementedBy registerEnvExtensionUnsafe]
constant registerEnvExtension {σ : Type} [Inhabited σ] (mkInitial : IO σ) : IO (EnvExtension σ) := arbitrary _
private def mkInitialExtensionStates : IO (Array EnvExtensionState) := do
exts ← envExtensionsRef.get; exts.mapM $ fun ext => ext.mkInitial
@[export lean_mk_empty_environment]
def mkEmptyEnvironment (trustLevel : UInt32 := 0) : IO Environment := do
initializing ← IO.initializing;
when initializing $ throw (IO.userError "environment objects cannot be created during initialization");
exts ← mkInitialExtensionStates;
pure {
const2ModIdx := {},
constants := {},
header := { trustLevel := trustLevel },
extensions := exts
}
structure PersistentEnvExtensionState (α : Type) (σ : Type) :=
(importedEntries : Array (Array α)) -- entries per imported module
(state : σ)
/- An environment extension with support for storing/retrieving entries from a .olean file.
- α is the type of the entries that are stored in .olean files.
- β is the type of values used to update the state.
- σ is the actual state.
Remark: for most extensions α and β coincide.
Note that `addEntryFn` is not in `IO`. This is intentional, and allows us to write simple functions such as
```
def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
```
without using `IO`. We have many functions like `addAlias`.
`α` and ‵β` do not coincide for extensions where the data used to update the state contains, for example,
closures which we currently cannot store in files. -/
structure PersistentEnvExtension (α : Type) (β : Type) (σ : Type) extends EnvExtension (PersistentEnvExtensionState α σ) :=
(name : Name)
(addImportedFn : Environment → Array (Array α) → IO σ)
(addEntryFn : σ → β → σ)
(exportEntriesFn : σ → Array α)
(statsFn : σ → Format)
/- Opaque persistent environment extension entry. It is essentially a C `void *`
TODO: mark opaque -/
def EnvExtensionEntry := NonScalar
instance EnvExtensionEntry.inhabited : Inhabited EnvExtensionEntry := inferInstanceAs (Inhabited NonScalar)
instance PersistentEnvExtensionState.inhabited {α σ} [Inhabited σ] : Inhabited (PersistentEnvExtensionState α σ) :=
⟨{importedEntries := #[], state := arbitrary _ }⟩
instance PersistentEnvExtension.inhabited {α β σ} [Inhabited σ] : Inhabited (PersistentEnvExtension α β σ) :=
⟨{ toEnvExtension := { idx := 0, stateInh := arbitrary _, mkInitial := arbitrary _ },
name := arbitrary _,
addImportedFn := fun _ _ => arbitrary _,
addEntryFn := fun s _ => s,
exportEntriesFn := fun _ => #[],
statsFn := fun _ => Format.nil }⟩
namespace PersistentEnvExtension
def getModuleEntries {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (m : ModuleIdx) : Array α :=
(ext.toEnvExtension.getState env).importedEntries.get! m
def addEntry {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (b : β) : Environment :=
ext.toEnvExtension.modifyState env $ fun s =>
let state := ext.addEntryFn s.state b;
{ state := state, .. s }
def getState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) : σ :=
(ext.toEnvExtension.getState env).state
def setState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (s : σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { state := s, .. ps }
def modifyState {α β σ : Type} (ext : PersistentEnvExtension α β σ) (env : Environment) (f : σ → σ) : Environment :=
ext.toEnvExtension.modifyState env $ fun ps => { state := f (ps.state), .. ps }
end PersistentEnvExtension
private def mkPersistentEnvExtensionsRef : IO (IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState))) :=
IO.mkRef #[]
@[init mkPersistentEnvExtensionsRef]
private constant persistentEnvExtensionsRef : IO.Ref (Array (PersistentEnvExtension EnvExtensionEntry EnvExtensionEntry EnvExtensionState)) := arbitrary _
structure PersistentEnvExtensionDescr (α β σ : Type) :=
(name : Name)
(mkInitial : IO σ)
(addImportedFn : Environment → Array (Array α) → IO σ)
(addEntryFn : σ → β → σ)
(exportEntriesFn : σ → Array α)
(statsFn : σ → Format := fun _ => Format.nil)
unsafe def registerPersistentEnvExtensionUnsafe {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := do
pExts ← persistentEnvExtensionsRef.get;
when (pExts.any (fun ext => ext.name == descr.name)) $ throw (IO.userError ("invalid environment extension, '" ++ toString descr.name ++ "' has already been used"));
ext ← registerEnvExtension $ do {
initial ← descr.mkInitial;
let s : PersistentEnvExtensionState α σ := {
importedEntries := #[],
state := initial
};
pure s
};
let pExt : PersistentEnvExtension α β σ := {
toEnvExtension := ext,
name := descr.name,
addImportedFn := descr.addImportedFn,
addEntryFn := descr.addEntryFn,
exportEntriesFn := descr.exportEntriesFn,
statsFn := descr.statsFn
};
persistentEnvExtensionsRef.modify $ fun pExts => pExts.push (unsafeCast pExt);
pure pExt
@[implementedBy registerPersistentEnvExtensionUnsafe]
constant registerPersistentEnvExtension {α β σ : Type} [Inhabited σ] (descr : PersistentEnvExtensionDescr α β σ) : IO (PersistentEnvExtension α β σ) := arbitrary _
/- Simple PersistentEnvExtension that implements exportEntriesFn using a list of entries. -/
def SimplePersistentEnvExtension (α σ : Type) := PersistentEnvExtension α α (List α × σ)
@[specialize] def mkStateFromImportedEntries {α σ : Type} (addEntryFn : σ → α → σ) (initState : σ) (as : Array (Array α)) : σ :=
as.foldl (fun r es => es.foldl (fun r e => addEntryFn r e) r) initState
structure SimplePersistentEnvExtensionDescr (α σ : Type) :=
(name : Name)
(addEntryFn : σ → α → σ)
(addImportedFn : Array (Array α) → σ)
(toArrayFn : List α → Array α := fun es => es.toArray)
def registerSimplePersistentEnvExtension {α σ : Type} [Inhabited σ] (descr : SimplePersistentEnvExtensionDescr α σ) : IO (SimplePersistentEnvExtension α σ) :=
registerPersistentEnvExtension {
name := descr.name,
mkInitial := pure ([], descr.addImportedFn #[]),
addImportedFn := fun _ as => pure ([], descr.addImportedFn as),
addEntryFn := fun s e => match s with
| (entries, s) => (e::entries, descr.addEntryFn s e),
exportEntriesFn := fun s => descr.toArrayFn s.1.reverse,
statsFn := fun s => format "number of local entries: " ++ format s.1.length
}
namespace SimplePersistentEnvExtension
instance {α σ : Type} [Inhabited σ] : Inhabited (SimplePersistentEnvExtension α σ) :=
inferInstanceAs (Inhabited (PersistentEnvExtension α α (List α × σ)))
def getEntries {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : List α :=
(PersistentEnvExtension.getState ext env).1
def getState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) : σ :=
(PersistentEnvExtension.getState ext env).2
def setState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (s : σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, _⟩ => (entries, s))
def modifyState {α σ : Type} (ext : SimplePersistentEnvExtension α σ) (env : Environment) (f : σ → σ) : Environment :=
PersistentEnvExtension.modifyState ext env (fun ⟨entries, s⟩ => (entries, f s))
end SimplePersistentEnvExtension
/-- Environment extension for tagging declarations.
Declarations must only be tagged in the module where they were declared. -/
def TagDeclarationExtension := SimplePersistentEnvExtension Name NameSet
def mkTagDeclarationExtension (name : Name) : IO TagDeclarationExtension :=
registerSimplePersistentEnvExtension {
name := name,
addImportedFn := fun as => {},
addEntryFn := fun s n => s.insert n,
toArrayFn := fun es => es.toArray.qsort Name.quickLt
}
namespace TagDeclarationExtension
instance : Inhabited TagDeclarationExtension :=
inferInstanceAs (Inhabited (SimplePersistentEnvExtension Name NameSet))
def tag (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Environment :=
ext.addEntry env n
def isTagged (ext : TagDeclarationExtension) (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (ext.getModuleEntries env modIdx).binSearchContains n Name.quickLt
| none => (ext.getState env).contains n
end TagDeclarationExtension
/- API for creating extensions in C++.
This API will eventually be deleted. -/
def CPPExtensionState := NonScalar
instance CPPExtensionState.inhabited : Inhabited CPPExtensionState := inferInstanceAs (Inhabited NonScalar)
section
/- It is not safe to use "extract closed term" optimization in the following code because of `unsafeIO`.
If `compiler.extract_closed` is set to true, then the compiler will cache the result of
`exts ← envExtensionsRef.get` during initialization which is incorrect. -/
set_option compiler.extract_closed false
@[export lean_register_extension]
unsafe def registerCPPExtension (initial : CPPExtensionState) : Option Nat :=
(unsafeIO (do ext ← registerEnvExtension (pure initial); pure ext.idx)).toOption
@[export lean_set_extension]
unsafe def setCPPExtensionState (env : Environment) (idx : Nat) (s : CPPExtensionState) : Option Environment :=
(unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get! idx).setState env s)).toOption
@[export lean_get_extension]
unsafe def getCPPExtensionState (env : Environment) (idx : Nat) : Option CPPExtensionState :=
(unsafeIO (do exts ← envExtensionsRef.get; pure $ (exts.get! idx).getState env)).toOption
end
/- Legacy support for Modification objects -/
/- Opaque modification object. It is essentially a C `void *`.
In Lean 3, a .olean file is essentially a collection of modification objects.
This type represents the modification objects implemented in C++.
We will eventually delete this type as soon as we port the remaining Lean 3
legacy code.
TODO: mark opaque -/
def Modification := NonScalar
instance Modification.inhabited : Inhabited Modification := inferInstanceAs (Inhabited NonScalar)
def regModListExtension : IO (EnvExtension (List Modification)) :=
registerEnvExtension (pure [])
@[init regModListExtension]
constant modListExtension : EnvExtension (List Modification) := arbitrary _
/- The C++ code uses this function to store the given modification object into the environment. -/
@[export lean_environment_add_modification]
def addModification (env : Environment) (mod : Modification) : Environment :=
modListExtension.modifyState env $ fun mods => mod :: mods
/- mkModuleData invokes this function to convert a list of modification objects into
a serialized byte array. -/
@[extern 2 "lean_serialize_modifications"]
constant serializeModifications : List Modification → IO ByteArray := arbitrary _
@[extern 3 "lean_perform_serialized_modifications"]
constant performModifications : Environment → ByteArray → IO Environment := arbitrary _
/- Content of a .olean file.
We use `compact.cpp` to generate the image of this object in disk. -/
structure ModuleData :=
(imports : Array Import)
(constants : Array ConstantInfo)
(entries : Array (Name × Array EnvExtensionEntry))
(serialized : ByteArray) -- Legacy support: serialized modification objects
instance ModuleData.inhabited : Inhabited ModuleData :=
⟨{imports := arbitrary _, constants := arbitrary _, entries := arbitrary _, serialized := arbitrary _}⟩
@[extern 3 "lean_save_module_data"]
constant saveModuleData (fname : @& String) (m : ModuleData) : IO Unit := arbitrary _
@[extern 2 "lean_read_module_data"]
constant readModuleData (fname : @& String) : IO ModuleData := arbitrary _
def mkModuleData (env : Environment) : IO ModuleData := do
pExts ← persistentEnvExtensionsRef.get;
let entries : Array (Name × Array EnvExtensionEntry) := pExts.size.fold
(fun i result =>
let state := (pExts.get! i).getState env;
let exportEntriesFn := (pExts.get! i).exportEntriesFn;
let extName := (pExts.get! i).name;
result.push (extName, exportEntriesFn state))
#[];
bytes ← serializeModifications (modListExtension.getState env);
pure {
imports := env.header.imports,
constants := env.constants.foldStage2 (fun cs _ c => cs.push c) #[],
entries := entries,
serialized := bytes
}
@[export lean_write_module]
def writeModule (env : Environment) (fname : String) : IO Unit := do
modData ← mkModuleData env; saveModuleData fname modData
partial def importModulesAux : List Import → (NameSet × Array ModuleData) → IO (NameSet × Array ModuleData)
| [], r => pure r
| i::is, (s, mods) =>
if i.runtimeOnly || s.contains i.module then
importModulesAux is (s, mods)
else do
let s := s.insert i.module;
mFile ← findOLean i.module;
unlessM (IO.fileExists mFile) $
throw $ IO.userError $ "object file '" ++ mFile ++ "' of module " ++ toString i.module ++ " does not exist";
mod ← readModuleData mFile;
(s, mods) ← importModulesAux mod.imports.toList (s, mods);
let mods := mods.push mod;
importModulesAux is (s, mods)
private partial def getEntriesFor (mod : ModuleData) (extId : Name) : Nat → Array EnvExtensionState
| i =>
if i < mod.entries.size then
let curr := mod.entries.get! i;
if curr.1 == extId then curr.2 else getEntriesFor (i+1)
else
#[]
private def setImportedEntries (env : Environment) (mods : Array ModuleData) : IO Environment := do
pExtDescrs ← persistentEnvExtensionsRef.get;
pure $ mods.iterate env $ fun _ mod env =>
pExtDescrs.iterate env $ fun _ extDescr env =>
let entries := getEntriesFor mod extDescr.name 0;
extDescr.toEnvExtension.modifyState env $ fun s =>
{ importedEntries := s.importedEntries.push entries,
.. s }
private def finalizePersistentExtensions (env : Environment) : IO Environment := do
pExtDescrs ← persistentEnvExtensionsRef.get;
pExtDescrs.iterateM env $ fun _ extDescr env => do
let s := extDescr.toEnvExtension.getState env;
newState ← extDescr.addImportedFn env s.importedEntries;
pure $ extDescr.toEnvExtension.setState env { state := newState, .. s }
@[export lean_import_modules]
def importModules (imports : List Import) (trustLevel : UInt32 := 0) : IO Environment := do
(moduleNames, mods) ← importModulesAux imports ({}, #[]);
let const2ModIdx := mods.iterate {} $ fun (modIdx) (mod : ModuleData) (m : HashMap Name ModuleIdx) =>
mod.constants.iterate m $ fun _ cinfo m =>
m.insert cinfo.name modIdx.val;
constants ← mods.iterateM SMap.empty $ fun _ (mod : ModuleData) (cs : ConstMap) =>
mod.constants.iterateM cs $ fun _ cinfo cs => do {
when (cs.contains cinfo.name) $ throw (IO.userError ("import failed, environment already contains '" ++ toString cinfo.name ++ "'"));
pure $ cs.insert cinfo.name cinfo
};
let constants := constants.switch;
exts ← mkInitialExtensionStates;
let env : Environment := {
const2ModIdx := const2ModIdx,
constants := constants,
extensions := exts,
header := {
quotInit := !imports.isEmpty, -- We assume `core.lean` initializes quotient module
trustLevel := trustLevel,
imports := imports.toArray,
moduleNames := moduleNames
}
};
env ← setImportedEntries env mods;
env ← finalizePersistentExtensions env;
env ← mods.iterateM env $ fun _ mod env => performModifications env mod.serialized;
pure env
def regNamespacesExtension : IO (SimplePersistentEnvExtension Name NameSet) :=
registerSimplePersistentEnvExtension {
name := `namespaces,
addImportedFn := fun as => mkStateFromImportedEntries NameSet.insert {} as,
addEntryFn := fun s n => s.insert n
}
@[init regNamespacesExtension]
constant namespacesExt : SimplePersistentEnvExtension Name NameSet := arbitrary _
def registerNamespace (env : Environment) (n : Name) : Environment :=
if (namespacesExt.getState env).contains n then env else namespacesExt.addEntry env n
def isNamespace (env : Environment) (n : Name) : Bool :=
(namespacesExt.getState env).contains n
def getNamespaceSet (env : Environment) : NameSet :=
namespacesExt.getState env
namespace Environment
private def isNamespaceName : Name → Bool
| Name.str Name.anonymous _ _ => true
| Name.str p _ _ => isNamespaceName p
| _ => false
private def registerNamePrefixes : Environment → Name → Environment
| env, Name.str p _ _ => if isNamespaceName p then registerNamePrefixes (registerNamespace env p) p else env
| env, _ => env
@[export lean_environment_add]
def add (env : Environment) (cinfo : ConstantInfo) : Environment :=
let env := registerNamePrefixes env cinfo.name;
env.addAux cinfo
@[export lean_display_stats]
def displayStats (env : Environment) : IO Unit := do
pExtDescrs ← persistentEnvExtensionsRef.get;
let numModules := ((pExtDescrs.get! 0).toEnvExtension.getState env).importedEntries.size;
IO.println ("direct imports: " ++ toString env.header.imports);
IO.println ("number of imported modules: " ++ toString numModules);
IO.println ("number of consts: " ++ toString env.constants.size);
IO.println ("number of imported consts: " ++ toString env.constants.stageSizes.1);
IO.println ("number of local consts: " ++ toString env.constants.stageSizes.2);
IO.println ("number of buckets for imported consts: " ++ toString env.constants.numBuckets);
IO.println ("trust level: " ++ toString env.header.trustLevel);
IO.println ("number of extensions: " ++ toString env.extensions.size);
pExtDescrs.forM $ fun extDescr => do {
IO.println ("extension '" ++ toString extDescr.name ++ "'");
let s := extDescr.toEnvExtension.getState env;
let fmt := extDescr.statsFn s.state;
unless fmt.isNil (IO.println (" " ++ toString (Format.nest 2 (extDescr.statsFn s.state))));
IO.println (" number of imported entries: " ++ toString (s.importedEntries.foldl (fun sum es => sum + es.size) 0));
pure ()
};
pure ()
@[extern "lean_eval_const"]
unsafe constant evalConst (α) (env : @& Environment) (constName : @& Name) : Except String α := arbitrary _
end Environment
/- Helper functions for accessing environment -/
@[inline]
def matchConst {α : Type} (env : Environment) (e : Expr) (failK : Unit → α) (k : ConstantInfo → List Level → α) : α :=
match e with
| Expr.const n lvls _ =>
match env.find? n with
| some cinfo => k cinfo lvls
| _ => failK ()
| _ => failK ()
end Lean
|
d253e0f3fd6f0765ee6c98f50f72e05da96b08ff | 437dc96105f48409c3981d46fb48e57c9ac3a3e4 | /src/analysis/normed_space/basic.lean | c6f5811a7c1f1fe39ad25cc6028f6c3e6b2a5a9c | [
"Apache-2.0"
] | permissive | dan-c-k/mathlib | 08efec79bd7481ee6da9cc44c24a653bff4fbe0d | 96efc220f6225bc7a5ed8349900391a33a38cc56 | refs/heads/master | 1,658,082,847,093 | 1,589,013,201,000 | 1,589,013,201,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 40,737 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Johannes Hölzl
-/
import topology.instances.nnreal
import topology.instances.complex
import topology.algebra.module
import topology.metric_space.antilipschitz
/-!
# Normed spaces
-/
variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*}
noncomputable theory
open filter metric
open_locale topological_space
localized "notation f `→_{`:50 a `}`:0 b := filter.tendsto f (_root_.nhds a) (_root_.nhds b)" in filter
/-- Auxiliary class, endowing a type `α` with a function `norm : α → ℝ`. This class is designed to
be extended in more interesting classes specifying the properties of the norm. -/
class has_norm (α : Type*) := (norm : α → ℝ)
export has_norm (norm)
notation `∥`:1024 e:1 `∥`:1 := norm e
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed group is an additive group endowed with a norm for which `dist x y = ∥x - y∥` defines
a metric space structure. -/
class normed_group (α : Type*) extends has_norm α, add_comm_group α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
end prio
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist x y ≤ dist (x + z) (y + z)) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 },
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this }
end }
/-- Construct a normed group from a translation invariant distance -/
def normed_group.of_add_dist' [has_norm α] [add_comm_group α] [metric_space α]
(H1 : ∀ x:α, ∥x∥ = dist x 0)
(H2 : ∀ x y z : α, dist (x + z) (y + z) ≤ dist x y) : normed_group α :=
{ dist_eq := λ x y, begin
rw H1, apply le_antisymm,
{ have := H2 (x-y) 0 y, rwa [sub_add_cancel, zero_add] at this },
{ rw [sub_eq_add_neg, ← add_right_neg y], apply H2 }
end }
/-- A normed group can be built from a norm that satisfies algebraic properties. This is
formalised in this structure. -/
structure normed_group.core (α : Type*) [add_comm_group α] [has_norm α] : Prop :=
(norm_eq_zero_iff : ∀ x : α, ∥x∥ = 0 ↔ x = 0)
(triangle : ∀ x y : α, ∥x + y∥ ≤ ∥x∥ + ∥y∥)
(norm_neg : ∀ x : α, ∥-x∥ = ∥x∥)
/-- Constructing a normed group from core properties of a norm, i.e., registering the distance and
the metric space structure from the norm properties. -/
noncomputable def normed_group.of_core (α : Type*) [add_comm_group α] [has_norm α]
(C : normed_group.core α) : normed_group α :=
{ dist := λ x y, ∥x - y∥,
dist_eq := assume x y, by refl,
dist_self := assume x, (C.norm_eq_zero_iff (x - x)).mpr (show x - x = 0, by simp),
eq_of_dist_eq_zero := assume x y h, show (x = y), from sub_eq_zero.mp $ (C.norm_eq_zero_iff (x - y)).mp h,
dist_triangle := assume x y z,
calc ∥x - z∥ = ∥x - y + (y - z)∥ : by simp [sub_eq_add_neg]
... ≤ ∥x - y∥ + ∥y - z∥ : C.triangle _ _,
dist_comm := assume x y,
calc ∥x - y∥ = ∥ -(y - x)∥ : by simp
... = ∥y - x∥ : by { rw [C.norm_neg] } }
section normed_group
variables [normed_group α] [normed_group β]
lemma dist_eq_norm (g h : α) : dist g h = ∥g - h∥ :=
normed_group.dist_eq _ _
@[simp] lemma dist_zero_right (g : α) : dist g 0 = ∥g∥ :=
by rw [dist_eq_norm, sub_zero]
lemma norm_sub_rev (g h : α) : ∥g - h∥ = ∥h - g∥ :=
by simpa only [dist_eq_norm] using dist_comm g h
@[simp] lemma norm_neg (g : α) : ∥-g∥ = ∥g∥ :=
by simpa using norm_sub_rev 0 g
@[simp] lemma dist_add_left (g h₁ h₂ : α) : dist (g + h₁) (g + h₂) = dist h₁ h₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_add_right (g₁ g₂ h : α) : dist (g₁ + h) (g₂ + h) = dist g₁ g₂ :=
by simp [dist_eq_norm]
@[simp] lemma dist_neg_neg (g h : α) : dist (-g) (-h) = dist g h :=
by simp only [dist_eq_norm, neg_sub_neg, norm_sub_rev]
@[simp] lemma dist_sub_left (g h₁ h₂ : α) : dist (g - h₁) (g - h₂) = dist h₁ h₂ :=
by simp only [sub_eq_add_neg, dist_add_left, dist_neg_neg]
@[simp] lemma dist_sub_right (g₁ g₂ h : α) : dist (g₁ - h) (g₂ - h) = dist g₁ g₂ :=
dist_add_right _ _ _
/-- Triangle inequality for the norm. -/
lemma norm_add_le (g h : α) : ∥g + h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 (-h)
lemma norm_add_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ + g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_add_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_add_add_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ + g₂) (h₁ + h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
by simpa only [dist_add_left, dist_add_right] using dist_triangle (g₁ + g₂) (h₁ + g₂) (h₁ + h₂)
lemma dist_add_add_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ + g₂) (h₁ + h₂) ≤ d₁ + d₂ :=
le_trans (dist_add_add_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma dist_sub_sub_le (g₁ g₂ h₁ h₂ : α) :
dist (g₁ - g₂) (h₁ - h₂) ≤ dist g₁ h₁ + dist g₂ h₂ :=
dist_neg_neg g₂ h₂ ▸ dist_add_add_le _ _ _ _
lemma dist_sub_sub_le_of_le {g₁ g₂ h₁ h₂ : α} {d₁ d₂ : ℝ}
(H₁ : dist g₁ h₁ ≤ d₁) (H₂ : dist g₂ h₂ ≤ d₂) :
dist (g₁ - g₂) (h₁ - h₂) ≤ d₁ + d₂ :=
le_trans (dist_sub_sub_le g₁ g₂ h₁ h₂) (add_le_add H₁ H₂)
lemma abs_dist_sub_le_dist_add_add (g₁ g₂ h₁ h₂ : α) :
abs (dist g₁ h₁ - dist g₂ h₂) ≤ dist (g₁ + g₂) (h₁ + h₂) :=
by simpa only [dist_add_left, dist_add_right, dist_comm h₂]
using abs_dist_sub_le (g₁ + g₂) (h₁ + h₂) (h₁ + g₂)
@[simp] lemma norm_nonneg (g : α) : 0 ≤ ∥g∥ :=
by { rw[←dist_zero_right], exact dist_nonneg }
lemma norm_eq_zero {g : α} : ∥g∥ = 0 ↔ g = 0 :=
dist_zero_right g ▸ dist_eq_zero
@[simp] lemma norm_zero : ∥(0:α)∥ = 0 := norm_eq_zero.2 rfl
lemma norm_sum_le {β} : ∀(s : finset β) (f : β → α), ∥s.sum f∥ ≤ s.sum (λa, ∥ f a ∥) :=
finset.le_sum_of_subadditive norm norm_zero norm_add_le
lemma norm_sum_le_of_le {β} (s : finset β) {f : β → α} {n : β → ℝ} (h : ∀ b ∈ s, ∥f b∥ ≤ n b) :
∥s.sum f∥ ≤ s.sum n :=
by { haveI := classical.dec_eq β, exact le_trans (norm_sum_le s f) (finset.sum_le_sum h) }
lemma norm_pos_iff {g : α} : 0 < ∥ g ∥ ↔ g ≠ 0 :=
dist_zero_right g ▸ dist_pos
lemma norm_le_zero_iff {g : α} : ∥g∥ ≤ 0 ↔ g = 0 :=
by { rw[←dist_zero_right], exact dist_le_zero }
lemma norm_sub_le (g h : α) : ∥g - h∥ ≤ ∥g∥ + ∥h∥ :=
by simpa [dist_eq_norm] using dist_triangle g 0 h
lemma norm_sub_le_of_le {g₁ g₂ : α} {n₁ n₂ : ℝ} (H₁ : ∥g₁∥ ≤ n₁) (H₂ : ∥g₂∥ ≤ n₂) :
∥g₁ - g₂∥ ≤ n₁ + n₂ :=
le_trans (norm_sub_le g₁ g₂) (add_le_add H₁ H₂)
lemma dist_le_norm_add_norm (g h : α) : dist g h ≤ ∥g∥ + ∥h∥ :=
by { rw dist_eq_norm, apply norm_sub_le }
lemma abs_norm_sub_norm_le (g h : α) : abs(∥g∥ - ∥h∥) ≤ ∥g - h∥ :=
by simpa [dist_eq_norm] using abs_dist_sub_le g h 0
lemma norm_sub_norm_le (g h : α) : ∥g∥ - ∥h∥ ≤ ∥g - h∥ :=
le_trans (le_abs_self _) (abs_norm_sub_norm_le g h)
lemma dist_norm_norm_le (g h : α) : dist ∥g∥ ∥h∥ ≤ ∥g - h∥ :=
abs_norm_sub_norm_le g h
lemma ball_0_eq (ε : ℝ) : ball (0:α) ε = {x | ∥x∥ < ε} :=
set.ext $ assume a, by simp
lemma norm_le_of_mem_closed_ball {g h : α} {r : ℝ} (H : h ∈ closed_ball g r) :
∥h∥ ≤ ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... ≤ ∥g∥ + r : by { apply add_le_add_left, rw ← dist_eq_norm, exact H }
lemma norm_lt_of_mem_ball {g h : α} {r : ℝ} (H : h ∈ ball g r) :
∥h∥ < ∥g∥ + r :=
calc
∥h∥ = ∥g + (h - g)∥ : by rw [add_sub_cancel'_right]
... ≤ ∥g∥ + ∥h - g∥ : norm_add_le _ _
... < ∥g∥ + r : by { apply add_lt_add_left, rw ← dist_eq_norm, exact H }
theorem normed_group.tendsto_nhds_zero {f : γ → α} {l : filter γ} :
tendsto f l (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in l, ∥ f x ∥ < ε :=
metric.tendsto_nhds.trans $ by simp only [dist_zero_right]
section nnnorm
/-- Version of the norm taking values in nonnegative reals. -/
def nnnorm (a : α) : nnreal := ⟨norm a, norm_nonneg a⟩
@[simp] lemma coe_nnnorm (a : α) : (nnnorm a : ℝ) = norm a := rfl
lemma nndist_eq_nnnorm (a b : α) : nndist a b = nnnorm (a - b) := nnreal.eq $ dist_eq_norm _ _
lemma nnnorm_eq_zero {a : α} : nnnorm a = 0 ↔ a = 0 :=
by simp only [nnreal.eq_iff.symm, nnreal.coe_zero, coe_nnnorm, norm_eq_zero]
@[simp] lemma nnnorm_zero : nnnorm (0 : α) = 0 :=
nnreal.eq norm_zero
lemma nnnorm_add_le (g h : α) : nnnorm (g + h) ≤ nnnorm g + nnnorm h :=
nnreal.coe_le_coe.2 $ norm_add_le g h
@[simp] lemma nnnorm_neg (g : α) : nnnorm (-g) = nnnorm g :=
nnreal.eq $ norm_neg g
lemma nndist_nnnorm_nnnorm_le (g h : α) : nndist (nnnorm g) (nnnorm h) ≤ nnnorm (g - h) :=
nnreal.coe_le_coe.2 $ dist_norm_norm_le g h
lemma of_real_norm_eq_coe_nnnorm (x : β) : ennreal.of_real ∥x∥ = (nnnorm x : ennreal) :=
ennreal.of_real_eq_coe_nnreal _
lemma edist_eq_coe_nnnorm_sub (x y : β) : edist x y = (nnnorm (x - y) : ennreal) :=
by rw [edist_dist, dist_eq_norm, of_real_norm_eq_coe_nnnorm]
lemma edist_eq_coe_nnnorm (x : β) : edist x 0 = (nnnorm x : ennreal) :=
by rw [edist_eq_coe_nnnorm_sub, _root_.sub_zero]
lemma nndist_add_add_le (g₁ g₂ h₁ h₂ : α) :
nndist (g₁ + g₂) (h₁ + h₂) ≤ nndist g₁ h₁ + nndist g₂ h₂ :=
nnreal.coe_le_coe.2 $ dist_add_add_le g₁ g₂ h₁ h₂
lemma edist_add_add_le (g₁ g₂ h₁ h₂ : α) :
edist (g₁ + g₂) (h₁ + h₂) ≤ edist g₁ h₁ + edist g₂ h₂ :=
by { simp only [edist_nndist], norm_cast, apply nndist_add_add_le }
lemma nnnorm_sum_le {β} : ∀(s : finset β) (f : β → α), nnnorm (s.sum f) ≤ s.sum (λa, nnnorm (f a)) :=
finset.le_sum_of_subadditive nnnorm nnnorm_zero nnnorm_add_le
end nnnorm
lemma lipschitz_with.neg {α : Type*} [emetric_space α] {K : nnreal} {f : α → β}
(hf : lipschitz_with K f) : lipschitz_with K (λ x, -f x) :=
λ x y, by simpa only [edist_dist, dist_neg_neg] using hf x y
lemma lipschitz_with.add {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x + g x) :=
λ x y,
calc edist (f x + g x) (f y + g y) ≤ edist (f x) (f y) + edist (g x) (g y) :
edist_add_add_le _ _ _ _
... ≤ Kf * edist x y + Kg * edist x y :
add_le_add' (hf x y) (hg x y)
... = (Kf + Kg) * edist x y :
(add_mul _ _ _).symm
lemma lipschitz_with.sub {α : Type*} [emetric_space α] {Kf : nnreal} {f : α → β}
(hf : lipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g) :
lipschitz_with (Kf + Kg) (λ x, f x - g x) :=
hf.add hg.neg
lemma antilipschitz_with.add_lipschitz_with {α : Type*} [metric_space α] {Kf : nnreal} {f : α → β}
(hf : antilipschitz_with Kf f) {Kg : nnreal} {g : α → β} (hg : lipschitz_with Kg g)
(hK : Kg < Kf⁻¹) :
antilipschitz_with (Kf⁻¹ - Kg)⁻¹ (λ x, f x + g x) :=
begin
refine antilipschitz_with.of_le_mul_dist (λ x y, _),
rw [nnreal.coe_inv, ← div_eq_inv_mul],
apply le_div_of_mul_le (nnreal.coe_pos.2 $ nnreal.sub_pos.2 hK),
rw [mul_comm, nnreal.coe_sub (le_of_lt hK), sub_mul],
calc ↑Kf⁻¹ * dist x y - Kg * dist x y ≤ dist (f x) (f y) - dist (g x) (g y) :
sub_le_sub (hf.mul_le_dist x y) (hg.dist_le_mul x y)
... ≤ _ : le_trans (le_abs_self _) (abs_dist_sub_le_dist_add_add _ _ _ _)
end
/-- A submodule of a normed group is also a normed group, with the restriction of the norm.
As all instances can be inferred from the submodule `s`, they are put as implicit instead of
typeclasses. -/
instance submodule.normed_group {𝕜 : Type*} {_ : ring 𝕜}
{E : Type*} [normed_group E] {_ : module 𝕜 E} (s : submodule 𝕜 E) : normed_group s :=
{ norm := λx, norm (x : E),
dist_eq := λx y, dist_eq_norm (x : E) (y : E) }
/-- normed group instance on the product of two normed groups, using the sup norm. -/
instance prod.normed_group : normed_group (α × β) :=
{ norm := λx, max ∥x.1∥ ∥x.2∥,
dist_eq := assume (x y : α × β),
show max (dist x.1 y.1) (dist x.2 y.2) = (max ∥(x - y).1∥ ∥(x - y).2∥), by simp [dist_eq_norm] }
lemma norm_fst_le (x : α × β) : ∥x.1∥ ≤ ∥x∥ :=
by simp [norm, le_max_left]
lemma norm_snd_le (x : α × β) : ∥x.2∥ ≤ ∥x∥ :=
by simp [norm, le_max_right]
lemma norm_prod_le_iff {x : α × β} {r : ℝ} :
∥x∥ ≤ r ↔ ∥x.1∥ ≤ r ∧ ∥x.2∥ ≤ r :=
max_le_iff
/-- normed group instance on the product of finitely many normed groups, using the sup norm. -/
instance pi.normed_group {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] :
normed_group (Πi, π i) :=
{ norm := λf, ((finset.sup finset.univ (λ b, nnnorm (f b)) : nnreal) : ℝ),
dist_eq := assume x y,
congr_arg (coe : nnreal → ℝ) $ congr_arg (finset.sup finset.univ) $ funext $ assume a,
show nndist (x a) (y a) = nnnorm (x a - y a), from nndist_eq_nnnorm _ _ }
/-- The norm of an element in a product space is `≤ r` if and only if the norm of each
component is. -/
lemma pi_norm_le_iff {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] {r : ℝ} (hr : 0 ≤ r)
{x : Πi, π i} : ∥x∥ ≤ r ↔ ∀i, ∥x i∥ ≤ r :=
by { simp only [(dist_zero_right _).symm, dist_pi_le_iff hr], refl }
lemma norm_le_pi_norm {π : ι → Type*} [fintype ι] [∀i, normed_group (π i)] (x : Πi, π i) (i : ι) :
∥x i∥ ≤ ∥x∥ :=
(pi_norm_le_iff (norm_nonneg x)).1 (le_refl _) i
lemma tendsto_iff_norm_tendsto_zero {f : ι → β} {a : filter ι} {b : β} :
tendsto f a (𝓝 b) ↔ tendsto (λ e, ∥ f e - b ∥) a (𝓝 0) :=
by rw tendsto_iff_dist_tendsto_zero ; simp only [(dist_eq_norm _ _).symm]
lemma tendsto_zero_iff_norm_tendsto_zero {f : γ → β} {a : filter γ} :
tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e ∥) a (𝓝 0) :=
have tendsto f a (𝓝 0) ↔ tendsto (λ e, ∥ f e - 0 ∥) a (𝓝 0) :=
tendsto_iff_norm_tendsto_zero,
by simpa
lemma lim_norm (x : α) : (λg:α, ∥g - x∥) →_{x} 0 :=
tendsto_iff_norm_tendsto_zero.1 (continuous_iff_continuous_at.1 continuous_id x)
lemma lim_norm_zero : (λg:α, ∥g∥) →_{0} 0 :=
by simpa using lim_norm (0:α)
lemma continuous_norm : continuous (λg:α, ∥g∥) :=
begin
rw continuous_iff_continuous_at,
intro x,
rw [continuous_at, tendsto_iff_dist_tendsto_zero],
exact squeeze_zero (λ t, abs_nonneg _) (λ t, abs_norm_sub_norm_le _ _) (lim_norm x)
end
lemma filter.tendsto.norm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, ∥f x∥) l (𝓝 ∥a∥) :=
tendsto.comp continuous_norm.continuous_at h
lemma continuous_nnnorm : continuous (nnnorm : α → nnreal) :=
continuous_subtype_mk _ continuous_norm
lemma filter.tendsto.nnnorm {β : Type*} {l : filter β} {f : β → α} {a : α} (h : tendsto f l (𝓝 a)) :
tendsto (λ x, nnnorm (f x)) l (𝓝 (nnnorm a)) :=
tendsto.comp continuous_nnnorm.continuous_at h
/-- If `∥y∥→∞`, then we can assume `y≠x` for any fixed `x`. -/
lemma eventually_ne_of_tendsto_norm_at_top {l : filter γ} {f : γ → α}
(h : tendsto (λ y, ∥f y∥) l at_top) (x : α) :
∀ᶠ y in l, f y ≠ x :=
begin
have : ∀ᶠ y in l, 1 + ∥x∥ ≤ ∥f y∥ := h (mem_at_top (1 + ∥x∥)),
refine this.mono (λ y hy hxy, _),
subst x,
exact not_le_of_lt zero_lt_one (add_le_iff_nonpos_left.1 hy)
end
/-- A normed group is a uniform additive group, i.e., addition and subtraction are uniformly
continuous. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_uniform_group : uniform_add_group α :=
begin
refine ⟨metric.uniform_continuous_iff.2 $ assume ε hε, ⟨ε / 2, half_pos hε, assume a b h, _⟩⟩,
rw [prod.dist_eq, max_lt_iff, dist_eq_norm, dist_eq_norm] at h,
calc dist (a.1 - a.2) (b.1 - b.2) = ∥(a.1 - b.1) - (a.2 - b.2)∥ :
by simp [dist_eq_norm, sub_eq_add_neg]; abel
... ≤ ∥a.1 - b.1∥ + ∥a.2 - b.2∥ : norm_sub_le _ _
... < ε / 2 + ε / 2 : add_lt_add h.1 h.2
... = ε : add_halves _
end
@[priority 100] -- see Note [lower instance priority]
instance normed_top_monoid : topological_add_monoid α := by apply_instance -- short-circuit type class inference
@[priority 100] -- see Note [lower instance priority]
instance normed_top_group : topological_add_group α := by apply_instance -- short-circuit type class inference
end normed_group
section normed_ring
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed ring is a ring endowed with a norm which satisfies the inequality `∥x y∥ ≤ ∥x∥ ∥y∥`. -/
class normed_ring (α : Type*) extends has_norm α, ring α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul : ∀ a b, norm (a * b) ≤ norm a * norm b)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_ring.to_normed_group [β : normed_ring α] : normed_group α := { ..β }
lemma norm_mul_le {α : Type*} [normed_ring α] (a b : α) : (∥a*b∥) ≤ (∥a∥) * (∥b∥) :=
normed_ring.norm_mul _ _
lemma norm_pow_le {α : Type*} [normed_ring α] (a : α) : ∀ {n : ℕ}, 0 < n → ∥a^n∥ ≤ ∥a∥^n
| 1 h := by simp
| (n+2) h :=
le_trans (norm_mul_le a (a^(n+1)))
(mul_le_mul (le_refl _)
(norm_pow_le (nat.succ_pos _)) (norm_nonneg _) (norm_nonneg _))
/-- Normed ring structure on the product of two normed rings, using the sup norm. -/
instance prod.normed_ring [normed_ring α] [normed_ring β] : normed_ring (α × β) :=
{ norm_mul := assume x y,
calc
∥x * y∥ = ∥(x.1*y.1, x.2*y.2)∥ : rfl
... = (max ∥x.1*y.1∥ ∥x.2*y.2∥) : rfl
... ≤ (max (∥x.1∥*∥y.1∥) (∥x.2∥*∥y.2∥)) :
max_le_max (norm_mul_le (x.1) (y.1)) (norm_mul_le (x.2) (y.2))
... = (max (∥x.1∥*∥y.1∥) (∥y.2∥*∥x.2∥)) : by simp[mul_comm]
... ≤ (max (∥x.1∥) (∥x.2∥)) * (max (∥y.2∥) (∥y.1∥)) : by { apply max_mul_mul_le_max_mul_max; simp [norm_nonneg] }
... = (max (∥x.1∥) (∥x.2∥)) * (max (∥y.1∥) (∥y.2∥)) : by simp[max_comm]
... = (∥x∥*∥y∥) : rfl,
..prod.normed_group }
end normed_ring
@[priority 100] -- see Note [lower instance priority]
instance normed_ring_top_monoid [normed_ring α] : topological_monoid α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α × α, e.fst * e.snd - x.fst * x.snd =
e.fst * e.snd - e.fst * x.snd + (e.fst * x.snd - x.fst * x.snd), by intro; rw sub_add_sub_cancel,
begin
apply squeeze_zero,
{ intro, apply norm_nonneg },
{ simp only [this], intro, apply norm_add_le },
{ rw ←zero_add (0 : ℝ), apply tendsto.add,
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * t.snd - t.fst * x.snd∥ ≤ ∥t.fst∥ * ∥t.snd - x.snd∥,
rw ←mul_sub, apply norm_mul_le },
{ rw ←mul_zero (∥x.fst∥), apply tendsto.mul,
{ apply continuous_iff_continuous_at.1,
apply continuous_norm.comp continuous_fst },
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_snd }}},
{ apply squeeze_zero,
{ intro, apply norm_nonneg },
{ intro t, show ∥t.fst * x.snd - x.fst * x.snd∥ ≤ ∥t.fst - x.fst∥ * ∥x.snd∥,
rw ←sub_mul, apply norm_mul_le },
{ rw ←zero_mul (∥x.snd∥), apply tendsto.mul,
{ apply tendsto_iff_norm_tendsto_zero.1,
apply continuous_iff_continuous_at.1,
apply continuous_fst },
{ apply tendsto_const_nhds }}}}
end ⟩
/-- A normed ring is a topological ring. -/
@[priority 100] -- see Note [lower instance priority]
instance normed_top_ring [normed_ring α] : topological_ring α :=
⟨ continuous_iff_continuous_at.2 $ λ x, tendsto_iff_norm_tendsto_zero.2 $
have ∀ e : α, -e - -x = -(e - x), by intro; simp,
by simp only [this, norm_neg]; apply lim_norm ⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed field is a field with a norm satisfying ∥x y∥ = ∥x∥ ∥y∥. -/
class normed_field (α : Type*) extends has_norm α, field α, metric_space α :=
(dist_eq : ∀ x y, dist x y = norm (x - y))
(norm_mul' : ∀ a b, norm (a * b) = norm a * norm b)
/-- A nondiscrete normed field is a normed field in which there is an element of norm different from
`0` and `1`. This makes it possible to bring any element arbitrarily close to `0` by multiplication
by the powers of any element, and thus to relate algebra and topology. -/
class nondiscrete_normed_field (α : Type*) extends normed_field α :=
(non_trivial : ∃x:α, 1<∥x∥)
end prio
@[priority 100] -- see Note [lower instance priority]
instance normed_field.to_normed_ring [i : normed_field α] : normed_ring α :=
{ norm_mul := by finish [i.norm_mul'], ..i }
namespace normed_field
@[simp] lemma norm_one {α : Type*} [normed_field α] : ∥(1 : α)∥ = 1 :=
have ∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α)∥ * 1, by calc
∥(1 : α)∥ * ∥(1 : α)∥ = ∥(1 : α) * (1 : α)∥ : by rw normed_field.norm_mul'
... = ∥(1 : α)∥ * 1 : by simp,
eq_of_mul_eq_mul_left (ne_of_gt (norm_pos_iff.2 (by simp))) this
@[simp] lemma norm_mul [normed_field α] (a b : α) : ∥a * b∥ = ∥a∥ * ∥b∥ :=
normed_field.norm_mul' a b
instance normed_field.is_monoid_hom_norm [normed_field α] : is_monoid_hom (norm : α → ℝ) :=
{ map_one := norm_one, map_mul := norm_mul }
@[simp] lemma norm_pow [normed_field α] (a : α) : ∀ (n : ℕ), ∥a^n∥ = ∥a∥^n :=
is_monoid_hom.map_pow norm a
@[simp] lemma norm_prod {β : Type*} [normed_field α] (s : finset β) (f : β → α) :
∥s.prod f∥ = s.prod (λb, ∥f b∥) :=
eq.symm (s.prod_hom norm)
@[simp] lemma norm_div {α : Type*} [normed_field α] (a b : α) : ∥a/b∥ = ∥a∥/∥b∥ :=
begin
classical,
by_cases hb : b = 0, {simp [hb]},
apply eq_div_of_mul_eq,
{ apply ne_of_gt, apply norm_pos_iff.mpr hb },
{ rw [←normed_field.norm_mul, div_mul_cancel _ hb] }
end
@[simp] lemma norm_inv {α : Type*} [normed_field α] (a : α) : ∥a⁻¹∥ = ∥a∥⁻¹ :=
by simp only [inv_eq_one_div, norm_div, norm_one]
@[simp] lemma norm_fpow {α : Type*} [normed_field α] (a : α) : ∀n : ℤ,
∥a^n∥ = ∥a∥^n
| (n : ℕ) := norm_pow a n
| -[1+ n] := by simp [fpow_neg_succ_of_nat]
lemma exists_one_lt_norm (α : Type*) [i : nondiscrete_normed_field α] : ∃x : α, 1 < ∥x∥ :=
i.non_trivial
lemma exists_norm_lt_one (α : Type*) [nondiscrete_normed_field α] : ∃x : α, 0 < ∥x∥ ∧ ∥x∥ < 1 :=
begin
rcases exists_one_lt_norm α with ⟨y, hy⟩,
refine ⟨y⁻¹, _, _⟩,
{ simp only [inv_eq_zero, ne.def, norm_pos_iff],
assume h,
rw ← norm_eq_zero at h,
rw h at hy,
exact lt_irrefl _ (lt_trans zero_lt_one hy) },
{ simp [inv_lt_one hy] }
end
lemma exists_lt_norm (α : Type*) [nondiscrete_normed_field α]
(r : ℝ) : ∃ x : α, r < ∥x∥ :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hn⟩ := pow_unbounded_of_one_lt r hw in
⟨w^n, by rwa norm_pow⟩
lemma exists_norm_lt (α : Type*) [nondiscrete_normed_field α]
{r : ℝ} (hr : 0 < r) : ∃ x : α, 0 < ∥x∥ ∧ ∥x∥ < r :=
let ⟨w, hw⟩ := exists_one_lt_norm α in
let ⟨n, hle, hlt⟩ := exists_int_pow_near' hr hw in
⟨w^n, by { rw norm_fpow; exact fpow_pos_of_pos (lt_trans zero_lt_one hw) _},
by rwa norm_fpow⟩
lemma punctured_nhds_ne_bot {α : Type*} [nondiscrete_normed_field α] (x : α) :
nhds_within x (-{x}) ≠ ⊥ :=
begin
rw [← mem_closure_iff_nhds_within_ne_bot, metric.mem_closure_iff],
rintros ε ε0,
rcases normed_field.exists_norm_lt α ε0 with ⟨b, hb0, hbε⟩,
refine ⟨x + b, mt (set.mem_singleton_iff.trans add_right_eq_self).1 $ norm_pos_iff.1 hb0, _⟩,
rwa [dist_comm, dist_eq_norm, add_sub_cancel'],
end
lemma tendsto_inv [normed_field α] {r : α} (r0 : r ≠ 0) : tendsto (λq, q⁻¹) (𝓝 r) (𝓝 r⁻¹) :=
begin
refine (nhds_basis_closed_ball.tendsto_iff nhds_basis_closed_ball).2 (λε εpos, _),
let δ := min (ε/2 * ∥r∥^2) (∥r∥/2),
have norm_r_pos : 0 < ∥r∥ := norm_pos_iff.mpr r0,
have A : 0 < ε / 2 * ∥r∥ ^ 2 := mul_pos' (half_pos εpos) (pow_pos norm_r_pos 2),
have δpos : 0 < δ, by simp [half_pos norm_r_pos, A],
refine ⟨δ, δpos, λ x hx, _⟩,
have rx : ∥r∥/2 ≤ ∥x∥ := calc
∥r∥/2 = ∥r∥ - ∥r∥/2 : by ring
... ≤ ∥r∥ - ∥r - x∥ :
begin
apply sub_le_sub (le_refl _),
rw [← dist_eq_norm, dist_comm],
exact le_trans hx (min_le_right _ _)
end
... ≤ ∥r - (r - x)∥ : norm_sub_norm_le r (r - x)
... = ∥x∥ : by simp [sub_sub_cancel],
have norm_x_pos : 0 < ∥x∥ := lt_of_lt_of_le (half_pos norm_r_pos) rx,
have : x⁻¹ - r⁻¹ = (r - x) * x⁻¹ * r⁻¹,
by rw [sub_mul, sub_mul, mul_inv_cancel (norm_pos_iff.mp norm_x_pos), one_mul, mul_comm,
← mul_assoc, inv_mul_cancel r0, one_mul],
calc dist x⁻¹ r⁻¹ = ∥x⁻¹ - r⁻¹∥ : dist_eq_norm _ _
... ≤ ∥r-x∥ * ∥x∥⁻¹ * ∥r∥⁻¹ : by rw [this, norm_mul, norm_mul, norm_inv, norm_inv]
... ≤ (ε/2 * ∥r∥^2) * (2 * ∥r∥⁻¹) * (∥r∥⁻¹) : begin
apply_rules [mul_le_mul, inv_nonneg.2, le_of_lt A, norm_nonneg, inv_nonneg.2, mul_nonneg,
(inv_le_inv norm_x_pos norm_r_pos).2, le_refl],
show ∥r - x∥ ≤ ε / 2 * ∥r∥ ^ 2,
by { rw [← dist_eq_norm, dist_comm], exact le_trans hx (min_le_left _ _) },
show ∥x∥⁻¹ ≤ 2 * ∥r∥⁻¹,
{ convert (inv_le_inv norm_x_pos (half_pos norm_r_pos)).2 rx,
rw [inv_div, div_eq_inv_mul, mul_comm] },
show (0 : ℝ) ≤ 2, by norm_num
end
... = ε * (∥r∥ * ∥r∥⁻¹)^2 : by { generalize : ∥r∥⁻¹ = u, ring }
... = ε : by { rw [mul_inv_cancel (ne.symm (ne_of_lt norm_r_pos))], simp }
end
lemma continuous_on_inv [normed_field α] : continuous_on (λ(x:α), x⁻¹) {x | x ≠ 0} :=
begin
assume x hx,
apply continuous_at.continuous_within_at,
exact (tendsto_inv hx)
end
instance : normed_field ℝ :=
{ norm := λ x, abs x,
dist_eq := assume x y, rfl,
norm_mul' := abs_mul }
instance : nondiscrete_normed_field ℝ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
end normed_field
/-- If a function converges to a nonzero value, its inverse converges to the inverse of this value.
We use the name `tendsto.inv'` as `tendsto.inv` is already used in multiplicative topological
groups. -/
lemma filter.tendsto.inv' [normed_field α] {l : filter β} {f : β → α} {y : α}
(hy : y ≠ 0) (h : tendsto f l (𝓝 y)) :
tendsto (λx, (f x)⁻¹) l (𝓝 y⁻¹) :=
(normed_field.tendsto_inv hy).comp h
lemma filter.tendsto.div [normed_field α] {l : filter β} {f g : β → α} {x y : α}
(hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (hy : y ≠ 0) :
tendsto (λa, f a / g a) l (𝓝 (x / y)) :=
hf.mul (hg.inv' hy)
/-- Continuity at a point of the result of dividing two functions
continuous at that point, where the denominator is nonzero. -/
lemma continuous_at.div [topological_space α] [normed_field β] {f : α → β} {g : α → β} {x : α}
(hf : continuous_at f x) (hg : continuous_at g x) (hnz : g x ≠ 0) :
continuous_at (λ x, f x / g x) x :=
hf.div hg hnz
lemma real.norm_eq_abs (r : ℝ) : norm r = abs r := rfl
@[simp] lemma real.norm_two : ∥(2:ℝ)∥ = 2 := abs_of_pos (@two_pos ℝ _)
@[simp] lemma norm_norm [normed_group α] (x : α) : ∥∥x∥∥ = ∥x∥ :=
by rw [real.norm_eq_abs, abs_of_nonneg (norm_nonneg _)]
@[simp] lemma nnnorm_norm [normed_group α] (a : α) : nnnorm ∥a∥ = nnnorm a :=
by simp only [nnnorm, norm_norm]
instance : normed_ring ℤ :=
{ norm := λ n, ∥(n : ℝ)∥,
norm_mul := λ m n, le_of_eq $ by simp only [norm, int.cast_mul, abs_mul],
dist_eq := λ m n, by simp only [int.dist_eq, norm, int.cast_sub] }
@[norm_cast] lemma int.norm_cast_real (m : ℤ) : ∥(m : ℝ)∥ = ∥m∥ := rfl
instance : normed_field ℚ :=
{ norm := λ r, ∥(r : ℝ)∥,
norm_mul' := λ r₁ r₂, by simp only [norm, rat.cast_mul, abs_mul],
dist_eq := λ r₁ r₂, by simp only [rat.dist_eq, norm, rat.cast_sub] }
instance : nondiscrete_normed_field ℚ :=
{ non_trivial := ⟨2, by { unfold norm, rw abs_of_nonneg; norm_num }⟩ }
@[norm_cast, simp] lemma rat.norm_cast_real (r : ℚ) : ∥(r : ℝ)∥ = ∥r∥ := rfl
@[norm_cast, simp] lemma int.norm_cast_rat (m : ℤ) : ∥(m : ℚ)∥ = ∥m∥ :=
by rw [← rat.norm_cast_real, ← int.norm_cast_real]; congr' 1; norm_cast
section normed_space
section prio
set_option default_priority 100 -- see Note [default priority]
-- see Note[vector space definition] for why we extend `module`.
/-- A normed space over a normed field is a vector space endowed with a norm which satisfies the
equality `∥c • x∥ = ∥c∥ ∥x∥`. -/
class normed_space (α : Type*) (β : Type*) [normed_field α] [normed_group β]
extends module α β :=
(norm_smul : ∀ (a:α) (b:β), norm (a • b) = has_norm.norm a * norm b)
end prio
variables [normed_field α] [normed_group β]
instance normed_field.to_normed_space : normed_space α α :=
{ norm_smul := normed_field.norm_mul }
lemma norm_smul [normed_space α β] (s : α) (x : β) : ∥s • x∥ = ∥s∥ * ∥x∥ :=
normed_space.norm_smul s x
lemma dist_smul [normed_space α β] (s : α) (x y : β) : dist (s • x) (s • y) = ∥s∥ * dist x y :=
by simp only [dist_eq_norm, (norm_smul _ _).symm, smul_sub]
lemma nnnorm_smul [normed_space α β] (s : α) (x : β) : nnnorm (s • x) = nnnorm s * nnnorm x :=
nnreal.eq $ norm_smul s x
lemma nndist_smul [normed_space α β] (s : α) (x y : β) :
nndist (s • x) (s • y) = nnnorm s * nndist x y :=
nnreal.eq $ dist_smul s x y
variables {E : Type*} {F : Type*}
[normed_group E] [normed_space α E] [normed_group F] [normed_space α F]
@[priority 100] -- see Note [lower instance priority]
instance normed_space.topological_vector_space : topological_vector_space α E :=
begin
refine { continuous_smul := continuous_iff_continuous_at.2 $ λ p, tendsto_iff_norm_tendsto_zero.2 _ },
refine squeeze_zero (λ _, norm_nonneg _) _ _,
{ exact λ q, ∥q.1 - p.1∥ * ∥q.2∥ + ∥p.1∥ * ∥q.2 - p.2∥ },
{ intro q,
rw [← sub_add_sub_cancel, ← norm_smul, ← norm_smul, smul_sub, sub_smul],
exact norm_add_le _ _ },
{ conv { congr, skip, skip, congr, rw [← zero_add (0:ℝ)], congr,
rw [← zero_mul ∥p.2∥], skip, rw [← mul_zero ∥p.1∥] },
exact ((tendsto_iff_norm_tendsto_zero.1 (continuous_fst.tendsto p)).mul (continuous_snd.tendsto p).norm).add
(tendsto_const_nhds.mul (tendsto_iff_norm_tendsto_zero.1 (continuous_snd.tendsto p))) }
end
/-- In a normed space over a nondiscrete normed field, only `⊤` submodule has a nonempty interior.
See also `submodule.eq_top_of_nonempty_interior'` for a `topological_module` version. -/
lemma submodule.eq_top_of_nonempty_interior {α E : Type*} [nondiscrete_normed_field α] [normed_group E]
[normed_space α E] (s : submodule α E) (hs : (interior (s:set E)).nonempty) :
s = ⊤ :=
begin
refine s.eq_top_of_nonempty_interior' _ hs,
simp only [is_unit_iff_ne_zero, @ne.def α, set.mem_singleton_iff.symm],
exact normed_field.punctured_nhds_ne_bot _
end
open normed_field
/-- If there is a scalar `c` with `∥c∥>1`, then any element can be moved by scalar multiplication to
any shell of width `∥c∥`. Also recap information on the norm of the rescaling element that shows
up in applications. -/
lemma rescale_to_shell {c : α} (hc : 1 < ∥c∥) {ε : ℝ} (εpos : 0 < ε) {x : E} (hx : x ≠ 0) :
∃d:α, d ≠ 0 ∧ ∥d • x∥ ≤ ε ∧ (ε/∥c∥ ≤ ∥d • x∥) ∧ (∥d∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥) :=
begin
have xεpos : 0 < ∥x∥/ε := div_pos_of_pos_of_pos (norm_pos_iff.2 hx) εpos,
rcases exists_int_pow_near xεpos hc with ⟨n, hn⟩,
have cpos : 0 < ∥c∥ := lt_trans (zero_lt_one : (0 :ℝ) < 1) hc,
have cnpos : 0 < ∥c^(n+1)∥ := by { rw norm_fpow, exact lt_trans xεpos hn.2 },
refine ⟨(c^(n+1))⁻¹, _, _, _, _⟩,
show (c ^ (n + 1))⁻¹ ≠ 0,
by rwa [ne.def, inv_eq_zero, ← ne.def, ← norm_pos_iff],
show ∥(c ^ (n + 1))⁻¹ • x∥ ≤ ε,
{ rw [norm_smul, norm_inv, ← div_eq_inv_mul, div_le_iff cnpos, mul_comm, norm_fpow],
exact (div_le_iff εpos).1 (le_of_lt (hn.2)) },
show ε / ∥c∥ ≤ ∥(c ^ (n + 1))⁻¹ • x∥,
{ rw [div_le_iff cpos, norm_smul, norm_inv, norm_fpow, fpow_add (ne_of_gt cpos),
fpow_one, mul_inv', mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel (ne_of_gt cpos),
one_mul, ← div_eq_inv_mul, le_div_iff (fpow_pos_of_pos cpos _), mul_comm],
exact (le_div_iff εpos).1 hn.1 },
show ∥(c ^ (n + 1))⁻¹∥⁻¹ ≤ ε⁻¹ * ∥c∥ * ∥x∥,
{ have : ε⁻¹ * ∥c∥ * ∥x∥ = ε⁻¹ * ∥x∥ * ∥c∥, by ring,
rw [norm_inv, inv_inv', norm_fpow, fpow_add (ne_of_gt cpos), fpow_one, this, ← div_eq_inv_mul],
exact mul_le_mul_of_nonneg_right hn.1 (norm_nonneg _) }
end
/-- The product of two normed spaces is a normed space, with the sup norm. -/
instance : normed_space α (E × F) :=
{ norm_smul :=
begin
intros s x,
cases x with x₁ x₂,
change max (∥s • x₁∥) (∥s • x₂∥) = ∥s∥ * max (∥x₁∥) (∥x₂∥),
rw [norm_smul, norm_smul, ← mul_max_of_nonneg _ _ (norm_nonneg _)]
end,
add_smul := λ r x y, prod.ext (add_smul _ _ _) (add_smul _ _ _),
smul_add := λ r x y, prod.ext (smul_add _ _ _) (smul_add _ _ _),
..prod.normed_group,
..prod.module }
/-- The product of finitely many normed spaces is a normed space, with the sup norm. -/
instance pi.normed_space {E : ι → Type*} [fintype ι] [∀i, normed_group (E i)]
[∀i, normed_space α (E i)] : normed_space α (Πi, E i) :=
{ norm_smul := λ a f,
show (↑(finset.sup finset.univ (λ (b : ι), nnnorm (a • f b))) : ℝ) =
nnnorm a * ↑(finset.sup finset.univ (λ (b : ι), nnnorm (f b))),
by simp only [(nnreal.coe_mul _ _).symm, nnreal.mul_finset_sup, nnnorm_smul] }
/-- A subspace of a normed space is also a normed space, with the restriction of the norm. -/
instance submodule.normed_space {𝕜 : Type*} [normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E] (s : submodule 𝕜 E) : normed_space 𝕜 s :=
{ norm_smul := λc x, norm_smul c (x : E) }
end normed_space
section normed_algebra
section prio
set_option default_priority 100 -- see Note [default priority]
/-- A normed algebra `𝕜'` over `𝕜` is an algebra endowed with a norm for which the embedding of
`𝕜` in `𝕜'` is an isometry. -/
class normed_algebra (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
extends algebra 𝕜 𝕜' :=
(norm_algebra_map_eq : ∀x:𝕜, ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥)
end prio
@[simp] lemma norm_algebra_map_eq {𝕜 : Type*} (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] (x : 𝕜) : ∥algebra_map 𝕜 𝕜' x∥ = ∥x∥ :=
normed_algebra.norm_algebra_map_eq _
end normed_algebra
section restrict_scalars
variables (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_field 𝕜'] [normed_algebra 𝕜 𝕜']
{E : Type*} [normed_group E] [normed_space 𝕜' E]
/-- `𝕜`-normed space structure induced by a `𝕜'`-normed space structure when `𝕜'` is a
normed algebra over `𝕜`. Not registered as an instance as `𝕜'` can not be inferred. -/
def normed_space.restrict_scalars : normed_space 𝕜 E :=
{ norm_smul := λc x, begin
change ∥(algebra_map 𝕜 𝕜' c) • x∥ = ∥c∥ * ∥x∥,
simp [norm_smul]
end,
..module.restrict_scalars 𝕜 𝕜' E }
end restrict_scalars
section summable
open_locale classical
open finset filter
variables [normed_group α]
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma cauchy_seq_finset_iff_vanishing_norm {f : ι → α} :
cauchy_seq (λ s : finset ι, s.sum f) ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε :=
begin
simp only [cauchy_seq_finset_iff_vanishing, metric.mem_nhds_iff, exists_imp_distrib],
split,
{ assume h ε hε, refine h {x | ∥x∥ < ε} ε hε _, rw [ball_0_eq ε] },
{ assume h s ε hε hs,
rcases h ε hε with ⟨t, ht⟩,
refine ⟨t, assume u hu, hs _⟩,
rw [ball_0_eq],
exact ht u hu }
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma summable_iff_vanishing_norm [complete_space α] {f : ι → α} :
summable f ↔ ∀ε > 0, ∃s:finset ι, ∀t, disjoint t s → ∥ t.sum f ∥ < ε :=
by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing_norm]
lemma cauchy_seq_finset_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g)
(h : ∀i, ∥f i∥ ≤ g i) : cauchy_seq (λ s : finset ι, s.sum f) :=
cauchy_seq_finset_iff_vanishing_norm.2 $ assume ε hε,
let ⟨s, hs⟩ := summable_iff_vanishing_norm.1 hg ε hε in
⟨s, assume t ht,
have ∥t.sum g∥ < ε := hs t ht,
have nn : 0 ≤ t.sum g := finset.sum_nonneg (assume a _, le_trans (norm_nonneg _) (h a)),
lt_of_le_of_lt (norm_sum_le_of_le t (λ i _, h i)) $
by rwa [real.norm_eq_abs, abs_of_nonneg nn] at this⟩
lemma cauchy_seq_finset_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) :
cauchy_seq (λ s : finset ι, s.sum f) :=
cauchy_seq_finset_of_norm_bounded _ hf (assume i, le_refl _)
/-- If a function `f` is summable in norm, and along some sequence of finsets exhausting the space
its sum is converging to a limit `a`, then this holds along all finsets, i.e., `f` is summable
with sum `a`. -/
lemma has_sum_of_subseq_of_summable {f : ι → α} (hf : summable (λa, ∥f a∥))
{s : β → finset ι} {p : filter β} (hp : p ≠ ⊥)
(hs : tendsto s p at_top) {a : α} (ha : tendsto (λ b, (s b).sum f) p (𝓝 a)) :
has_sum f a :=
tendsto_nhds_of_cauchy_seq_of_subseq (cauchy_seq_finset_of_summable_norm hf) hp hs ha
/-- If `∑' i, ∥f i∥` is summable, then `∥(∑' i, f i)∥ ≤ (∑' i, ∥f i∥)`. Note that we do not assume that
`∑' i, f i` is summable, and it might not be the case if `α` is not a complete space. -/
lemma norm_tsum_le_tsum_norm {f : ι → α} (hf : summable (λi, ∥f i∥)) : ∥(∑'i, f i)∥ ≤ (∑' i, ∥f i∥) :=
begin
by_cases h : summable f,
{ have h₁ : tendsto (λs:finset ι, ∥s.sum f∥) at_top (𝓝 ∥(∑' i, f i)∥) :=
(continuous_norm.tendsto _).comp h.has_sum,
have h₂ : tendsto (λs:finset ι, s.sum (λi, ∥f i∥)) at_top (𝓝 (∑' i, ∥f i∥)) :=
hf.has_sum,
exact le_of_tendsto_of_tendsto' at_top_ne_bot h₁ h₂ (assume s, norm_sum_le _ _) },
{ rw tsum_eq_zero_of_not_summable h,
simp [tsum_nonneg] }
end
variable [complete_space α]
lemma summable_of_norm_bounded {f : ι → α} (g : ι → ℝ) (hg : summable g) (h : ∀i, ∥f i∥ ≤ g i) :
summable f :=
by { rw summable_iff_cauchy_seq_finset, exact cauchy_seq_finset_of_norm_bounded g hg h }
lemma summable_of_nnnorm_bounded {f : ι → α} (g : ι → nnreal) (hg : summable g)
(h : ∀i, nnnorm (f i) ≤ g i) : summable f :=
summable_of_norm_bounded (λ i, (g i : ℝ)) (nnreal.summable_coe.2 hg) (λ i, by exact_mod_cast h i)
lemma summable_of_summable_norm {f : ι → α} (hf : summable (λa, ∥f a∥)) : summable f :=
summable_of_norm_bounded _ hf (assume i, le_refl _)
lemma summable_of_summable_nnnorm {f : ι → α} (hf : summable (λa, nnnorm (f a))) : summable f :=
summable_of_nnnorm_bounded _ hf (assume i, le_refl _)
end summable
|
5ba0d56e11da61e4eca5c6f5ff0143b3fcdd7dc7 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/coe2.lean | caea7063fc71d42c043b18002156a7851c234e58 | [
"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 | 325 | lean | import data.int
open nat int
variable f : int → int
variable a : nat
constant bv : nat → Type₁
attribute bv [coercion]
constant g : Π {n : nat}, bv n → bv n
set_option pp.all true
check f a
check fun x : a, g x
set_option elaborator.coercions false
check f a -- ERROR
check fun x : a, g x -- ERROR
|
f664add878835ef7988ade2707b6553cebcc8bf1 | d7189ea2ef694124821b033e533f18905b5e87ef | /galois/vector/dot_product.lean | 892370fc8c2516fc8ab23076e7748eac25afd42e | [
"Apache-2.0"
] | permissive | digama0/lean-protocol-support | eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59 | cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda | refs/heads/master | 1,625,421,450,627 | 1,506,035,462,000 | 1,506,035,462,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,231 | lean | import data.rat
galois.logic
galois.vector.lemmas
universes u
section
parameters {A : Type u} [comm_ring A]
def dot_product {n : ℕ} (x y : vector A n) : A
:= list.foldr (+) 0 (vector.map₂ (*) x y).to_list
lemma dot_product_cons {n : ℕ} (x y : A) (xs ys : vector A n)
: dot_product (x :: xs) (y :: ys)
= x * y + dot_product xs ys
:= begin
induction xs, induction ys,
reflexivity,
end
lemma dot_product_nil : dot_product vector.nil vector.nil = 0
:= rfl
lemma dot_product_0_len (xs ys : vector A 0)
: dot_product xs ys = 0
:= begin
rw vector.eq_nil xs, rw vector.eq_nil ys, reflexivity,
end
lemma dot_product_0 {n : ℕ} (xs : vector A n)
: dot_product (vector.generate n (λ _, (0 : A))) xs = 0
:= begin
induction n,
rw vector.eq_nil xs,
rw dot_product_0_len,
dsimp [vector.generate],
have Hxs := xs.invert_succ, induction Hxs with x xs' Hxs,
subst xs, rw dot_product_cons,
rw ih_1, simp,
end
lemma dot_product_unit (n : ℕ) (i : fin n) (c : A) (v : vector A n)
: dot_product (vector.generate n (λj, if i.val = j then c else 0)) v
= c * v.nth i
:= begin
induction n; dsimp [vector.generate],
exfalso, apply fin.fin_0_empty, assumption,
have Hv := v.invert_succ,
induction Hv with x xs Hv, subst Hv,
rw dot_product_cons,
apply (if H : i.val = 0 then _ else _),
{ rw (if_pos H), rw (vector.nth_0 _ _ H),
dsimp [function.comp],
rw H,
have Hf : (λ (x : ℕ), ite (0 = nat.succ x) c 0) = λ _, 0,
apply funext; intros x,
rw if_neg, intros contra, cases contra,
rw Hf, clear Hf,
rw dot_product_0, simp,
},
{ rw (if_neg H), simp,
have H' : i ≠ 0,
intros contra, apply H, rw contra, reflexivity,
rw vector.nth_cons_nz _ H', dsimp [function.comp],
rw ← ih_1, f_equal, f_equal,
apply funext, intros n,
f_equal, apply ite_iff,
apply fin.succ_pred_equiv, }
end
lemma dot_product_scale_l {n : ℕ} (c : A) (xs ys : vector A n)
: dot_product (vector.map (λ x, c * x) xs) ys
= c * dot_product xs ys
:= begin
induction n,
{ rw (vector.eq_nil xs), rw (vector.eq_nil ys),
rw vector.map_nil,
rw dot_product_nil, simp, },
{ have Hx := xs.invert_succ, induction Hx with x xs' Hx, subst xs,
have Hy := ys.invert_succ, induction Hy with y ys' Hy, subst ys,
rw vector.map_cons, repeat { rw dot_product_cons },
rw mul_add, rw ih_1, simp,
}
end
lemma dot_product_comm {n : ℕ} (x y : vector A n)
: dot_product x y = dot_product y x
:= begin
dsimp [dot_product],
rw vector.map₂_comm, intros, apply mul_comm,
end
lemma dot_product_sum_r {n : ℕ} (x y z : vector A n)
: dot_product x (vector.map₂ (+) y z)
= dot_product x y + dot_product x z
:= begin
induction n,
{ repeat {rw dot_product_0_len },
rw add_zero, },
{ have Hx := x.invert_succ, induction Hx with x' xs Hx, subst x,
have Hy := y.invert_succ, induction Hy with y' ys Hy, subst y,
have Hz := z.invert_succ, induction Hz with z' zs Hz, subst z,
rw vector.map₂_cons, repeat { rw dot_product_cons },
rw ih_1, rw mul_add, simp,
}
end
lemma dot_product_sum_l {n : ℕ} (x y z : vector A n)
: dot_product (vector.map₂ (+) x y) z
= dot_product x z + dot_product y z
:= begin
rw dot_product_comm, rw dot_product_sum_r,
rw dot_product_comm z x, rw dot_product_comm z y,
end
end |
ae6ad72437a26c73399a12793806d54e507887a6 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/num/bitwise_auto.lean | 6d220e159defcab23bfb5ea667869a95c1c575c5 | [] | 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 | 6,019 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.num.basic
import Mathlib.data.bitvec.core
import Mathlib.PostPort
universes l u_1
namespace Mathlib
/-!
# Bitwise operations using binary representation of integers
## Definitions
* bitwise operations for `pos_num` and `num`,
* `snum`, a type that represents integers as a bit string with a sign bit at the end,
* arithmetic operations for `snum`.
-/
namespace pos_num
def lor : pos_num → pos_num → pos_num := sorry
def land : pos_num → pos_num → num := sorry
def ldiff : pos_num → pos_num → num := sorry
def lxor : pos_num → pos_num → num := sorry
def test_bit : pos_num → ℕ → Bool := sorry
def one_bits : pos_num → ℕ → List ℕ := sorry
def shiftl (p : pos_num) : ℕ → pos_num := sorry
def shiftr : pos_num → ℕ → num := sorry
end pos_num
namespace num
def lor : num → num → num := sorry
def land : num → num → num := sorry
def ldiff : num → num → num := sorry
def lxor : num → num → num := sorry
def shiftl : num → ℕ → num := sorry
def shiftr : num → ℕ → num := sorry
def test_bit : num → ℕ → Bool := sorry
def one_bits : num → List ℕ := sorry
end num
/-- This is a nonzero (and "non minus one") version of `snum`.
See the documentation of `snum` for more details. -/
inductive nzsnum where
| 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 where
| zero : Bool → snum
| nz : nzsnum → snum
protected instance snum.has_coe : has_coe nzsnum snum := has_coe.mk snum.nz
protected instance snum.has_zero : HasZero snum := { zero := snum.zero false }
protected instance nzsnum.has_one : HasOne nzsnum := { one := nzsnum.msb tt }
protected instance snum.has_one : HasOne snum := { one := snum.nz 1 }
protected instance nzsnum.inhabited : Inhabited nzsnum := { default := 1 }
protected instance snum.inhabited : Inhabited snum := { default := 0 }
infixr:67 " :: " => Mathlib.nzsnum.bit
/-!
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
def sign : nzsnum → Bool := sorry
def not : nzsnum → nzsnum := sorry
prefix:40 "~" => Mathlib.nzsnum.not
def bit0 : nzsnum → nzsnum := bit false
def bit1 : nzsnum → nzsnum := bit tt
def head : nzsnum → Bool := sorry
def tail : nzsnum → snum := sorry
end nzsnum
namespace snum
def sign : snum → Bool := sorry
def not : snum → snum := sorry
prefix:40 "~" => Mathlib.snum.not
def bit : Bool → snum → snum := sorry
infixr:67 " :: " => Mathlib.snum.bit
def bit0 : snum → snum := bit false
def bit1 : snum → snum := bit tt
theorem bit_zero (b : Bool) : b :: zero b = zero b :=
bool.cases_on b (Eq.refl (false :: zero false)) (Eq.refl (tt :: zero tt))
theorem bit_one (b : Bool) : b :: zero (!b) = ↑(nzsnum.msb b) :=
bool.cases_on b (Eq.refl (false :: zero (!false))) (Eq.refl (tt :: zero (!tt)))
end snum
namespace nzsnum
def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (snum.zero b))
(s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : nzsnum) : C ↑p :=
sorry
end nzsnum
namespace snum
def head : snum → Bool := sorry
def tail : snum → snum := sorry
def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (zero b))
(s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : snum) : C p :=
sorry
def rec' {α : Sort u_1} (z : Bool → α) (s : Bool → snum → α → α) : snum → α := drec' z s
def test_bit : ℕ → snum → Bool := sorry
def succ : snum → snum :=
rec' (fun (b : Bool) => cond b 0 1)
fun (b : Bool) (p succp : snum) => cond b (false :: succp) (tt :: p)
def pred : snum → snum :=
rec' (fun (b : Bool) => cond b (~1) (~0))
fun (b : Bool) (p predp : snum) => cond b (false :: p) (tt :: predp)
protected def neg (n : snum) : snum := succ (~n)
protected instance has_neg : Neg snum := { neg := snum.neg }
def czadd : Bool → Bool → snum → snum := sorry
end snum
namespace snum
/-- `a.bits n` is the vector of the `n` first bits of `a` (starting from the LSB). -/
def bits : snum → (n : ℕ) → vector Bool n := sorry
def cadd : snum → snum → Bool → snum :=
rec' (fun (a : Bool) (p : snum) (c : Bool) => czadd c a p)
fun (a : Bool) (p : snum) (IH : snum → Bool → snum) =>
rec' (fun (b c : Bool) => czadd c b (a :: p))
fun (b : Bool) (q : snum) (_x : Bool → snum) (c : Bool) =>
bitvec.xor3 a b c :: IH q (bitvec.carry a b c)
/-- Add two `snum`s. -/
protected def add (a : snum) (b : snum) : snum := cadd a b false
protected instance has_add : Add snum := { add := snum.add }
/-- Substract two `snum`s. -/
protected def sub (a : snum) (b : snum) : snum := a + -b
protected instance has_sub : Sub snum := { sub := snum.sub }
/-- Multiply two `snum`s. -/
protected def mul (a : snum) : snum → snum :=
rec' (fun (b : Bool) => cond b (-a) 0)
fun (b : Bool) (q IH : snum) => cond b (bit0 IH + a) (bit0 IH)
protected instance has_mul : Mul snum := { mul := snum.mul }
end Mathlib |
67e6d75405473d49a7ae4ee7b22ffff3088d2fd8 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/algebra/category/Group/limits.lean | bca3165ea9d2257d1905285fec78c004c186e113 | [
"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 | 4,248 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.category.Group.basic
import category_theory.limits.types
import category_theory.limits.preserves
import algebra.group.pi
/-!
# The category of abelian groups has all limits
Further, these limits are preserved by the forgetful functor --- that is,
the underlying types are just the limits in the category of types.
## Further work
A lot of this should be generalised / automated, as it's quite common for concrete
categories that the forgetful functor preserves limits.
-/
open category_theory
open category_theory.limits
universe u
namespace AddCommGroup
variables {J : Type u} [small_category J]
instance add_comm_group_obj (F : J ⥤ AddCommGroup) (j) :
add_comm_group ((F ⋙ forget AddCommGroup).obj j) :=
by { change add_comm_group (F.obj j), apply_instance }
instance sections_add_submonoid (F : J ⥤ AddCommGroup) :
is_add_submonoid (F ⋙ forget AddCommGroup).sections :=
{ zero_mem := λ j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_zero],
refl,
end,
add_mem := λ a b ah bh j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_add],
dsimp [functor.sections] at ah,
rw ah f,
dsimp [functor.sections] at bh,
rw bh f,
refl,
end }
instance sections_add_subgroup (F : J ⥤ AddCommGroup) :
is_add_subgroup (F ⋙ forget AddCommGroup).sections :=
{ neg_mem := λ a ah j j' f,
begin
erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_neg],
dsimp [functor.sections] at ah,
rw ah f,
refl,
end,
..(AddCommGroup.sections_add_submonoid F) }
instance limit_add_comm_group (F : J ⥤ AddCommGroup) :
add_comm_group (limit (F ⋙ forget AddCommGroup)) :=
@subtype.add_comm_group ((Π (j : J), (F ⋙ forget _).obj j)) (by apply_instance) _
(by convert (AddCommGroup.sections_add_subgroup F))
/-- `limit.π (F ⋙ forget AddCommGroup) j` as a `add_monoid_hom`. -/
def limit_π_add_monoid_hom (F : J ⥤ AddCommGroup) (j) :
limit (F ⋙ forget AddCommGroup) →+ (F ⋙ forget AddCommGroup).obj j :=
{ to_fun := limit.π (F ⋙ forget AddCommGroup) j,
map_zero' := by { simp only [types.types_limit_π], refl },
map_add' := λ x y, by { simp only [types.types_limit_π], refl } }
namespace AddCommGroup_has_limits
-- The next two definitions are used in the construction of `has_limits AddCommGroup`.
-- After that, the limits should be constructed using the generic limits API,
-- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`.
/--
Construction of a limit cone in `AddCommGroup`.
(Internal use only; use the limits API.)
-/
def limit (F : J ⥤ AddCommGroup) : cone F :=
{ X := ⟨limit (F ⋙ forget _), by apply_instance⟩,
π :=
{ app := limit_π_add_monoid_hom F,
naturality' := λ j j' f,
add_monoid_hom.coe_inj ((limit.cone (F ⋙ forget _)).π.naturality f) } }
/--
Witness that the limit cone in `AddCommGroup` is a limit cone.
(Internal use only; use the limits API.)
-/
def limit_is_limit (F : J ⥤ AddCommGroup) : is_limit (limit F) :=
begin
refine is_limit.of_faithful
(forget AddCommGroup) (limit.is_limit _)
(λ s, ⟨_, _, _⟩) (λ s, rfl); dsimp,
{ apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_zero, refl },
{ intros x y, apply subtype.eq, funext, dsimp,
erw (s.π.app j).map_add, refl }
end
end AddCommGroup_has_limits
open AddCommGroup_has_limits
/-- The category of abelian groups has all limits. -/
instance AddCommGroup_has_limits : has_limits AddCommGroup :=
{ has_limits_of_shape := λ J 𝒥,
{ has_limit := λ F, by exactI
{ cone := limit F,
is_limit := limit_is_limit F } } }
/--
The forgetful functor from abelian groups to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
instance forget_preserves_limits : preserves_limits (forget AddCommGroup) :=
{ preserves_limits_of_shape := λ J 𝒥,
{ preserves_limit := λ F,
by exactI preserves_limit_of_preserves_limit_cone
(limit.is_limit F) (limit.is_limit (F ⋙ forget _)) } }
end AddCommGroup
|
13e4fef6ada65b84d20e88e2133aeed37031cd8d | 130c49f47783503e462c16b2eff31933442be6ff | /src/Lean/Elab/Term.lean | 0485ca2229269849d27b965520c471a2efc635de | [
"Apache-2.0"
] | permissive | Hazel-Brown/lean4 | 8aa5860e282435ffc30dcdfccd34006c59d1d39c | 79e6732fc6bbf5af831b76f310f9c488d44e7a16 | refs/heads/master | 1,689,218,208,951 | 1,629,736,869,000 | 1,629,736,896,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,382 | 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, Sebastian Ullrich
-/
import Lean.ResolveName
import Lean.Util.Sorry
import Lean.Util.ReplaceExpr
import Lean.Structure
import Lean.Meta.ExprDefEq
import Lean.Meta.AppBuilder
import Lean.Meta.SynthInstance
import Lean.Meta.CollectMVars
import Lean.Meta.Coe
import Lean.Meta.Tactic.Util
import Lean.Hygiene
import Lean.Util.RecDepth
import Lean.Elab.Log
import Lean.Elab.Level
import Lean.Elab.Attributes
import Lean.Elab.AutoBound
import Lean.Elab.InfoTree
import Lean.Elab.Open
import Lean.Elab.SetOption
namespace Lean.Elab.Term
/-
Set isDefEq configuration for the elaborator.
Note that we enable all approximations but `quasiPatternApprox`
In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration.
The example:
```
def ex : StateT δ (StateT σ Id) σ :=
monadLift (get : StateT σ Id σ)
```
demonstrates why it produces counterintuitive behavior.
We have the `Monad-lift` application:
```
@monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α
```
It produces the following unification problem when we process the expected type:
```
?n ?α =?= StateT δ (StateT σ id) σ
==> (approximate using first-order unification)
?n := StateT δ (StateT σ id)
?α := σ
```
Then, we need to solve:
```
?m ?α =?= StateT σ id σ
==> instantiate metavars
?m σ =?= StateT σ id σ
==> (approximate since it is a quasi-pattern unification constraint)
?m := fun σ => StateT σ id σ
```
Note that the constraint is not a Milner pattern because σ is in
the local context of `?m`. We are ignoring the other possible solutions:
```
?m := fun σ' => StateT σ id σ
?m := fun σ' => StateT σ' id σ
?m := fun σ' => StateT σ id σ'
```
We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions).
If we had use first-order unification, then we would have produced
the right answer: `?m := StateT σ id`
Haskell would work on this example since it always uses
first-order unification.
-/
def setElabConfig (cfg : Meta.Config) : Meta.Config :=
{ cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false }
structure Context where
fileName : String
fileMap : FileMap
declName? : Option Name := none
macroStack : MacroStack := []
currMacroScope : MacroScope := firstFrontendMacroScope
/- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`.
The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in
the list of pending synthetic metavariables, and returns `?m`. -/
mayPostpone : Bool := true
/- When `errToSorry` is set to true, the method `elabTerm` catches
exceptions and converts them into synthetic `sorry`s.
The implementation of choice nodes and overloaded symbols rely on the fact
that when `errToSorry` is set to false for an elaboration function `F`, then
`errToSorry` remains `false` for all elaboration functions invoked by `F`.
That is, it is safe to transition `errToSorry` from `true` to `false`, but
we must not set `errToSorry` to `true` when it is currently set to `false`. -/
errToSorry : Bool := true
/- When `autoBoundImplicit` is set to true, instead of producing
an "unknown identifier" error for unbound variables, we generate an
internal exception. This exception is caught at `elabBinders` and
`elabTypeWithUnboldImplicit`. Both methods add implicit declarations
for the unbound variable and try again. -/
autoBoundImplicit : Bool := false
autoBoundImplicits : Std.PArray Expr := {}
/-- Map from user name to internal unique name -/
sectionVars : NameMap Name := {}
/-- Map from internal name to fvar -/
sectionFVars : NameMap Expr := {}
/-- Enable/disable implicit lambdas feature. -/
implicitLambda : Bool := true
/-- Saved context for postponed terms and tactics to be executed. -/
structure SavedContext where
declName? : Option Name
options : Options
openDecls : List OpenDecl
macroStack : MacroStack
errToSorry : Bool
/-- We use synthetic metavariables as placeholders for pending elaboration steps. -/
inductive SyntheticMVarKind where
-- typeclass instance search
| typeClass
/- Similar to typeClass, but error messages are different.
if `f?` is `some f`, we produce an application type mismatch error message.
Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)`
Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/
| coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr)
-- tactic block execution
| tactic (tacticCode : Syntax) (ctx : SavedContext)
-- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`)
| postponed (ctx : SavedContext)
instance : ToString SyntheticMVarKind where
toString
| SyntheticMVarKind.typeClass => "typeclass"
| SyntheticMVarKind.coe .. => "coe"
| SyntheticMVarKind.tactic .. => "tactic"
| SyntheticMVarKind.postponed .. => "postponed"
structure SyntheticMVarDecl where
mvarId : MVarId
stx : Syntax
kind : SyntheticMVarKind
inductive MVarErrorKind where
| implicitArg (ctx : Expr)
| hole
| custom (msgData : MessageData)
instance : ToString MVarErrorKind where
toString
| MVarErrorKind.implicitArg ctx => "implicitArg"
| MVarErrorKind.hole => "hole"
| MVarErrorKind.custom msg => "custom"
structure MVarErrorInfo where
mvarId : MVarId
ref : Syntax
kind : MVarErrorKind
structure LetRecToLift where
ref : Syntax
fvarId : FVarId
attrs : Array Attribute
shortDeclName : Name
declName : Name
lctx : LocalContext
localInstances : LocalInstances
type : Expr
val : Expr
mvarId : MVarId
structure State where
levelNames : List Name := []
syntheticMVars : List SyntheticMVarDecl := []
mvarErrorInfos : List MVarErrorInfo := []
messages : MessageLog := {}
letRecsToLift : List LetRecToLift := []
infoState : InfoState := {}
deriving Inhabited
abbrev TermElabM := ReaderT Context $ StateRefT State MetaM
abbrev TermElab := Syntax → Option Expr → TermElabM Expr
-- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the
-- whole monad stack at every use site. May eventually be covered by `deriving`.
instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind }
open Meta
instance : Inhabited (TermElabM α) where
default := throw arbitrary
structure SavedState where
meta : Meta.SavedState
«elab» : State
deriving Inhabited
protected def saveState : TermElabM SavedState := do
pure { meta := (← Meta.saveState), «elab» := (← get) }
def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do
let traceState ← getTraceState -- We never backtrack trace message
let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false`
s.meta.restore
set s.elab
setTraceState traceState
unless restoreInfo do
modify fun s => { s with infoState := infoState }
instance : MonadBacktrack SavedState TermElabM where
saveState := Term.saveState
restoreState b := b.restore
abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α
instance [Inhabited α] : Inhabited (TermElabResult α) where
default := EStateM.Result.ok arbitrary arbitrary
def setMessageLog (messages : MessageLog) : TermElabM Unit :=
modify fun s => { s with messages := messages }
def resetMessageLog : TermElabM Unit :=
setMessageLog {}
def getMessageLog : TermElabM MessageLog :=
return (← get).messages
/--
Execute `x`, save resulting expression and new state.
We remove any `Info` created by `x`.
The info nodes are committed when we execute `applyResult`.
We use `observing` to implement overloaded notation and decls.
We want to save `Info` nodes for the chosen alternative.
-/
def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do
let s ← saveState
try
let e ← x
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.ok e sNew)
catch
| ex@(Exception.error _ _) =>
let sNew ← saveState
s.restore (restoreInfo := true)
pure (EStateM.Result.error ex sNew)
| ex@(Exception.internal id _) =>
if id == postponeExceptionId then
s.restore (restoreInfo := true)
throw ex
/--
Apply the result/exception and state captured with `observing`.
We use this method to implement overloaded notation and symbols. -/
def applyResult (result : TermElabResult α) : TermElabM α :=
match result with
| EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a
| EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex
/--
Execute `x`, but keep state modifications only if `x` did not postpone.
This method is useful to implement elaboration functions that cannot decide whether
they need to postpone or not without updating the state. -/
def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do
-- We just reuse the implementation of `observing` and `applyResult`.
let r ← observing x
applyResult r
def getLevelNames : TermElabM (List Name) :=
return (← get).levelNames
def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do
match (← getLCtx).find? fvar.fvarId! with
| some d => pure d
| none => unreachable!
instance : AddErrorMessageContext TermElabM where
add ref msg := do
let ctx ← read
let ref := getBetterRef ref ctx.macroStack
let msg ← addMessageContext msg
let msg ← addMacroStack msg ctx.macroStack
pure (ref, msg)
instance : MonadLog TermElabM where
getRef := getRef
getFileMap := return (← read).fileMap
getFileName := return (← read).fileName
logMessage msg := do
let ctx ← readThe Core.Context
let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data };
modify fun s => { s with messages := s.messages.add msg }
protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope
protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule
protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do
let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 }))
withReader (fun ctx => { ctx with currMacroScope := fresh }) x
instance : MonadQuotation TermElabM where
getCurrMacroScope := Term.getCurrMacroScope
getMainModule := Term.getMainModule
withFreshMacroScope := Term.withFreshMacroScope
instance : MonadInfoTree TermElabM where
getInfoState := return (← get).infoState
modifyInfoState f := modify fun s => { s with infoState := f s.infoState }
/--
Execute `x` but discard changes performed at `Term.State` and `Meta.State`.
Recall that the environment is at `Core.State`. Thus, any updates to it will
be preserved. This method is useful for performing computations where all
metavariable must be resolved or discarded.
The info trees are not discarded, however, and wrapped in `InfoTree.Context`
to store their metavariable context. -/
def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do
let s ← get
let sMeta ← getThe Meta.State
try
withSaveInfoContext x
finally
modify ({ s with infoState := ·.infoState })
set sMeta
unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) :=
mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term"
@[implementedBy mkTermElabAttributeUnsafe]
constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab)
builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute
/--
Auxiliary datatatype for presenting a Lean lvalue modifier.
We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`.
Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list
`[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`.
Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/
inductive LVal where
| fieldIdx (ref : Syntax) (i : Nat)
/- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name.
`ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/
| fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax)
| getOp (ref : Syntax) (idx : Syntax)
def LVal.getRef : LVal → Syntax
| LVal.fieldIdx ref _ => ref
| LVal.fieldName ref .. => ref
| LVal.getOp ref _ => ref
def LVal.isFieldName : LVal → Bool
| LVal.fieldName .. => true
| _ => false
instance : ToString LVal where
toString
| LVal.fieldIdx _ i => toString i
| LVal.fieldName _ n .. => n
| LVal.getOp _ idx => "[" ++ toString idx ++ "]"
def getDeclName? : TermElabM (Option Name) := return (← read).declName?
def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift
def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId
def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId
def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val }
def withDeclName (name : Name) (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with declName? := name }) x
def setLevelNames (levelNames : List Name) : TermElabM Unit :=
modify fun s => { s with levelNames := levelNames }
def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do
let levelNamesSaved ← getLevelNames
setLevelNames levelNames
try x finally setLevelNames levelNamesSaved
def withoutErrToSorry (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with errToSorry := false }) x
/-- For testing `TermElabM` methods. The #eval command will sign the error. -/
def throwErrorIfErrors : TermElabM Unit := do
if (← get).messages.hasErrors then
throwError "Error(s)"
def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit :=
withRef Syntax.missing $ trace cls msg
def ppGoal (mvarId : MVarId) : TermElabM Format :=
Meta.ppGoal mvarId
open Level (LevelElabM)
def liftLevelM (x : LevelElabM α) : TermElabM α := do
let ctx ← read
let mctx ← getMCtx
let ngen ← getNGen
let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit }
match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with
| EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a
| EStateM.Result.error ex _ => throw ex
def elabLevel (stx : Syntax) : TermElabM Level :=
liftLevelM $ Level.elabLevel stx
/- Elaborate `x` with `stx` on the macro stack -/
def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α :=
withMacroExpansionInfo beforeStx afterStx do
withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x
/-
Add the given metavariable to the list of pending synthetic metavariables.
The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/
def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars }
def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do
registerSyntheticMVar (← getRef) mvarId kind
def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos }
def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos }
def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do
modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos }
def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit :=
match e.getAppFn with
| Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData
| _ => pure ()
/-
Auxiliary method for reporting errors of the form "... contains metavariables ...".
This kind of error is thrown, for example, at `Match.lean` where elaboration
cannot continue if there are metavariables in patterns.
We only want to log it if we haven't logged any error so far. -/
def throwMVarError (m : MessageData) : TermElabM α := do
if (← get).messages.hasErrors then
throwAbortTerm
else
throwError m
def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do
match mvarErrorInfo.kind with
| MVarErrorKind.implicitArg app => do
let app ← instantiateMVars app
let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (appendExtra msg)
| MVarErrorKind.hole => do
let msg : MessageData := "don't know how to synthesize placeholder"
let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId
logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg)
| MVarErrorKind.custom msg =>
logErrorAt mvarErrorInfo.ref (appendExtra msg)
where
appendExtra (msg : MessageData) : MessageData :=
match extraMsg? with
| none => msg
| some extraMsg => msg ++ extraMsg
/--
Try to log errors for the unassigned metavariables `pendingMVarIds`.
Return `true` if there were "unfilled holes", and we should "abort" declaration.
TODO: try to fill "all" holes using synthetic "sorry's"
Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/
def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do
let s ← get
let hasOtherErrors := s.messages.hasErrors
let mut hasNewErrors := false
let mut alreadyVisited : NameSet := {}
for mvarErrorInfo in s.mvarErrorInfos do
let mvarId := mvarErrorInfo.mvarId
unless alreadyVisited.contains mvarId do
alreadyVisited := alreadyVisited.insert mvarId
let foundError ← withMVarContext mvarId do
/- The metavariable `mvarErrorInfo.mvarId` may have been assigned or
delayed assigned to another metavariable that is unassigned. -/
let mvarDeps ← getMVars (mkMVar mvarId)
if mvarDeps.any pendingMVarIds.contains then do
unless hasOtherErrors do
mvarErrorInfo.logError extraMsg?
pure true
else
pure false
if foundError then
hasNewErrors := true
return hasNewErrors
/-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/
def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do
let pendingMVarIds ← getMVarsAtDecl decl
if (← logUnassignedUsingErrorInfos pendingMVarIds) then
throwAbortCommand
/-
Execute `x` without allowing it to postpone elaboration tasks.
That is, `tryPostpone` is a noop. -/
def withoutPostponing (x : TermElabM α) : TermElabM α :=
withReader (fun ctx => { ctx with mayPostpone := false }) x
/-- Creates syntax for `(` <ident> `:` <type> `)` -/
def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax :=
mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"]
/--
Convert unassigned universe level metavariables into parameters.
The new parameter names are of the form `u_i` where `i >= nextParamIdx`.
The method returns the updated expression and new `nextParamIdx`.
Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/
def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do
let mctx ← getMCtx
let levelNames ← getLevelNames
let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx
setMCtx r.mctx
pure (r.expr, r.nextParamIdx)
/-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/
def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do
let nextParamIdx ← get
let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx
set nextParamIdx
pure e
/--
Auxiliary method for creating fresh binder names.
Do not confuse with the method for creating fresh free/meta variable ids. -/
def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name :=
withFreshMacroScope $ MonadQuotation.addMacroScope `x
/--
Auxiliary method for creating a `Syntax.ident` containing
a fresh name. This method is intended for creating fresh binder names.
It is just a thin layer on top of `mkFreshUserName`. -/
def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax :=
return mkIdentFrom ref (← mkFreshBinderName)
private def applyAttributesCore
(declName : Name) (attrs : Array Attribute)
(applicationTime? : Option AttributeApplicationTime) : TermElabM Unit :=
for attr in attrs do
let env ← getEnv
match getAttributeImpl env attr.name with
| Except.error errMsg => throwError errMsg
| Except.ok attrImpl =>
match applicationTime? with
| none => attrImpl.add declName attr.stx attr.kind
| some applicationTime =>
if applicationTime == attrImpl.applicationTime then
attrImpl.add declName attr.stx attr.kind
/-- Apply given attributes **at** a given application time -/
def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit :=
applyAttributesCore declName attrs applicationTime
def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit :=
applyAttributesCore declName attrs none
def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do
let header : MessageData := match header? with
| some header => m!"{header} "
| none => m!"type mismatch{indentExpr e}\n"
return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}"
def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do
/-
We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was
always of the form:
```
failed to synthesize instance
CoeT <eType> <e> <expectedType>
```
We should revisit this decision in the future and decide whether it may contain useful information
or not. -/
let extraMsg := Format.nil
/-
let extraMsg : MessageData := match extraMsg? with
| none => Format.nil
| some extraMsg => Format.line ++ extraMsg;
-/
match f? with
| none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}"
| some f => Meta.throwAppTypeMismatch f e extraMsg
def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α :=
withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x
namespace ContainsPendingMVar
abbrev M := MonadCacheT Expr Unit (OptionT TermElabM)
/-- See `containsPostponedTerm` -/
partial def visit (e : Expr) : M Unit := do
checkCache e fun _ => do
match e with
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a _ => visit f; visit a
| Expr.mdata _ b _ => visit b
| Expr.proj _ _ b _ => visit b
| Expr.fvar fvarId .. =>
match (← getLocalDecl fvarId) with
| LocalDecl.cdecl .. => return ()
| LocalDecl.ldecl (value := v) .. => visit v
| Expr.mvar mvarId .. =>
let e' ← instantiateMVars e
if e' != e then
visit e'
else
match (← getDelayedAssignment? mvarId) with
| some d => visit d.val
| none => failure
| _ => return ()
end ContainsPendingMVar
/-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/
def containsPendingMVar (e : Expr) : TermElabM Bool := do
match (← ContainsPendingMVar.visit e |>.run.run) with
| some _ => return false
| none => return true
/- Try to synthesize metavariable using type class resolution.
This method assumes the local context and local instances of `instMVar` coincide
with the current local context and local instances.
Return `true` if the instance was synthesized successfully, and `false` if
the instance contains unassigned metavariables that are blocking the type class
resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/
def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do
let instMVarDecl ← getMVarDecl instMVar
let type := instMVarDecl.type
let type ← instantiateMVars type
let result ← trySynthInstance type maxResultSize?
match result with
| LOption.some val =>
if (← isExprMVarAssigned instMVar) then
let oldVal ← instantiateMVars (mkMVar instMVar)
unless (← isDefEq oldVal val) do
if (← containsPendingMVar oldVal <||> containsPendingMVar val) then
/- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration),
we return `false` to indicate we should try again later. This is very course grain since
the metavariable may not be responsible for the failure. We should refine the test in the future if needed.
This check has been added to address dependencies between postponed metavariables. The following
example demonstrates the issue fixed by this test.
```
structure Point where
x : Nat
y : Nat
def Point.compute (p : Point) : Point :=
let p := { p with x := 1 }
let p := { p with y := 0 }
if (p.x - p.y) > p.x then p else p
```
The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to
`p` has not been elaborated yet.
-/
return false -- we will try again later
let oldValType ← inferType oldVal
let valType ← inferType val
unless (← isDefEq oldValType valType) do
throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}"
throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}"
else
unless (← isDefEq (mkMVar instMVar) val) do
throwError "failed to assign synthesized type class instance{indentExpr val}"
pure true
| LOption.undef => pure false -- we will try later
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
register_builtin_option autoLift : Bool := {
defValue := true
descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed"
}
register_builtin_option maxCoeSize : Nat := {
defValue := 16
descr := "maximum number of instances used to construct an automatic coercion"
}
def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do
synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions)))
/-
The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would
eagerly evaluate `e` -/
def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do
match expectedType with
| Expr.app (Expr.const ``Thunk u _) arg _ =>
if (← isDefEq eType arg) then
pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e)))
else
pure none
| _ =>
pure none
def mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let u ← getLevel eType
let v ← getLevel expectedType
let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType]
let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic
let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar]
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
expandCoe eNew
else
-- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe`
-- after we syntheze `mvar`
let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque
registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?)
return mvarAux
catch
| Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg
| _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f?
/--
Try to apply coercion to make sure `e` has type `expectedType`.
Relevant definitions:
```
class CoeT (α : Sort u) (a : α) (β : Sort v)
abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β
```
-/
private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
if (← isDefEq expectedType eType) then
return e
else match (← tryCoeThunk? expectedType eType e) with
| some r => return r
| none => mkCoe expectedType eType e f? errorMsgHeader?
def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do
let type ← withReducible $ whnf type
match type with
| Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α)))
| _ => pure none
def synthesizeInst (type : Expr) : TermElabM Expr := do
let type ← instantiateMVars type
match (← trySynthInstance type) with
| LOption.some val => pure val
| LOption.undef => throwError "failed to synthesize instance{indentExpr type}"
| LOption.none => throwError "failed to synthesize instance{indentExpr type}"
def isMonadApp (type : Expr) : TermElabM Bool := do
let some (m, _) ← isTypeApp? type | pure false
return (← isMonad? m) |>.isSome
/--
Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`.
The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol
of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`).
The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism
do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y`
since none of them is polymorphic
```
def f (x : Bool) : IO Bool := do
let y ← if x == 0 then IO.println "hello"; true else false;
!y
```
On the other hand, the following fails since `+` is polymorphic
```
def f (x : Bool) : IO Nat := do
IO.prinln x
x + x -- Error: failed to synthesize `Add (IO Nat)`
```
-/
private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) :=
commitWhenSome? do
let doIt : TermElabM (Option Expr) := do
try
let aNew ← tryCoe errorMsgHeader? β α a none
let aNew ← mkPure m aNew
pure (some aNew)
catch _ =>
pure none
forallTelescope α fun _ α => do
if (← isMonadApp α) then
pure none
else if !α.getAppFn.isMVar then
doIt
else
pure none
/-
Try coercions and monad lifts to make sure `e` has type `expectedType`.
If `expectedType` is of the form `n β`, we try monad lifts and other extensions.
Otherwise, we just use the basic `tryCoe`.
Extensions for monads.
Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α`
1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`.
It only works if `n` implements `Pure`
If `eType` is of the form `m α`. We use the following approaches.
1- Try to unify `n` and `m`. If it succeeds, then we use
```
coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β
```
`n` must be a `Monad` to use this one.
2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use
```
liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α
```
Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as
```
def g (x : Nat) : IO Nat := do
IO.println x
pure x
def f {m} [MonadLiftT IO m] : m Nat :=
g 10
```
3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use
```
liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β
```
Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`.
This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and
we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)`
using the instance `pureCoeDepProp`.
Note that, approach 2 is more powerful than `tryCoe`.
Recall that type class resolution never assigns metavariables created by other modules.
Now, consider the following scenario
```lean
def g (x : Nat) : IO Nat := ...
deg h (x : Nat) : StateT Nat IO Nat := do
v ← g x;
IO.Println v;
...
```
Let's assume there is no other occurrence of `v` in `h`.
Thus, we have that the expected of `g x` is `StateT Nat IO ?α`,
and the given type is `IO Nat`. So, even if we add a coercion.
```
instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ...
```
It is not applicable because TC would have to assign `?α := Nat`.
On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]`
since this goal does not contain any metavariables. And then, we
convert `g x` into `liftM $ g x`.
-/
private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do
let expectedType ← instantiateMVars expectedType
let eType ← instantiateMVars eType
let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f?
let tryCoeSimple : TermElabM Expr :=
tryCoe errorMsgHeader? expectedType eType e f?
let some (n, β) ← isTypeApp? expectedType | tryCoeSimple
let tryPureCoeAndSimple : TermElabM Expr := do
if autoLift.get (← getOptions) then
match (← tryPureCoe? errorMsgHeader? n β eType e) with
| some eNew => pure eNew
| none => tryCoeSimple
else
tryCoeSimple
let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple
if (← isDefEq m n) then
let some monadInst ← isMonad? n | tryCoeSimple
try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch
else if autoLift.get (← getOptions) then
try
-- Construct lift from `m` to `n`
let monadLiftType ← mkAppM ``MonadLiftT #[m, n]
let monadLiftVal ← synthesizeInst monadLiftType
let u_1 ← getDecLevel α
let u_2 ← getDecLevel eType
let u_3 ← getDecLevel expectedType
let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e]
let eNewType ← inferType eNew
if (← isDefEq expectedType eNewType) then
return eNew -- approach 2 worked
else
let some monadInst ← isMonad? n | tryCoeSimple
let u ← getLevel α
let v ← getLevel β
let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β]
let coeTInstVal ← synthesizeInst coeTInstType
let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e])
let eNewType ← inferType eNew
unless (← isDefEq expectedType eNewType) do throwMismatch
return eNew -- approach 3 worked
catch _ =>
/-
If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`.
Otherwise, we just try `tryCoe?`.
-/
match (← isMonad? m) with
| none => tryPureCoeAndSimple
| some _ => tryCoeSimple
else
tryCoeSimple
/--
If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal.
If they are not, then try coercions.
Argument `f?` is used only for generating error messages. -/
def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr)
(f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
match expectedType? with
| none => pure e
| some expectedType =>
if (← isDefEq eType expectedType) then
pure e
else
tryLiftAndCoe errorMsgHeader? expectedType eType e f?
/--
If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal.
If they are not, then try coercions. -/
def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr :=
match expectedType? with
| none => pure e
| _ => do
let eType ← inferType e
ensureHasTypeAux expectedType? eType e none errorMsgHeader?
private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do
let expectedType ← match expectedType? with
| none => mkFreshTypeMVar
| some expectedType => pure expectedType
mkSyntheticSorry expectedType
private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do
let syntheticSorry ← mkSyntheticSorryFor expectedType?
logException ex
pure syntheticSorry
/-- If `mayPostpone == true`, throw `Expection.postpone`. -/
def tryPostpone : TermElabM Unit := do
if (← read).mayPostpone then
throwPostpone
/-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/
def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do
if e.getAppFn.isMVar then
let e ← instantiateMVars e
if e.getAppFn.isMVar then
tryPostpone
def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit :=
match e? with
| some e => tryPostponeIfMVar e
| none => tryPostpone
def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do
tryPostponeIfNoneOrMVar expectedType?
let some expectedType ← pure expectedType? |
throwError "{msg}, expected type must be known"
let expectedType ← instantiateMVars expectedType
if expectedType.hasExprMVar then
tryPostpone
throwError "{msg}, expected type contains metavariables{indentExpr expectedType}"
pure expectedType
def saveContext : TermElabM SavedContext :=
return {
macroStack := (← read).macroStack
declName? := (← read).declName?
options := (← getOptions)
openDecls := (← getOpenDecls)
errToSorry := (← read).errToSorry
}
def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <|
withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls })
x
private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do
trace[Elab.postpone] "{stx} : {expectedType?}"
let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque
let ctx ← read
registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext))
pure mvar
def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) :=
return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId
def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do
let isHole? : TermElabM (Option MVarId) := do
match e with
| Expr.mvar mvarId _ =>
match (← getSyntheticMVarDecl? mvarId) with
| some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId
| some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId
| _ => return none
| _ => pure none
match (← isHole?) with
| none => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder }
| some mvarId => return Sum.inr mvarId
def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do
withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard
/-
Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or
an error is found. -/
private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool)
: List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr
| [] => do throwError "unexpected syntax{indentD stx}"
| (elabFn::elabFns) =>
try
-- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`)
withInfoContext' (mkInfo := mkTermInfo elabFn.decl (expectedType? := expectedType?) stx)
(try
elabFn.value stx expectedType?
catch ex => match ex with
| Exception.error ref msg =>
if (← read).errToSorry then
exceptionToSorry ex expectedType?
else
throw ex
| Exception.internal id _ =>
if (← read).errToSorry && id == abortTermExceptionId then
exceptionToSorry ex expectedType?
else if id == unsupportedSyntaxExceptionId then
throw ex -- to outer try
else if catchExPostpone && id == postponeExceptionId then
/- If `elab` threw `Exception.postpone`, we reset any state modifications.
For example, we want to make sure pending synthetic metavariables created by `elab` before
it threw `Exception.postpone` are discarded.
Note that we are also discarding the messages created by `elab`.
For example, consider the expression.
`((f.x a1).x a2).x a3`
Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`.
Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone`
because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and
finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would
keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is
wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch
and new metavariables are created for the nested functions. -/
s.restore
postponeElabTerm stx expectedType?
else
throw ex)
catch ex => match ex with
| Exception.internal id _ =>
if id == unsupportedSyntaxExceptionId then
s.restore -- also removes the info tree created above
elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
else
throw ex
| _ => throw ex
private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do
let s ← saveState
let k := stx.getKind
match termElabAttribute.getEntries (← getEnv) k with
| [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}"
| elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns
instance : MonadMacroAdapter TermElabM where
getCurrMacroScope := getCurrMacroScope
getNextMacroScope := return (← getThe Core.State).nextMacroScope
setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next }
private def isExplicit (stx : Syntax) : Bool :=
match stx with
| `(@$f) => true
| _ => false
private def isExplicitApp (stx : Syntax) : Bool :=
stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0]
/--
Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation.
Example: `fun {α} (a : α) => a` -/
private def isLambdaWithImplicit (stx : Syntax) : Bool :=
match stx with
| `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder
| _ => false
private partial def dropTermParens : Syntax → Syntax := fun stx =>
match stx with
| `(($stx)) => dropTermParens stx
| _ => stx
private def isHole (stx : Syntax) : Bool :=
match stx with
| `(_) => true
| `(? _) => true
| `(? $x:ident) => true
| _ => false
private def isTacticBlock (stx : Syntax) : Bool :=
match stx with
| `(by $x:tacticSeq) => true
| _ => false
private def isNoImplicitLambda (stx : Syntax) : Bool :=
match stx with
| `(noImplicitLambda% $x:term) => true
| _ => false
private def isTypeAscription (stx : Syntax) : Bool :=
match stx with
| `(($e : $type)) => true
| _ => false
def mkNoImplicitLambdaAnnotation (type : Expr) : Expr :=
mkAnnotation `noImplicitLambda type
def hasNoImplicitLambdaAnnotation (type : Expr) : Bool :=
annotation? `noImplicitLambda type |>.isSome
/-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/
def blockImplicitLambda (stx : Syntax) : Bool :=
let stx := dropTermParens stx
-- TODO: make it extensible
isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx ||
isNoImplicitLambda stx || isTypeAscription stx
/--
Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and
`blockImplicitLambda stx` is not true, else return `none`.
Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β`
-/
private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) :=
if blockImplicitLambda stx then
return none
else match expectedType? with
| some expectedType => do
if hasNoImplicitLambdaAnnotation expectedType then
return none
else
let expectedType ← whnfForall expectedType
match expectedType with
| Expr.forallE _ _ _ c =>
if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then
return some expectedType
else
return none
| _ => return none
| _ => return none
private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do
match ex with
| Exception.error ref msg =>
if impFVars.isEmpty then
return Exception.error ref msg
else
let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature"
for impFVar in impFVars do
let auxMsg := m!"{impFVar} : {← inferType impFVar}"
let auxMsg ← addMessageContext auxMsg
msg := m!"{msg}{indentD auxMsg}"
msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations."
return Exception.error ref msg
| _ => return ex
private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do
let body ← elabUsingElabFns stx expectedType catchExPostpone
try
let body ← ensureHasType expectedType body
let r ← mkLambdaFVars impFVars body
trace[Elab.implicitForall] r
pure r
catch ex =>
throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars)
private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr :=
loop type #[]
where
loop
| type@(Expr.forallE n d b c), fvars =>
if c.binderInfo.isExplicit then
elabImplicitLambdaAux stx catchExPostpone type fvars
else withFreshMacroScope do
let n ← MonadQuotation.addMacroScope n
withLocalDecl n c.binderInfo d fun fvar => do
let type ← whnfForall (b.instantiate1 fvar)
loop type (fvars.push fvar)
| type, fvars =>
elabImplicitLambdaAux stx catchExPostpone type fvars
/- Main loop for `elabTerm` -/
private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr
| Syntax.missing => mkSyntheticSorryFor expectedType?
| stx => withFreshMacroScope <| withIncRecDepth do
trace[Elab.step] "expected type: {expectedType?}, term\n{stx}"
checkMaxHeartbeats "elaborator"
withNestedTraces do
let env ← getEnv
match (← liftMacroM (expandMacroImpl? env stx)) with
| some (decl, stxNew) =>
withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <|
withMacroExpansion stx stxNew <|
withRef stxNew <|
elabTermAux expectedType? catchExPostpone implicitLambda stxNew
| _ =>
let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none
match implicit? with
| some expectedType => elabImplicitLambda stx catchExPostpone expectedType
| none => elabUsingElabFns stx expectedType? catchExPostpone
/-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/
def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do
addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?)
/--
Main function for elaborating terms.
It extracts the elaboration methods from the environment using the node kind.
Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods.
It creates a fresh macro scope for executing the elaboration method.
All unlogged trace messages produced by the elaboration method are logged using
the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`,
the error is logged and a synthetic sorry expression is returned.
If the elaboration throws `Exception.postpone` and `catchExPostpone == true`,
a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered,
and returned.
The option `catchExPostpone == false` is used to implement `resumeElabTerm`
to prevent the creation of another synthetic metavariable when resuming the elaboration.
If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms.
We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect.
-/
def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr :=
withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx
def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do
let e ← elabTerm stx expectedType? catchExPostpone implicitLambda
withRef stx <| ensureHasType expectedType? e errorMsgHeader?
/-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/
def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do
let saved ← saveState
modify fun s => { s with messages := {} }
try
let a ← x
if (← get).messages.hasErrors then
restoreState saved
return none
else
modify fun s => { s with messages := saved.elab.messages ++ s.messages }
return a
catch _ =>
restoreState saved
return none
/-- Adapt a syntax transformation to a regular, term-producing elaborator. -/
def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do
let stx' ← exp stx
withMacroExpansion stx stx' $ elabTerm stx' expectedType?
def mkInstMVar (type : Expr) : TermElabM Expr := do
let mvar ← mkFreshExprMVar type MetavarKind.synthetic
let mvarId := mvar.mvarId!
unless (← synthesizeInstMVarCore mvarId) do
registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass
pure mvar
/-
Relevant definitions:
```
class CoeSort (α : Sort u) (β : outParam (Sort v))
abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β
```
-/
private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do
let β ← mkFreshTypeMVar
let u ← getLevel α
let v ← getLevel β
let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β]
let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic
let mvarId := mvar.mvarId!
try
withoutMacroStackAtErr do
if (← synthesizeCoeInstMVarCore mvarId) then
let result ← expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar]
unless (← isType result) do
throwError "failed to coerse{indentExpr a}\nto a type, after applying `coeSort`, result is still not a type{indentExpr result}\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\nwas{indentExpr mvar}"
return result
else
throwError "type expected"
catch
| Exception.error _ msg => throwError "type expected\n{msg}"
| _ => throwError "type expected"
/--
Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort`
or is unifiable with `Expr.sort`, or can be coerced into one. -/
def ensureType (e : Expr) : TermElabM Expr := do
if (← isType e) then
pure e
else
let eType ← inferType e
let u ← mkFreshLevelMVar
if (← isDefEq eType (mkSort u)) then
pure e
else
tryCoeSort eType e
/-- Elaborate `stx` and ensure result is a type. -/
def elabType (stx : Syntax) : TermElabM Expr := do
let u ← mkFreshLevelMVar
let type ← elabTerm stx (mkSort u)
withRef stx $ ensureType type
/--
Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught,
a new local declaration is created, registered, and `k` is tried to be executed again. -/
partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
let flag := autoBoundImplicitLocal.get (← getOptions)
if flag then
withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do
let rec loop (s : SavedState) : TermElabM α := do
try
k
catch
| ex => match isAutoBoundImplicitLocalException? ex with
| some n =>
-- Restore state, declare `n`, and try again
s.restore
withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x =>
withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do
loop (← saveState)
| none => throw ex
loop (← saveState)
else
k
def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do
withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k
/--
Return `autoBoundImplicits ++ xs.
This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/
def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do
let autoBoundImplicits := (← read).autoBoundImplicits
for auto in autoBoundImplicits do
let localDecl ← getLocalDecl auto.fvarId!
for x in xs do
if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then
throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'"
return autoBoundImplicits.toArray ++ xs
def mkAuxName (suffix : Name) : TermElabM Name := do
match (← read).declName? with
| none => throwError "auxiliary declaration cannot be created when declaration name is not available"
| some declName => Lean.mkAuxName (declName ++ suffix) 1
builtin_initialize registerTraceClass `Elab.letrec
/- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it
is delayed assigned to one. -/
def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do
trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}"
let mvarId := (← getMCtx).getDelayedRoot mvarId
trace[Elab.letrec] "mvarId root: {mkMVar mvarId}"
return (← get).letRecsToLift.any (·.mvarId == mvarId)
def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do
let lctx ← getLCtx
let view := extractMacroScopes n
let rec loop (n : Name) (projs : List String) :=
match lctx.findFromUserName? { view with name := n }.review with
| some decl =>
if decl.isAuxDecl && !projs.isEmpty then
/- We do not consider dot notation for local decls corresponding to recursive functions being defined.
The following example would not be elaborated correctly without this case.
```
def foo.aux := 1
def foo : Nat → Nat
| n => foo.aux -- should not be interpreted as `(foo).bar`
```
-/
none
else
some (decl.toExpr, projs)
| none => match n with
| Name.str pre s _ => loop pre (s::projs)
| _ => none
return loop view.name []
/- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/
def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val _ => do
let r? ← resolveLocalName val
match r? with
| some (fvar, []) => pure (some fvar)
| _ => pure none
| _ => pure none
/--
Create an `Expr.const` using the given name and explicit levels.
Remark: fresh universe metavariables are created if the constant has more universe
parameters than `explicitLevels`. -/
def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do
let cinfo ← getConstInfo constName
if explicitLevels.length > cinfo.levelParams.length then
throwError "too many explicit universe levels for '{constName}'"
else
let numMissingLevels := cinfo.levelParams.length - explicitLevels.length
let us ← mkFreshLevelMVars numMissingLevels
pure $ Lean.mkConst constName (explicitLevels ++ us)
private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do
candidates.foldlM (init := []) fun result (constName, projs) => do
-- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail.
let const ← mkConst constName explicitLevels
return (const, projs) :: result
def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do
try
if let some (e, projs) ← resolveLocalName n then
unless explicitLevels.isEmpty do
throwError "invalid use of explicit universe parameters, '{e}' is a local"
return [(e, projs)]
-- check for section variable capture by a quotation
let ctx ← read
if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then
return [(e, projs)] -- section variables should shadow global decls
if preresolved.isEmpty then
process (← resolveGlobalName n)
else
process preresolved
catch ex =>
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
throw ex
where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do
if candidates.isEmpty then
if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then
throwAutoBoundImplicitLocal n
else
throwError "unknown identifier '{Lean.mkConst n}'"
if preresolved.isEmpty && explicitLevels.isEmpty then
addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType?
mkConsts candidates explicitLevels
/--
Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`.
Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces
`(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/
def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do
match ident with
| Syntax.ident info rawStr n preresolved =>
let r ← resolveName ident n preresolved explicitLevels expectedType?
r.mapM fun (c, fields) => do
let ids := ident.identComponents (nFields? := fields.length)
return (c, ids.head!, ids.tail!)
| _ => throwError "identifier expected"
def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) :=
match stx with
| Syntax.ident _ _ val preresolved => do
let rs ← try resolveName stx val preresolved [] catch _ => pure []
let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty
let fs := rs.map fun (f, _) => f
match fs with
| [] => pure none
| [f] =>
if withInfo then
addTermInfo stx f
pure (some f)
| _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}"
| _ => throwError "identifier expected"
private def mkSomeContext : Context := {
fileName := "<TermElabM>"
fileMap := arbitrary
}
def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) :=
withConfig setElabConfig (x ctx |>.run s)
@[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α :=
(·.1) <$> x.run ctx s
def TermElabM.toIO (x : TermElabM α)
(ctxCore : Core.Context) (sCore : Core.State)
(ctxMeta : Meta.Context) (sMeta : Meta.State)
(ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do
let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta
pure (a, sCore, sMeta, s)
instance [MetaEval α] : MetaEval (TermElabM α) where
eval env opts x _ :=
let x : TermElabM α := do
try x finally
let s ← get
s.messages.forM fun msg => do IO.println (← msg.toString)
MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext
unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α :=
withoutModifyingEnv do
let name ← mkFreshUserName `_tmp
let type ← inferType value
let type ← whnfD type
unless type.isConstOf typeName do
throwError "unexpected type at evalExpr{indentExpr type}"
let decl := Declaration.defnDecl {
name := name, levelParams := [], type := type,
value := value, hints := ReducibilityHints.opaque,
safety := DefinitionSafety.unsafe
}
ensureNoUnassignedMVars decl
addAndCompile decl
evalConst α name
private def throwStuckAtUniverseCnstr : TermElabM Unit := do
-- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property
let entries ← getPostponed
let mut found : Std.HashSet (Level × Level) := {}
let mut uniqueEntries := #[]
for entry in entries do
let mut lhs := entry.lhs
let mut rhs := entry.rhs
if Level.normLt rhs lhs then
(lhs, rhs) := (rhs, lhs)
unless found.contains (lhs, rhs) do
found := found.insert (lhs, rhs)
uniqueEntries := uniqueEntries.push entry
for i in [1:uniqueEntries.size] do
logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i])
throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0])
def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do
let postponed ← getResetPostponed
try
let a ← x
unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do
throwStuckAtUniverseCnstr
setPostponed postponed
return a
catch ex =>
setPostponed postponed
throw ex
end Term
builtin_initialize
registerTraceClass `Elab.postpone
registerTraceClass `Elab.coe
registerTraceClass `Elab.debug
export Term (TermElabM)
end Lean.Elab
|
9684be75f8575f04197f52b5170929c93b41ec18 | 737dc4b96c97368cb66b925eeea3ab633ec3d702 | /stage0/src/Lean/Meta/Tactic/Simp/Main.lean | ecea7956002ebe5bc91079e858c61df1bcc0457e | [
"Apache-2.0"
] | permissive | Bioye97/lean4 | 1ace34638efd9913dc5991443777b01a08983289 | bc3900cbb9adda83eed7e6affeaade7cfd07716d | refs/heads/master | 1,690,589,820,211 | 1,631,051,000,000 | 1,631,067,598,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,489 | 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.Tactic.Replace
import Lean.Meta.Tactic.Util
import Lean.Meta.Tactic.Clear
import Lean.Meta.Tactic.Simp.Types
import Lean.Meta.Tactic.Simp.Rewrite
namespace Lean.Meta
namespace Simp
builtin_initialize congrHypothesisExceptionId : InternalExceptionId ←
registerInternalExceptionId `congrHypothesisFailed
def throwCongrHypothesisFailed : MetaM α :=
throw <| Exception.internal congrHypothesisExceptionId
def Result.getProof (r : Result) : MetaM Expr := do
match r.proof? with
| some p => return p
| none => mkEqRefl r.expr
private def mkEqTrans (r₁ r₂ : Result) : MetaM Result := do
match r₁.proof? with
| none => return r₂
| some p₁ => match r₂.proof? with
| none => return { r₂ with proof? := r₁.proof? }
| some p₂ => return { r₂ with proof? := (← Meta.mkEqTrans p₁ p₂) }
def mkCongrFun (r : Result) (a : Expr) : MetaM Result :=
match r.proof? with
| none => return { expr := mkApp r.expr a, proof? := none }
| some h => return { expr := mkApp r.expr a, proof? := (← Meta.mkCongrFun h a) }
def mkCongr (r₁ r₂ : Result) : MetaM Result :=
let e := mkApp r₁.expr r₂.expr
match r₁.proof?, r₂.proof? with
| none, none => return { expr := e, proof? := none }
| some h, none => return { expr := e, proof? := (← Meta.mkCongrFun h r₂.expr) }
| none, some h => return { expr := e, proof? := (← Meta.mkCongrArg r₁.expr h) }
| some h₁, some h₂ => return { expr := e, proof? := (← Meta.mkCongr h₁ h₂) }
private def mkImpCongr (r₁ r₂ : Result) : MetaM Result := do
let e ← mkArrow r₁.expr r₂.expr
match r₁.proof?, r₂.proof? with
| none, none => return { expr := e, proof? := none }
| _, _ => return { expr := e, proof? := (← Meta.mkImpCongr (← r₁.getProof) (← r₂.getProof)) } -- TODO specialize if bootleneck
private def reduceProj (e : Expr) : MetaM Expr := do
match (← reduceProj? e) with
| some e => return e
| _ => return e
private def reduceProjFn? (e : Expr) : SimpM (Option Expr) := do
matchConst e.getAppFn (fun _ => pure none) fun cinfo _ => do
match (← getProjectionFnInfo? cinfo.name) with
| none => return none
| some projInfo =>
if projInfo.fromClass then
if (← read).simpLemmas.isDeclToUnfold cinfo.name then
-- We only unfold class projections when the user explicitly requested them to be unfolded.
-- Recall that `unfoldDefinition?` has support for unfolding this kind of projection.
withReducibleAndInstances <| unfoldDefinition? e
else
return none
else
-- `structure` projection
match (← unfoldDefinition? e) with
| none => pure none
| some e =>
match (← reduceProj? e.getAppFn) with
| some f => return some (mkAppN f e.getAppArgs)
| none => return none
private def reduceFVar (cfg : Config) (e : Expr) : MetaM Expr := do
if cfg.zeta then
match (← getFVarLocalDecl e).value? with
| some v => return v
| none => return e
else
return e
private def unfold? (e : Expr) : SimpM (Option Expr) := do
let f := e.getAppFn
if !f.isConst then
return none
let fName := f.constName!
if (← isProjectionFn fName) then
return none -- should be reduced by `reduceProjFn?`
if (← read).simpLemmas.isDeclToUnfold e.getAppFn.constName! then
withDefault <| unfoldDefinition? e
else
return none
private partial def reduce (e : Expr) : SimpM Expr := withIncRecDepth do
let cfg := (← read).config
if cfg.beta then
let e' := e.headBeta
if e' != e then
return (← reduce e')
-- TODO: eta reduction
if cfg.proj then
match (← reduceProjFn? e) with
| some e => return (← reduce e)
| none => pure ()
if cfg.iota then
match (← reduceRecMatcher? e) with
| some e => return (← reduce e)
| none => pure ()
match (← unfold? e) with
| some e => reduce e
| none => return e
private partial def dsimp (e : Expr) : M Expr := do
transform e (post := fun e => return TransformStep.done (← reduce e))
partial def simp (e : Expr) : M Result := withIncRecDepth do
let cfg ← getConfig
if (← isProof e) then
return { expr := e }
if cfg.memoize then
if let some result := (← get).cache.find? e then
return result
simpLoop { expr := e }
where
simpLoop (r : Result) : M Result := do
let cfg ← getConfig
if (← get).numSteps > cfg.maxSteps then
throwError "simp failed, maximum number of steps exceeded"
else
let init := r.expr
modify fun s => { s with numSteps := s.numSteps + 1 }
match (← pre r.expr) with
| Step.done r => cacheResult cfg r
| Step.visit r' =>
let r ← mkEqTrans r r'
let r ← mkEqTrans r (← simpStep r.expr)
match (← post r.expr) with
| Step.done r' => cacheResult cfg (← mkEqTrans r r')
| Step.visit r' =>
let r ← mkEqTrans r r'
if cfg.singlePass || init == r.expr then
cacheResult cfg r
else
simpLoop r
simpStep (e : Expr) : M Result := do
match e with
| Expr.mdata _ e _ => simp e
| Expr.proj .. => pure { expr := (← reduceProj e) }
| Expr.app .. => simpApp e
| Expr.lam .. => simpLambda e
| Expr.forallE .. => simpForall e
| Expr.letE .. => simpLet e
| Expr.const .. => simpConst e
| Expr.bvar .. => unreachable!
| Expr.sort .. => pure { expr := e }
| Expr.lit .. => pure { expr := e }
| Expr.mvar .. => pure { expr := (← instantiateMVars e) }
| Expr.fvar .. => pure { expr := (← reduceFVar (← getConfig) e) }
congrDefault (e : Expr) : M Result :=
withParent e <| e.withApp fun f args => do
let infos := (← getFunInfoNArgs f args.size).paramInfo
let mut r ← simp f
let mut i := 0
for arg in args do
trace[Debug.Meta.Tactic.simp] "app [{i}] {infos.size} {arg} hasFwdDeps: {infos[i].hasFwdDeps}"
if i < infos.size && !infos[i].hasFwdDeps then
r ← mkCongr r (← simp arg)
else if (← whnfD (← inferType r.expr)).isArrow then
r ← mkCongr r (← simp arg)
else
r ← mkCongrFun r (← dsimp arg)
i := i + 1
return r
/- Return true iff processing the given congruence lemma hypothesis produced a non-refl proof. -/
processCongrHypothesis (h : Expr) : M Bool := do
forallTelescopeReducing (← inferType h) fun xs hType => withNewLemmas xs do
let lhs ← instantiateMVars hType.appFn!.appArg!
let r ← simp lhs
let rhs := hType.appArg!
rhs.withApp fun m zs => do
let val ← mkLambdaFVars zs r.expr
unless (← isDefEq m val) do
throwCongrHypothesisFailed
unless (← isDefEq h (← mkLambdaFVars xs (← r.getProof))) do
throwCongrHypothesisFailed
return r.proof?.isSome
/- Try to rewrite `e` children using the given congruence lemma -/
tryCongrLemma? (c : CongrLemma) (e : Expr) : M (Option Result) := withNewMCtxDepth do
trace[Debug.Meta.Tactic.simp.congr] "{c.theoremName}, {e}"
let lemma ← mkConstWithFreshMVarLevels c.theoremName
let (xs, bis, type) ← forallMetaTelescopeReducing (← inferType lemma)
if c.hypothesesPos.any (· ≥ xs.size) then
return none
let lhs := type.appFn!.appArg!
let rhs := type.appArg!
if (← isDefEq lhs e) then
let mut modified := false
for i in c.hypothesesPos do
let x := xs[i]
try
if (← processCongrHypothesis x) then
modified := true
catch _ =>
trace[Meta.Tactic.simp.congr] "processCongrHypothesis {c.theoremName} failed {← inferType x}"
return none
unless modified do
trace[Meta.Tactic.simp.congr] "{c.theoremName} not modified"
return none
unless (← synthesizeArgs c.theoremName xs bis (← read).discharge?) do
trace[Meta.Tactic.simp.congr] "{c.theoremName} synthesizeArgs failed"
return none
let eNew ← instantiateMVars rhs
let proof ← instantiateMVars (mkAppN lemma xs)
return some { expr := eNew, proof? := proof }
else
return none
congr (e : Expr) : M Result := do
let f := e.getAppFn
if f.isConst then
let congrLemmas ← getCongrLemmas
let cs := congrLemmas.get f.constName!
for c in cs do
match (← tryCongrLemma? c e) with
| none => pure ()
| some r => return r
congrDefault e
else
congrDefault e
simpApp (e : Expr) : M Result := do
let e ← reduce e
if !e.isApp then
simp e
else
congr e
simpConst (e : Expr) : M Result :=
return { expr := (← reduce e) }
withNewLemmas {α} (xs : Array Expr) (f : M α) : M α := do
if (← getConfig).contextual then
let mut s ← getSimpLemmas
let mut updated := false
for x in xs do
if (← isProof x) then
s ← s.add #[] x
updated := true
if updated then
withSimpLemmas s f
else
f
else
f
simpLambda (e : Expr) : M Result :=
withParent e <| lambdaTelescope e fun xs e => withNewLemmas xs do
let r ← simp e
let eNew ← mkLambdaFVars xs r.expr
match r.proof? with
| none => return { expr := eNew }
| some h =>
let p ← xs.foldrM (init := h) fun x h => do
mkFunExt (← mkLambdaFVars #[x] h)
return { expr := eNew, proof? := p }
simpArrow (e : Expr) : M Result := do
trace[Debug.Meta.Tactic.simp] "arrow {e}"
let p := e.bindingDomain!
let q := e.bindingBody!
let rp ← simp p
trace[Debug.Meta.Tactic.simp] "arrow [{(← getConfig).contextual}] {p} [{← isProp p}] -> {q} [{← isProp q}]"
if (← (← getConfig).contextual <&&> isProp p <&&> isProp q) then
trace[Debug.Meta.Tactic.simp] "ctx arrow {rp.expr} -> {q}"
withLocalDeclD e.bindingName! rp.expr fun h => do
let s ← getSimpLemmas
let s ← s.add #[] h
withSimpLemmas s do
let rq ← simp q
match rq.proof? with
| none => mkImpCongr rp rq
| some hq =>
let hq ← mkLambdaFVars #[h] hq
return { expr := (← mkArrow rp.expr rq.expr), proof? := (← mkImpCongrCtx (← rp.getProof) hq) }
else
mkImpCongr rp (← simp q)
simpForall (e : Expr) : M Result := withParent e do
trace[Debug.Meta.Tactic.simp] "forall {e}"
if e.isArrow then
simpArrow e
else if (← isProp e) then
withLocalDecl e.bindingName! e.bindingInfo! e.bindingDomain! fun x => withNewLemmas #[x] do
let b := e.bindingBody!.instantiate1 x
let rb ← simp b
let eNew ← mkForallFVars #[x] rb.expr
match rb.proof? with
| none => return { expr := eNew }
| some h => return { expr := eNew, proof? := (← mkForallCongr (← mkLambdaFVars #[x] h)) }
else
return { expr := (← dsimp e) }
simpLet (e : Expr) : M Result := do
if (← getConfig).zeta then
match e with
| Expr.letE _ _ v b _ => return { expr := b.instantiate1 v }
| _ => unreachable!
else
-- TODO: simplify nondependent let-decls
return { expr := (← dsimp e) }
cacheResult (cfg : Config) (r : Result) : M Result := do
if cfg.memoize then
modify fun s => { s with cache := s.cache.insert e r }
return r
def main (e : Expr) (ctx : Context) (methods : Methods := {}) : MetaM Result := do
withReducible do
simp e methods ctx |>.run' {}
abbrev Discharge := Expr → SimpM (Option Expr)
namespace DefaultMethods
mutual
partial def discharge? (e : Expr) : SimpM (Option Expr) := do
let ctx ← read
if ctx.dischargeDepth >= ctx.config.maxDischargeDepth then
trace[Meta.Tactic.simp.discharge] "maximum discharge depth has been reached"
return none
else
withReader (fun ctx => { ctx with dischargeDepth := ctx.dischargeDepth + 1 }) do
let r ← simp e methods
if r.expr.isConstOf ``True then
try
return some (← mkOfEqTrue (← r.getProof))
catch _ =>
return none
else
return none
partial def pre (e : Expr) : SimpM Step :=
preDefault e discharge?
partial def post (e : Expr) : SimpM Step :=
postDefault e discharge?
partial def methods : Methods :=
{ pre := pre, post := post, discharge? := discharge? }
end
end DefaultMethods
end Simp
def simp (e : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM Simp.Result := do profileitM Exception "simp" (← getOptions) do
match discharge? with
| none => Simp.main e ctx (methods := Simp.DefaultMethods.methods)
| some d => Simp.main e ctx (methods := { pre := (Simp.preDefault . d), post := (Simp.postDefault . d), discharge? := d })
/-- See `simpTarget`. This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def simpTargetCore (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) := do
let target ← instantiateMVars (← getMVarType mvarId)
let r ← simp target ctx discharge?
if r.expr.isConstOf ``True then
match r.proof? with
| some proof => assignExprMVar mvarId (← mkOfEqTrue proof)
| none => assignExprMVar mvarId (mkConst ``True.intro)
return none
else
match r.proof? with
| some proof => replaceTargetEq mvarId r.expr proof
| none =>
if target != r.expr then
replaceTargetDefEq mvarId r.expr
else
return mvarId
/--
Simplify the given goal target (aka type). Return `none` if the goal was closed. Return `some mvarId'` otherwise,
where `mvarId'` is the simplified new goal. -/
def simpTarget (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option MVarId) :=
withMVarContext mvarId do
checkNotAssigned mvarId `simp
simpTargetCore mvarId ctx discharge?
/--
Simplify `prop` (which is inhabited by `proof`). Return `none` if the goal was closed. Return `some (proof', prop')`
otherwise, where `proof' : prop'` and `prop'` is the simplified `prop`.
This method assumes `mvarId` is not assigned, and we are already using `mvarId`s local context. -/
def simpStep (mvarId : MVarId) (proof : Expr) (prop : Expr) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (Expr × Expr)) := do
let r ← simp prop ctx discharge?
if r.expr.isConstOf ``False then
match r.proof? with
| some eqProof => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) (← mkEqMP eqProof proof))
| none => assignExprMVar mvarId (← mkFalseElim (← getMVarType mvarId) proof)
return none
else
match r.proof? with
| some eqProof => return some ((← mkEqMP eqProof proof), r.expr)
| none =>
if r.expr != prop then
return some ((← mkExpectedTypeHint proof r.expr), r.expr)
else
return some (proof, r.expr)
def simpLocalDecl (mvarId : MVarId) (fvarId : FVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) : MetaM (Option (FVarId × MVarId)) := do
withMVarContext mvarId do
checkNotAssigned mvarId `simp
let localDecl ← getLocalDecl fvarId
let type ← instantiateMVars localDecl.type
match (← simpStep mvarId (mkFVar fvarId) type ctx discharge?) with
| none => return none
| some (value, type') =>
if type != type' then
let mvarId ← assert mvarId localDecl.userName type' value
let mvarId ← tryClear mvarId localDecl.fvarId
let (fvarId, mvarId) ← intro1P mvarId
return some (fvarId, mvarId)
else
return some (fvarId, mvarId)
abbrev FVarIdToLemmaId := NameMap Name
def simpGoal (mvarId : MVarId) (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (simplifyTarget : Bool := true) (fvarIdsToSimp : Array FVarId := #[]) (fvarIdToLemmaId : FVarIdToLemmaId := {}) : MetaM (Option (Array FVarId × MVarId)) := do
withMVarContext mvarId do
checkNotAssigned mvarId `simp
let mut mvarId := mvarId
let mut toAssert : Array Hypothesis := #[]
for fvarId in fvarIdsToSimp do
let localDecl ← getLocalDecl fvarId
let type ← instantiateMVars localDecl.type
let ctx ← match fvarIdToLemmaId.find? localDecl.fvarId with
| none => pure ctx
| some lemmaId => pure { ctx with simpLemmas := (← ctx.simpLemmas.eraseCore lemmaId) }
match (← simpStep mvarId (mkFVar fvarId) type ctx discharge?) with
| none => return none
| some (value, type) => toAssert := toAssert.push { userName := localDecl.userName, type := type, value := value }
if simplifyTarget then
match (← simpTarget mvarId ctx discharge?) with
| none => return none
| some mvarIdNew => mvarId := mvarIdNew
let (fvarIdsNew, mvarIdNew) ← assertHypotheses mvarId toAssert
let mvarIdNew ← tryClearMany mvarIdNew fvarIdsToSimp
return (fvarIdsNew, mvarIdNew)
end Lean.Meta
|
7eddcf5c61aee156eb23a344bc8975c82b18bd87 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/ring_theory/polynomial/cyclotomic/basic.lean | 13fb857418a7b1d4750f2671b3c6dbb0ec7c5759 | [
"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,543 | lean | /-
Copyright (c) 2020 Riccardo Brasca. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Riccardo Brasca
-/
import algebra.polynomial.big_operators
import analysis.complex.roots_of_unity
import data.polynomial.lifts
import field_theory.separable
import field_theory.splitting_field
import number_theory.arithmetic_function
import ring_theory.roots_of_unity
import field_theory.ratfunc
import algebra.ne_zero
/-!
# Cyclotomic polynomials.
For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic
polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies
over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then
this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R`
with coefficients in any ring `R`.
## Main definition
* `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`.
## Main results
* `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K`
comes from a polynomial with integer coefficients.
* `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`.
* `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`.
* `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for
`cyclotomic n R` over an abstract fraction field for `polynomial R`.
* `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible.
## Implementation details
Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting
results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is
not the standard one unless there is a primitive `n`th root of unity in `R`. For example,
`cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is
`R = ℂ`, we decided to work in general since the difficulties are essentially the same.
To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a
polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`.
To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in
`cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root
of unity `μ : K`, where `K` is a field of characteristic `0`.
-/
open_locale classical big_operators
noncomputable theory
universe u
namespace polynomial
section cyclotomic'
section is_domain
variables {R : Type*} [comm_ring R] [is_domain R]
/-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic
polynomial if there is a primitive `n`-th root of unity in `R`. -/
def cyclotomic' (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : polynomial R :=
∏ μ in primitive_roots n R, (X - C μ)
/-- The zeroth modified cyclotomic polyomial is `1`. -/
@[simp] lemma cyclotomic'_zero
(R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 0 R = 1 :=
by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero]
/-- The first modified cyclotomic polyomial is `X - 1`. -/
@[simp] lemma cyclotomic'_one
(R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 1 R = X - 1 :=
begin
simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one,
is_primitive_root.primitive_roots_one]
end
/-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/
@[simp] lemma cyclotomic'_two
(R : Type*) [comm_ring R] [is_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) :
cyclotomic' 2 R = X + 1 :=
begin
rw [cyclotomic'],
have prim_root_two : primitive_roots 2 R = {(-1 : R)},
{ apply finset.eq_singleton_iff_unique_mem.2,
split,
{ simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] },
{ intros x hx,
rw [mem_primitive_roots zero_lt_two] at hx,
exact is_primitive_root.eq_neg_one_of_two_right hx } },
simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one,
sub_neg_eq_add]
end
/-- `cyclotomic' n R` is monic. -/
lemma cyclotomic'.monic
(n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).monic :=
monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _
/-- `cyclotomic' n R` is different from `0`. -/
lemma cyclotomic'_ne_zero
(n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' n R ≠ 0 :=
(cyclotomic'.monic n R).ne_zero
/-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of
unity in `R`. -/
lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(cyclotomic' n R).nat_degree = nat.totient n :=
begin
rw [cyclotomic'],
rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)),
simp only [is_primitive_root.card_primitive_roots h, mul_one,
nat_degree_X_sub_C,
nat.cast_id, finset.sum_const, nsmul_eq_mul],
intros z hz,
exact X_sub_C_ne_zero z
end
/-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/
lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) :
(cyclotomic' n R).degree = nat.totient n :=
by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h]
/-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/
lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] :
(cyclotomic' n R).roots = (primitive_roots n R).val :=
by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) }
/-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ`
varies over the `n`-th roots of unity. -/
lemma X_pow_sub_one_eq_prod {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) :
X ^ n - 1 = ∏ ζ in nth_roots_finset n R, (X - C ζ) :=
begin
rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)],
simp only [finset.prod_mk, ring_hom.map_one],
rw [nth_roots],
have hmonic : (X ^ n - C (1 : R)).monic := monic_X_pow_sub_C (1 : R) (ne_of_lt hpos).symm,
symmetry,
apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic,
rw [@nat_degree_X_pow_sub_C R _ _ n 1, ← nth_roots],
exact is_primitive_root.card_nth_roots h
end
end is_domain
section field
variables {K : Type*} [field K]
/-- `cyclotomic' n K` splits. -/
lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) :=
begin
apply splits_prod (ring_hom.id K),
intros z hz,
simp only [splits_X_sub_C (ring_hom.id K)]
end
/-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/
lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) :
splits (ring_hom.id K) (X ^ n - C (1 : K)) :=
by rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h,
nat_degree_X_pow_sub_C]
/-- If there is a primitive `n`-th root of unity in `K`, then
`∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/
lemma prod_cyclotomic'_eq_X_pow_sub_one {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ}
(hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 :=
begin
rw [X_pow_sub_one_eq_prod hpos h],
have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ),
{ intros i hi,
simp only [cyclotomic'] },
conv_lhs { apply_congr,
skip,
simp [rwcyc, H] },
rw ← finset.prod_bUnion,
{ simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots h] },
intros x hx y hy hdiff,
exact is_primitive_root.disjoint hdiff,
end
/-- If there is a primitive `n`-th root of unity in `K`, then
`cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/
lemma cyclotomic'_eq_X_pow_sub_one_div {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ}
(hpos : 0 < n) (h : is_primitive_root ζ n) :
cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) :=
begin
rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h,
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem],
have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic'.monic i K },
rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1,
simp only [degree_zero, zero_add],
refine ⟨by rw mul_comm, _⟩,
rw [bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h)
end
/-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a
monic polynomial with integer coefficients. -/
lemma int_coeff_of_cyclotomic' {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ}
(h : is_primitive_root ζ n) :
(∃ (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K ∧
P.degree = (cyclotomic' n K).degree ∧ P.monic) :=
begin
refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K),
induction n using nat.strong_induction_on with k hk generalizing ζ h,
cases nat.eq_zero_or_pos k with hzero hpos,
{ use 1,
simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true,
coe_map_ring_hom, map_one, and_self] },
let B : polynomial K := ∏ i in nat.proper_divisors k, cyclotomic' i K,
have Bmo : B.monic,
{ apply monic_prod_of_monic,
intros i hi,
exact (cyclotomic'.monic i K) },
have Bint : B ∈ lifts (int.cast_ring_hom K),
{ refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _,
intros x hx,
have xsmall := (nat.mem_proper_divisors.1 hx).2,
obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1,
rw [mul_comm] at hd,
exact hk x xsmall (is_primitive_root.pow hpos h hd) },
replace Bint := lifts_and_degree_eq_and_monic Bint Bmo,
obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint,
let Q₁ : polynomial ℤ := (X ^ k - 1) /ₘ B₁,
have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : polynomial K).degree < B.degree,
{ split,
{ rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos h),
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos],
simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] },
rw [degree_zero, bot_lt_iff_ne_bot],
intro habs,
exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) },
replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : polynomial K) Bmo huniq,
simp only [lifts, ring_hom.mem_srange],
use Q₁,
rw [coe_map_ring_hom, (map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1],
simp
end
/-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`,
then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/
lemma unique_int_coeff_of_cycl {K : Type*} [comm_ring K] [is_domain K] [char_zero K] {ζ : K}
{n : ℕ+} (h : is_primitive_root ζ n) :
(∃! (P : polynomial ℤ), map (int.cast_ring_hom K) P = cyclotomic' n K) :=
begin
obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic' h,
refine ⟨P, hP.1, λ Q hQ, _⟩,
apply (map_injective (int.cast_ring_hom K) int.cast_injective),
rw [hP.1, hQ]
end
end field
end cyclotomic'
section cyclotomic
/-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/
def cyclotomic (n : ℕ) (R : Type*) [ring R] : polynomial R :=
if h : n = 0 then 1 else
map (int.cast_ring_hom R) ((int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some)
lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) :
cyclotomic n ℤ = (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some :=
begin
simp only [cyclotomic, h, dif_neg, not_false_iff],
ext i,
simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast]
end
/-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/
lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] :
map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R :=
begin
by_cases hzero : n = 0,
{ simp only [hzero, cyclotomic, dif_pos, map_one] },
simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff]
end
lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧
(cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic :=
begin
by_cases hzero : n = 0,
{ simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos,
eq_self_iff_true, map_one, and_self] },
rw int_cyclotomic_rw hzero,
exact (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n hzero)).some_spec
end
lemma int_cyclotomic_unique {n : ℕ} {P : polynomial ℤ} (h : map (int.cast_ring_hom ℂ) P =
cyclotomic' n ℂ) : P = cyclotomic n ℤ :=
begin
apply map_injective (int.cast_ring_hom ℂ) int.cast_injective,
rw [h, (int_cyclotomic_spec n).1]
end
/-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/
@[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) :
map f (cyclotomic n R) = cyclotomic n S :=
begin
rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S],
ext i,
simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast]
end
/-- The zeroth cyclotomic polyomial is `1`. -/
@[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 :=
by simp only [cyclotomic, dif_pos]
/-- The first cyclotomic polyomial is `X - 1`. -/
@[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 :=
begin
have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ,
{ simp only [cyclotomic'_one, pnat.one_coe, map_X, map_one, map_sub] },
symmetry,
rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)],
simp only [map_X, map_one, map_sub]
end
/-- The second cyclotomic polyomial is `X + 1`. -/
@[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 :=
begin
have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ,
{ simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, map_add, map_X, map_one] },
symmetry,
rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)],
simp only [map_add, map_X, map_one]
end
/-- `cyclotomic n` is monic. -/
lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic :=
begin
rw ←map_cyclotomic_int,
apply monic_map,
exact (int_cyclotomic_spec n).2.2
end
/-- `cyclotomic n` is primitive. -/
lemma cyclotomic.is_primitive (n : ℕ) (R : Type*) [comm_ring R] : (cyclotomic n R).is_primitive :=
(cyclotomic.monic n R).is_primitive
/-- `cyclotomic n R` is different from `0`. -/
lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 :=
monic.ne_zero (cyclotomic.monic n R)
/-- The degree of `cyclotomic n` is `totient n`. -/
lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] :
(cyclotomic n R).degree = nat.totient n :=
begin
rw ←map_cyclotomic_int,
rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _,
{ cases n with k,
{ simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]},
rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))],
exact (int_cyclotomic_spec k.succ).2.1 },
simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff,
int.cast_one, ne.def, not_false_iff, one_ne_zero]
end
/-- The natural degree of `cyclotomic n` is `totient n`. -/
lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] :
(cyclotomic n R).nat_degree = nat.totient n :=
begin
have hdeg := degree_cyclotomic n R,
rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg,
exact_mod_cast hdeg
end
/-- The degree of `cyclotomic n R` is positive. -/
lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] :
0 < (cyclotomic n R).degree := by
{ rw degree_cyclotomic n R, exact_mod_cast (nat.totient_pos hpos) }
/-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/
lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] :
∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 :=
begin
have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1,
{ apply map_injective (int.cast_ring_hom ℂ) int.cast_injective,
rw map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ),
simp only [int_cyclotomic_spec, polynomial.map_pow, nat.cast_id, map_X, map_one, map_sub],
exact prod_cyclotomic'_eq_X_pow_sub_one hpos
(complex.is_primitive_root_exp n (ne_of_lt hpos).symm) },
have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1),
{ simp only [polynomial.map_pow, polynomial.map_X, polynomial.map_one, polynomial.map_sub] },
have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ),
{ intros i hi,
exact (map_cyclotomic_int i R).symm },
rw [finset.prod_congr (refl n.divisors) h, coerc, ←map_prod (int.cast_ring_hom R)
(λ i, cyclotomic i ℤ), integer]
end
lemma cyclotomic.dvd_X_pow_sub_one (n : ℕ) (R : Type*) [comm_ring R] :
(cyclotomic n R) ∣ X ^ n - 1 :=
begin
rcases n.eq_zero_or_pos with rfl | hn,
{ simp },
refine ⟨∏ i in n.proper_divisors, cyclotomic i R, _⟩,
rw [←prod_cyclotomic_eq_X_pow_sub_one hn,
nat.divisors_eq_proper_divisors_insert_self_of_pos hn, finset.prod_insert],
exact nat.proper_divisors.not_self_mem
end
lemma prod_cyclotomic_eq_geom_sum {n : ℕ} (h : 0 < n) (R) [comm_ring R] [is_domain R] :
∏ i in n.divisors \ {1}, cyclotomic i R = geom_sum X n :=
begin
apply_fun (* cyclotomic 1 R) using mul_left_injective₀ (cyclotomic_ne_zero 1 R),
have : ∏ i in {1}, cyclotomic i R = cyclotomic 1 R := finset.prod_singleton,
simp_rw [←this, finset.prod_sdiff $ show {1} ⊆ n.divisors, by simp [h.ne'], this, cyclotomic_one,
geom_sum_mul, prod_cyclotomic_eq_X_pow_sub_one h]
end
lemma _root_.is_root_of_unity_iff {n : ℕ} (h : 0 < n) (R : Type*) [comm_ring R] [is_domain R]
{ζ : R} : ζ ^ n = 1 ↔ ∃ i ∈ n.divisors, (cyclotomic i R).is_root ζ :=
by rw [←mem_nth_roots h, nth_roots, mem_roots $ X_pow_sub_C_ne_zero h _,
C_1, ←prod_cyclotomic_eq_X_pow_sub_one h, is_root_prod]; apply_instance
lemma is_root_of_unity_of_root_cyclotomic {n : ℕ} {R} [comm_ring R] {ζ : R} {i : ℕ}
(hi : i ∈ n.divisors) (h : (cyclotomic i R).is_root ζ) : ζ ^ n = 1 :=
begin
rcases n.eq_zero_or_pos with rfl | hn,
{ exact pow_zero _ },
have := congr_arg (eval ζ) (prod_cyclotomic_eq_X_pow_sub_one hn R).symm,
rw [eval_sub, eval_pow, eval_X, eval_one] at this,
convert eq_add_of_sub_eq' this,
convert (add_zero _).symm,
apply eval_eq_zero_of_dvd_of_eval_eq_zero _ h,
exact finset.dvd_prod_of_mem _ hi
end
section arithmetic_function
open nat.arithmetic_function
open_locale arithmetic_function
/-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R`
using Möbius inversion. -/
lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (R : Type*) [comm_ring R] [is_domain R] :
algebra_map _ (ratfunc R) (cyclotomic n R) =
∏ i in n.divisors_antidiagonal, (algebra_map (polynomial R) _ (X ^ i.snd - 1)) ^ μ i.fst :=
begin
rcases n.eq_zero_or_pos with rfl | hpos,
{ simp },
have h : ∀ (n : ℕ), 0 < n →
∏ i in nat.divisors n, algebra_map _ (ratfunc R) (cyclotomic i R) = algebra_map _ _ (X ^ n - 1),
{ intros n hn,
rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] },
rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos;
rw [ne.def, is_fraction_ring.to_map_eq_zero_iff],
{ apply cyclotomic_ne_zero },
{ apply monic.ne_zero,
apply monic_X_pow_sub_C _ (ne_of_gt hn) }
end
end arithmetic_function
/-- We have
`cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/
lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] {n : ℕ}
(hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) :=
begin
nontriviality R,
rw [←prod_cyclotomic_eq_X_pow_sub_one hpos,
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem],
have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic.monic i R },
rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1,
simp only [degree_zero, zero_add],
split,
{ rw mul_comm },
rw [bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h)
end
/-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides
`∏ i in nat.proper_divisors n, cyclotomic i R`. -/
lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n)
(hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R :=
begin
replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2
⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩,
rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm
(nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)),
finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one
(nat.pos_of_mem_proper_divisors hm)],
exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩
end
/-- If there is a primitive `n`-th root of unity in `K`, then
`cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular,
`cyclotomic n K = cyclotomic' n K` -/
lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [comm_ring K] [is_domain K] {ζ : K}
{n : ℕ} (hz : is_primitive_root ζ n) :
cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) :=
begin
rw ←cyclotomic',
induction n using nat.strong_induction_on with k hk generalizing ζ hz,
obtain hzero | hpos := k.eq_zero_or_pos,
{ simp only [hzero, cyclotomic'_zero, cyclotomic_zero] },
have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K,
{ intros i hi,
obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1,
rw mul_comm at hd,
exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) },
rw [@cyclotomic_eq_X_pow_sub_one_div _ _ _ hpos,
cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h]
end
section roots
variables {R : Type*} {n : ℕ} [comm_ring R] [is_domain R]
/-- Any `n`-th primitive root of unity is a root of `cyclotomic n K`.-/
lemma is_root_cyclotomic (hpos : 0 < n) {μ : R} (h : is_primitive_root μ n) :
is_root (cyclotomic n R) μ :=
begin
rw [← mem_roots (cyclotomic_ne_zero n R),
cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def],
rwa [← mem_primitive_roots hpos] at h,
end
private lemma is_root_cyclotomic_iff' {n : ℕ} {K : Type*} [field K] {μ : K} [ne_zero (n : K)] :
is_root (cyclotomic n K) μ ↔ is_primitive_root μ n :=
begin
-- in this proof, `o` stands for `order_of μ`
have hnpos : 0 < n := (ne_zero.of_ne_zero_coe K).out.bot_lt,
refine ⟨λ hμ, _, is_root_cyclotomic hnpos⟩,
have hμn : μ ^ n = 1,
{ rw is_root_of_unity_iff hnpos,
exact ⟨n, n.mem_divisors_self hnpos.ne', hμ⟩ },
by_contra hnμ,
have ho : 0 < order_of μ,
{ apply order_of_pos',
rw is_of_fin_order_iff_pow_eq_one,
exact ⟨n, hnpos, hμn⟩ },
have := pow_order_of_eq_one μ,
rw is_root_of_unity_iff ho at this,
obtain ⟨i, hio, hiμ⟩ := this,
replace hio := nat.dvd_of_mem_divisors hio,
rw is_primitive_root.not_iff at hnμ,
rw ←order_of_dvd_iff_pow_eq_one at hμn,
have key : i < n := (nat.le_of_dvd ho hio).trans_lt ((nat.le_of_dvd hnpos hμn).lt_of_ne hnμ),
have key' : i ∣ n := hio.trans hμn,
rw ←polynomial.dvd_iff_is_root at hμ hiμ,
have hni : {i, n} ⊆ n.divisors,
{ simpa [finset.insert_subset, key'] using hnpos.ne' },
obtain ⟨k, hk⟩ := hiμ,
obtain ⟨j, hj⟩ := hμ,
have := prod_cyclotomic_eq_X_pow_sub_one hnpos K,
rw [←finset.prod_sdiff hni, finset.prod_pair key.ne, hk, hj] at this,
have hn := (X_pow_sub_one_separable_iff.mpr $ ne_zero.ne' n K).squarefree,
rw [←this, squarefree] at hn,
contrapose! hn,
refine ⟨X - C μ, ⟨(∏ x in n.divisors \ {i, n}, cyclotomic x K) * k * j, by ring⟩, _⟩,
simp [polynomial.is_unit_iff_degree_eq_zero]
end
lemma is_root_cyclotomic_iff [ne_zero (n : R)] {μ : R} :
is_root (cyclotomic n R) μ ↔ is_primitive_root μ n :=
begin
have hf : function.injective _ := is_fraction_ring.injective R (fraction_ring R),
haveI : ne_zero (n : fraction_ring R) := ne_zero.nat_of_injective hf,
rw [←is_root_map_iff hf, ←is_primitive_root.map_iff_of_injective hf, map_cyclotomic,
←is_root_cyclotomic_iff']
end
lemma roots_cyclotomic_nodup [ne_zero (n : R)] : (cyclotomic n R).roots.nodup :=
begin
obtain h | ⟨ζ, hζ⟩ := (cyclotomic n R).roots.empty_or_exists_mem,
{ exact h.symm ▸ multiset.nodup_zero },
rw [mem_roots $ cyclotomic_ne_zero n R, is_root_cyclotomic_iff] at hζ,
refine multiset.nodup_of_le (roots.le_of_dvd (X_pow_sub_C_ne_zero
(ne_zero.pos_of_ne_zero_coe R) 1) $ cyclotomic.dvd_X_pow_sub_one n R) hζ.nth_roots_nodup,
end
lemma cyclotomic.roots_to_finset_eq_primitive_roots [ne_zero (n : R)] :
(⟨(cyclotomic n R).roots, roots_cyclotomic_nodup⟩ : finset _) = primitive_roots n R :=
by { ext, simp [cyclotomic_ne_zero n R, is_root_cyclotomic_iff,
mem_primitive_roots, ne_zero.pos_of_ne_zero_coe R] }
lemma cyclotomic.roots_eq_primitive_roots_val [ne_zero (n : R)] :
(cyclotomic n R).roots = (primitive_roots n R).val :=
by rw ←cyclotomic.roots_to_finset_eq_primitive_roots
end roots
/-- If `R` is of characteristic zero, then `ζ` is a root of `cyclotomic n R` if and only if it is a
primitive `n`-th root of unity. -/
lemma is_root_cyclotomic_iff_char_zero {n : ℕ} {R : Type*} [comm_ring R] [is_domain R]
[char_zero R] {μ : R} (hn : 0 < n) :
(polynomial.cyclotomic n R).is_root μ ↔ is_primitive_root μ n :=
by { letI := ne_zero.of_gt hn, exact is_root_cyclotomic_iff }
/-- Over a ring `R` of characteristic zero, `λ n, cyclotomic n R` is injective. -/
lemma cyclotomic_injective {R : Type*} [comm_ring R] [char_zero R] :
function.injective (λ n, cyclotomic n R) :=
begin
intros n m hnm,
simp only at hnm,
rcases eq_or_ne n 0 with rfl | hzero,
{ rw [cyclotomic_zero] at hnm,
replace hnm := congr_arg nat_degree hnm,
rw [nat_degree_one, nat_degree_cyclotomic] at hnm,
by_contra,
exact (nat.totient_pos (zero_lt_iff.2 (ne.symm h))).ne hnm },
{ haveI := ne_zero.mk hzero,
rw [← map_cyclotomic_int _ R, ← map_cyclotomic_int _ R] at hnm,
replace hnm := map_injective (int.cast_ring_hom R) int.cast_injective hnm,
replace hnm := congr_arg (map (int.cast_ring_hom ℂ)) hnm,
rw [map_cyclotomic_int, map_cyclotomic_int] at hnm,
have hprim := complex.is_primitive_root_exp _ hzero,
have hroot := is_root_cyclotomic_iff.2 hprim,
rw hnm at hroot,
haveI hmzero : ne_zero m := ⟨λ h, by simpa [h] using hroot⟩,
rw is_root_cyclotomic_iff at hroot,
replace hprim := hprim.eq_order_of,
rwa [← is_primitive_root.eq_order_of hroot] at hprim}
end
lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n)
(P : polynomial R) :
P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 :=
begin
nontriviality R,
refine ⟨λ hcycl, _, λ hP, _⟩,
{ rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n),
← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos],
exact prod_cyclotomic_eq_X_pow_sub_one hpos R },
{ have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic,
{ apply monic_prod_of_monic,
intros i hi,
exact cyclotomic.monic i R },
rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ hpos,
(div_mod_by_monic_unique P 0 prod_monic _).1],
refine ⟨by rwa [zero_add, mul_comm], _⟩,
rw [degree_zero, bot_lt_iff_ne_bot],
intro h,
exact monic.ne_zero prod_monic (degree_eq_bot.1 h) },
end
/-- If `p` is prime, then `cyclotomic p R = geom_sum X p`. -/
lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] {p : ℕ}
(hp : nat.prime p) : cyclotomic p R = geom_sum X p :=
begin
refine ((eq_cyclotomic_iff hp.pos _).mpr _).symm,
simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one],
end
lemma cyclotomic_prime_mul_X_sub_one (R : Type*) [comm_ring R] (p : ℕ) [hn : fact (nat.prime p)] :
(cyclotomic p R) * (X - 1) = X ^ p - 1 :=
by rw [cyclotomic_eq_geom_sum hn.out, geom_sum_mul]
/-- If `p ^ k` is a prime power, then `cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p`. -/
lemma cyclotomic_prime_pow_eq_geom_sum {R : Type*} [comm_ring R] {p n : ℕ} (hp : nat.prime p) :
cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p :=
begin
have : ∀ m, cyclotomic (p ^ (m + 1)) R = geom_sum (X ^ (p ^ m)) p ↔
geom_sum (X ^ p ^ m) p * ∏ (x : ℕ) in finset.range (m + 1),
cyclotomic (p ^ x) R = X ^ p ^ (m + 1) - 1,
{ intro m,
have := eq_cyclotomic_iff (pow_pos hp.pos (m + 1)) _,
rw eq_comm at this,
rw [this, nat.prod_proper_divisors_prime_pow hp], },
induction n with n_n n_ih,
{ simp [cyclotomic_eq_geom_sum hp], },
rw ((eq_cyclotomic_iff (pow_pos hp.pos (n_n.succ + 1)) _).mpr _).symm,
rw [nat.prod_proper_divisors_prime_pow hp, finset.prod_range_succ, n_ih],
rw this at n_ih,
rw [mul_comm _ (geom_sum _ _), n_ih, geom_sum_mul, sub_left_inj, ← pow_mul, pow_add, pow_one],
end
/-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/
lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) :
(cyclotomic n R).coeff 0 = 1 :=
begin
induction n using nat.strong_induction_on with n hi,
have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1,
{ rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2
(lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _),
cyclotomic_one R],
have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j,
{ intros j hj,
apply nat.succ_le_of_lt,
exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp
(nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) },
have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1,
{ intros j hj,
exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) },
have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1,
{ rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr,
simp only [finset.prod_const_one] },
simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] },
have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0,
{ rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn),
nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn),
finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod,
mul_neg_eq_neg_mul_symm, mul_one] },
have hzero : (X ^ n - 1).coeff 0 = (-1 : R),
{ rw coeff_zero_eq_eval_zero _,
simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow,
eval_sub] },
rw hzero at heq,
exact neg_inj.mp (eq.symm heq)
end
/-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are
coprime. -/
lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ}
(hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) :
a.coprime p :=
begin
apply nat.coprime.symm,
rw [hprime.1.coprime_iff_not_dvd],
intro h,
replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h,
rw [is_root.def, eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot,
by_cases hone : n = 1,
{ simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero,
one_ne_zero, coeff_sub] at hroot,
exact hroot },
rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne
(nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot,
exact one_ne_zero hroot
end
end cyclotomic
section order
/-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo
`p` divides `n`. -/
lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime]
{a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) :
order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n :=
begin
apply order_of_dvd_of_pow_eq_one,
suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : polynomial (zmod p)) = 0,
{ simp only [eval_X, eval_one, eval_pow, eval_sub, eq_nat_cast] at hpow,
apply units.coe_eq_one.1,
simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] },
rw [is_root.def] at hroot,
rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p),
nat.divisors_eq_proper_divisors_insert_self_of_pos hpos,
finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul]
end
end order
section minpoly
open is_primitive_root complex
/-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/
lemma _root_.is_primitive_root.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K}
(h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] :
minpoly ℤ μ ∣ cyclotomic n ℤ :=
begin
apply minpoly.gcd_domain_dvd ℚ (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive,
simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h
end
lemma _root_.is_primitive_root.minpoly_eq_cyclotomic_of_irreducible {K : Type*} [field K]
{R : Type*} [comm_ring R] [is_domain R] {μ : R} {n : ℕ} [algebra K R] (hμ : is_primitive_root μ n)
(h : irreducible $ cyclotomic n K) [ne_zero (n : K)] : cyclotomic n K = minpoly K μ :=
begin
haveI := ne_zero.of_no_zero_smul_divisors K R n,
refine minpoly.eq_of_irreducible_of_monic h _ (cyclotomic.monic n K),
rwa [aeval_def, eval₂_eq_eval_map, map_cyclotomic, ←is_root.def, is_root_cyclotomic_iff]
end
/-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/
lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K}
(h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] :
cyclotomic n ℤ = minpoly ℤ μ :=
begin
refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos))
(cyclotomic.monic n ℤ) (h.minpoly_dvd_cyclotomic hpos) _,
simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h
end
/-- `cyclotomic n ℚ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/
lemma cyclotomic_eq_minpoly_rat {n : ℕ} {K : Type*} [field K] {μ : K}
(h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] :
cyclotomic n ℚ = minpoly ℚ μ :=
begin
rw [← map_cyclotomic_int, cyclotomic_eq_minpoly h hpos],
exact (minpoly.gcd_domain_eq_field_fractions _ (is_integral h hpos)).symm
end
/-- `cyclotomic n ℤ` is irreducible. -/
lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) :=
begin
rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos],
apply minpoly.irreducible,
exact (is_primitive_root_exp n hpos.ne').is_integral hpos,
end
/-- `cyclotomic n ℚ` is irreducible. -/
lemma cyclotomic.irreducible_rat {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℚ) :=
begin
rw [← map_cyclotomic_int],
exact (is_primitive.int.irreducible_iff_irreducible_map_cast (cyclotomic.is_primitive n ℤ)).1
(cyclotomic.irreducible hpos),
end
/-- If `n ≠ m`, then `(cyclotomic n ℚ)` and `(cyclotomic m ℚ)` are coprime. -/
lemma cyclotomic.is_coprime_rat {n m : ℕ} (h : n ≠ m) :
is_coprime (cyclotomic n ℚ) (cyclotomic m ℚ) :=
begin
rcases n.eq_zero_or_pos with rfl | hnzero,
{ exact is_coprime_one_left },
rcases m.eq_zero_or_pos with rfl | hmzero,
{ exact is_coprime_one_right },
rw (irreducible.coprime_iff_not_dvd $ cyclotomic.irreducible_rat $ hnzero),
exact (λ hdiv, h $ cyclotomic_injective $ eq_of_monic_of_associated (cyclotomic.monic n ℚ)
(cyclotomic.monic m ℚ) $ irreducible.associated_of_dvd (cyclotomic.irreducible_rat
hnzero) (cyclotomic.irreducible_rat hmzero) hdiv),
end
end minpoly
section expand
/-- If `p` is a prime such that `¬ p ∣ n`, then
`expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R)`. -/
@[simp] lemma cyclotomic_expand_eq_cyclotomic_mul {p n : ℕ} (hp : nat.prime p) (hdiv : ¬p ∣ n)
(R : Type*) [comm_ring R] :
expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R) :=
begin
rcases nat.eq_zero_or_pos n with rfl | hnpos,
{ simp },
haveI := ne_zero.of_pos hnpos,
suffices : expand ℤ p (cyclotomic n ℤ) = (cyclotomic (n * p) ℤ) * (cyclotomic n ℤ),
{ rw [← map_cyclotomic_int, ← map_expand, this, map_mul, map_cyclotomic_int] },
refine eq_of_monic_of_dvd_of_nat_degree_le (monic_mul (cyclotomic.monic _ _)
(cyclotomic.monic _ _)) ((cyclotomic.monic n ℤ).expand hp.pos) _ _,
{ refine (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _ (is_primitive.mul
(cyclotomic.is_primitive (n * p) ℤ) (cyclotomic.is_primitive n ℤ))
((cyclotomic.monic n ℤ).expand hp.pos).is_primitive).2 _,
rw [map_mul, map_cyclotomic_int, map_cyclotomic_int, map_expand, map_cyclotomic_int],
refine is_coprime.mul_dvd (cyclotomic.is_coprime_rat (λ h, _)) _ _,
{ replace h : n * p = n * 1 := by simp [h],
exact nat.prime.ne_one hp (nat.eq_of_mul_eq_mul_left hnpos h) },
{ have hpos : 0 < n * p := mul_pos hnpos hp.pos,
have hprim := complex.is_primitive_root_exp _ hpos.ne',
rw [cyclotomic_eq_minpoly_rat hprim hpos],
refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _,
rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval, ← is_root.def,
is_root_cyclotomic_iff],
convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n),
rw [nat.mul_div_cancel _ (nat.prime.pos hp)] },
{ have hprim := complex.is_primitive_root_exp _ hnpos.ne.symm,
rw [cyclotomic_eq_minpoly_rat hprim hnpos],
refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _,
rw [aeval_def, ← eval_map, map_expand, expand_eval, ← is_root.def,
← cyclotomic_eq_minpoly_rat hprim hnpos, map_cyclotomic, is_root_cyclotomic_iff],
exact is_primitive_root.pow_of_prime hprim hp hdiv,} },
{ rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_mul (cyclotomic_ne_zero _ ℤ)
(cyclotomic_ne_zero _ ℤ), nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n,
nat.totient_mul ((nat.prime.coprime_iff_not_dvd hp).2 hdiv),
nat.totient_prime hp, mul_comm (p - 1), ← nat.mul_succ, nat.sub_one,
nat.succ_pred_eq_of_pos hp.pos] }
end
/-- If `p` is a prime such that `p ∣ n`, then
`expand R p (cyclotomic n R) = cyclotomic (p * n) R`. -/
@[simp] lemma cyclotomic_expand_eq_cyclotomic {p n : ℕ} (hp : nat.prime p) (hdiv : p ∣ n)
(R : Type*) [comm_ring R] : expand R p (cyclotomic n R) = cyclotomic (n * p) R :=
begin
rcases n.eq_zero_or_pos with rfl | hzero,
{ simp },
haveI := ne_zero.of_pos hzero,
suffices : expand ℤ p (cyclotomic n ℤ) = cyclotomic (n * p) ℤ,
{ rw [← map_cyclotomic_int, ← map_expand, this, map_cyclotomic_int] },
refine eq_of_monic_of_dvd_of_nat_degree_le (cyclotomic.monic _ _)
((cyclotomic.monic n ℤ).expand hp.pos) _ _,
{ have hpos := nat.mul_pos hzero hp.pos,
have hprim := complex.is_primitive_root_exp _ hpos.ne.symm,
rw [cyclotomic_eq_minpoly hprim hpos],
refine @minpoly.gcd_domain_dvd ℤ ℂ ℚ _ _ _ _ _ _ _ _ complex.algebra (algebra_int ℂ) _ _
(is_primitive_root.is_integral hprim hpos) _ ((cyclotomic.monic n ℤ).expand
hp.pos).is_primitive _,
rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval,
← is_root.def, is_root_cyclotomic_iff],
{ convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n),
rw [nat.mul_div_cancel _ hp.pos] } },
{ rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n,
nat.totient_mul_of_prime_of_dvd hp hdiv, mul_comm] }
end
end expand
section char_p
/-- If `R` is of characteristic `p` and `¬p ∣ n`, then
`cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1)`. -/
lemma cyclotomic_mul_prime_eq_pow_of_not_dvd (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)]
[ring R] [char_p R p] (hn : ¬p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1) :=
begin
suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ (p - 1),
{ rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R),
this, polynomial.map_pow] },
apply mul_right_injective₀ (cyclotomic_ne_zero n $ zmod p),
rw [←pow_succ, tsub_add_cancel_of_le hp.out.one_lt.le, mul_comm, ← zmod.expand_card],
nth_rewrite 2 [← map_cyclotomic_int],
rw [← map_expand, cyclotomic_expand_eq_cyclotomic_mul hp.out hn, polynomial.map_mul,
map_cyclotomic, map_cyclotomic]
end
/-- If `R` is of characteristic `p` and `p ∣ n`, then
`cyclotomic (n * p) R = (cyclotomic n R) ^ p`. -/
lemma cyclotomic_mul_prime_dvd_eq_pow (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)] [ring R]
[char_p R p] (hn : p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ p :=
begin
suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ p,
{ rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R),
this, polynomial.map_pow] },
rw [← zmod.expand_card, ← map_cyclotomic_int n, ← map_expand, cyclotomic_expand_eq_cyclotomic
hp.out hn, map_cyclotomic, mul_comm]
end
/-- If `R` is of characteristic `p` and `¬p ∣ m`, then
`cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1))`. -/
lemma cyclotomic_mul_prime_pow_eq (R : Type*) {p m : ℕ} [fact (nat.prime p)]
[ring R] [char_p R p] (hm : ¬p ∣ m) :
∀ {k}, 0 < k → cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1))
| 1 _ := by rw [pow_one, nat.sub_self, pow_zero, mul_comm,
cyclotomic_mul_prime_eq_pow_of_not_dvd R hm]
| (a + 2) _ :=
begin
have hdiv : p ∣ p ^ a.succ * m := ⟨p ^ a * m, by rw [← mul_assoc, pow_succ]⟩,
rw [pow_succ, mul_assoc, mul_comm, cyclotomic_mul_prime_dvd_eq_pow R hdiv,
cyclotomic_mul_prime_pow_eq a.succ_pos, ← pow_mul],
congr' 1,
simp only [tsub_zero, nat.succ_sub_succ_eq_sub],
rw [nat.mul_sub_right_distrib, mul_comm, pow_succ']
end
/-- If `R` is of characteristic `p` and `¬p ∣ m`, then `ζ` is a root of `cyclotomic (p ^ k * m) R`
if and only if it is a primitive `m`-th root of unity. -/
lemma is_root_cyclotomic_prime_pow_mul_iff_of_char_p {m k p : ℕ} {R : Type*} [comm_ring R]
[is_domain R] [hp : fact (nat.prime p)] [hchar : char_p R p] {μ : R} [ne_zero (m : R)] :
(polynomial.cyclotomic (p ^ k * m) R).is_root μ ↔ is_primitive_root μ m :=
begin
rcases k.eq_zero_or_pos with rfl | hk,
{ rw [pow_zero, one_mul, is_root_cyclotomic_iff] },
refine ⟨λ h, _, λ h, _⟩,
{ rw [is_root.def, cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk, eval_pow] at h,
replace h := pow_eq_zero h,
rwa [← is_root.def, is_root_cyclotomic_iff] at h },
{ rw [← is_root_cyclotomic_iff, is_root.def] at h,
rw [cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk,
is_root.def, eval_pow, h, zero_pow],
simp only [tsub_pos_iff_lt],
apply strict_mono_pow hp.out.one_lt (nat.pred_lt hk.ne') }
end
end char_p
end polynomial
|
d155e7eb791615f00dfe975e98a42802c3158000 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/algebra/group_action_hom.lean | e4d24c8d56b6cd3b7e3120ac7a1afe102c45329e | [
"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 | 9,503 | lean | /-
Copyright (c) 2020 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.group_ring_action
import group_theory.group_action
/-!
# Equivariant homomorphisms
## Main definitions
* `mul_action_hom M X Y`, the type of equivariant functions from `X` to `Y`, where `M` is a monoid
that acts on the types `X` and `Y`.
* `distrib_mul_action_hom M A B`, the type of equivariant additive monoid homomorphisms
from `A` to `B`, where `M` is a monoid that acts on the additive monoids `A` and `B`.
* `mul_semiring_action_hom M R S`, the type of equivariant ring homomorphisms
from `R` to `S`, where `M` is a monoid that acts on the rings `R` and `S`.
## Notations
* `X →[M] Y` is `mul_action_hom M X Y`.
* `A →+[M] B` is `distrib_mul_action_hom M X Y`.
* `R →+*[M] S` is `mul_semiring_action_hom M X Y`.
-/
variables (M' : Type*)
variables (X : Type*) [has_scalar M' X]
variables (Y : Type*) [has_scalar M' Y]
variables (Z : Type*) [has_scalar M' Z]
variables (M : Type*) [monoid M]
variables (A : Type*) [add_monoid A] [distrib_mul_action M A]
variables (A' : Type*) [add_group A'] [distrib_mul_action M A']
variables (B : Type*) [add_monoid B] [distrib_mul_action M B]
variables (B' : Type*) [add_group B'] [distrib_mul_action M B']
variables (C : Type*) [add_monoid C] [distrib_mul_action M C]
variables (R : Type*) [semiring R] [mul_semiring_action M R]
variables (R' : Type*) [ring R'] [mul_semiring_action M R']
variables (S : Type*) [semiring S] [mul_semiring_action M S]
variables (S' : Type*) [ring S'] [mul_semiring_action M S']
variables (T : Type*) [semiring T] [mul_semiring_action M T]
variables (G : Type*) [group G] (H : subgroup G)
set_option old_structure_cmd true
/-- Equivariant functions. -/
@[nolint has_inhabited_instance]
structure mul_action_hom :=
(to_fun : X → Y)
(map_smul' : ∀ (m : M') (x : X), to_fun (m • x) = m • to_fun x)
notation X ` →[`:25 M:25 `] `:0 Y:0 := mul_action_hom M X Y
namespace mul_action_hom
instance : has_coe_to_fun (X →[M'] Y) :=
⟨_, λ c, c.to_fun⟩
variables {M M' X Y}
@[simp] lemma map_smul (f : X →[M'] Y) (m : M') (x : X) : f (m • x) = m • f x :=
f.map_smul' m x
@[ext] theorem ext : ∀ {f g : X →[M'] Y}, (∀ x, f x = g x) → f = g
| ⟨f, _⟩ ⟨g, _⟩ H := by { congr' 1 with x, exact H x }
theorem ext_iff {f g : X →[M'] Y} : f = g ↔ ∀ x, f x = g x :=
⟨λ H x, by rw H, ext⟩
variables (M M') {X}
/-- The identity map as an equivariant map. -/
protected def id : X →[M'] X :=
⟨id, λ _ _, rfl⟩
@[simp] lemma id_apply (x : X) : mul_action_hom.id M' x = x := rfl
variables {M M' X Y Z}
/-- Composition of two equivariant maps. -/
def comp (g : Y →[M'] Z) (f : X →[M'] Y) : X →[M'] Z :=
⟨g ∘ f, λ m x, calc
g (f (m • x)) = g (m • f x) : by rw f.map_smul
... = m • g (f x) : g.map_smul _ _⟩
@[simp] lemma comp_apply (g : Y →[M'] Z) (f : X →[M'] Y) (x : X) : g.comp f x = g (f x) := rfl
@[simp] lemma id_comp (f : X →[M'] Y) : (mul_action_hom.id M').comp f = f :=
ext $ λ x, by rw [comp_apply, id_apply]
@[simp] lemma comp_id (f : X →[M'] Y) : f.comp (mul_action_hom.id M') = f :=
ext $ λ x, by rw [comp_apply, id_apply]
local attribute [instance] mul_action.regular
variables {G} (H)
/-- The canonical map to the left cosets. -/
def to_quotient : G →[G] quotient_group.quotient H :=
⟨coe, λ g x, rfl⟩
@[simp] lemma to_quotient_apply (g : G) : to_quotient H g = g := rfl
end mul_action_hom
/-- Equivariant additive monoid homomorphisms. -/
@[nolint has_inhabited_instance]
structure distrib_mul_action_hom extends A →[M] B, A →+ B.
/-- Reinterpret an equivariant additive monoid homomorphism as an additive monoid homomorphism. -/
add_decl_doc distrib_mul_action_hom.to_add_monoid_hom
/-- Reinterpret an equivariant additive monoid homomorphism as an equivariant function. -/
add_decl_doc distrib_mul_action_hom.to_mul_action_hom
notation A ` →+[`:25 M:25 `] `:0 B:0 := distrib_mul_action_hom M A B
namespace distrib_mul_action_hom
instance has_coe : has_coe (A →+[M] B) (A →+ B) :=
⟨to_add_monoid_hom⟩
instance has_coe' : has_coe (A →+[M] B) (A →[M] B) :=
⟨to_mul_action_hom⟩
instance : has_coe_to_fun (A →+[M] B) :=
⟨_, λ c, c.to_fun⟩
variables {M A B}
@[norm_cast] lemma coe_fn_coe (f : A →+[M] B) : ((f : A →+ B) : A → B) = f := rfl
@[norm_cast] lemma coe_fn_coe' (f : A →+[M] B) : ((f : A →[M] B) : A → B) = f := rfl
@[ext] theorem ext : ∀ {f g : A →+[M] B}, (∀ x, f x = g x) → f = g
| ⟨f, _, _, _⟩ ⟨g, _, _, _⟩ H := by { congr' 1 with x, exact H x }
theorem ext_iff {f g : A →+[M] B} : f = g ↔ ∀ x, f x = g x :=
⟨λ H x, by rw H, ext⟩
@[simp] lemma map_zero (f : A →+[M] B) : f 0 = 0 :=
f.map_zero'
@[simp] lemma map_add (f : A →+[M] B) (x y : A) : f (x + y) = f x + f y :=
f.map_add' x y
@[simp] lemma map_neg (f : A' →+[M] B') (x : A') : f (-x) = -f x :=
(f : A' →+ B').map_neg x
@[simp] lemma map_sub (f : A' →+[M] B') (x y : A') : f (x - y) = f x - f y :=
(f : A' →+ B').map_sub x y
@[simp] lemma map_smul (f : A →+[M] B) (m : M) (x : A) : f (m • x) = m • f x :=
f.map_smul' m x
variables (M) {A}
/-- The identity map as an equivariant additive monoid homomorphism. -/
protected def id : A →+[M] A :=
⟨id, λ _ _, rfl, rfl, λ _ _, rfl⟩
@[simp] lemma id_apply (x : A) : distrib_mul_action_hom.id M x = x := rfl
variables {M A B C}
/-- Composition of two equivariant additive monoid homomorphisms. -/
def comp (g : B →+[M] C) (f : A →+[M] B) : A →+[M] C :=
{ .. mul_action_hom.comp (g : B →[M] C) (f : A →[M] B),
.. add_monoid_hom.comp (g : B →+ C) (f : A →+ B), }
@[simp] lemma comp_apply (g : B →+[M] C) (f : A →+[M] B) (x : A) : g.comp f x = g (f x) := rfl
@[simp] lemma id_comp (f : A →+[M] B) : (distrib_mul_action_hom.id M).comp f = f :=
ext $ λ x, by rw [comp_apply, id_apply]
@[simp] lemma comp_id (f : A →+[M] B) : f.comp (distrib_mul_action_hom.id M) = f :=
ext $ λ x, by rw [comp_apply, id_apply]
end distrib_mul_action_hom
/-- Equivariant ring homomorphisms. -/
@[nolint has_inhabited_instance]
structure mul_semiring_action_hom extends R →+[M] S, R →+* S.
/-- Reinterpret an equivariant ring homomorphism as a ring homomorphism. -/
add_decl_doc mul_semiring_action_hom.to_ring_hom
/-- Reinterpret an equivariant ring homomorphism as an equivariant additive monoid homomorphism. -/
add_decl_doc mul_semiring_action_hom.to_distrib_mul_action_hom
notation R ` →+*[`:25 M:25 `] `:0 S:0 := mul_semiring_action_hom M R S
namespace mul_semiring_action_hom
instance has_coe : has_coe (R →+*[M] S) (R →+* S) :=
⟨to_ring_hom⟩
instance has_coe' : has_coe (R →+*[M] S) (R →+[M] S) :=
⟨to_distrib_mul_action_hom⟩
instance : has_coe_to_fun (R →+*[M] S) :=
⟨_, λ c, c.to_fun⟩
variables {M R S}
@[norm_cast] lemma coe_fn_coe (f : R →+*[M] S) : ((f : R →+* S) : R → S) = f := rfl
@[norm_cast] lemma coe_fn_coe' (f : R →+*[M] S) : ((f : R →+[M] S) : R → S) = f := rfl
@[ext] theorem ext : ∀ {f g : R →+*[M] S}, (∀ x, f x = g x) → f = g
| ⟨f, _, _, _, _, _⟩ ⟨g, _, _, _, _, _⟩ H := by { congr' 1 with x, exact H x }
theorem ext_iff {f g : R →+*[M] S} : f = g ↔ ∀ x, f x = g x :=
⟨λ H x, by rw H, ext⟩
@[simp] lemma map_zero (f : R →+*[M] S) : f 0 = 0 :=
f.map_zero'
@[simp] lemma map_add (f : R →+*[M] S) (x y : R) : f (x + y) = f x + f y :=
f.map_add' x y
@[simp] lemma map_neg (f : R' →+*[M] S') (x : R') : f (-x) = -f x :=
(f : R' →+* S').map_neg x
@[simp] lemma map_sub (f : R' →+*[M] S') (x y : R') : f (x - y) = f x - f y :=
(f : R' →+* S').map_sub x y
@[simp] lemma map_one (f : R →+*[M] S) : f 1 = 1 :=
f.map_one'
@[simp] lemma map_mul (f : R →+*[M] S) (x y : R) : f (x * y) = f x * f y :=
f.map_mul' x y
@[simp] lemma map_smul (f : R →+*[M] S) (m : M) (x : R) : f (m • x) = m • f x :=
f.map_smul' m x
variables (M) {R}
/-- The identity map as an equivariant ring homomorphism. -/
protected def id : R →+*[M] R :=
⟨id, λ _ _, rfl, rfl, λ _ _, rfl, rfl, λ _ _, rfl⟩
@[simp] lemma id_apply (x : R) : mul_semiring_action_hom.id M x = x := rfl
variables {M R S T}
/-- Composition of two equivariant additive monoid homomorphisms. -/
def comp (g : S →+*[M] T) (f : R →+*[M] S) : R →+*[M] T :=
{ .. distrib_mul_action_hom.comp (g : S →+[M] T) (f : R →+[M] S),
.. ring_hom.comp (g : S →+* T) (f : R →+* S), }
@[simp] lemma comp_apply (g : S →+*[M] T) (f : R →+*[M] S) (x : R) : g.comp f x = g (f x) := rfl
@[simp] lemma id_comp (f : R →+*[M] S) : (mul_semiring_action_hom.id M).comp f = f :=
ext $ λ x, by rw [comp_apply, id_apply]
@[simp] lemma comp_id (f : R →+*[M] S) : f.comp (mul_semiring_action_hom.id M) = f :=
ext $ λ x, by rw [comp_apply, id_apply]
end mul_semiring_action_hom
section
variables (M) {R'} (U : set R') [is_subring U] [is_invariant_subring M U]
local attribute [instance] subset.ring
/-- The canonical inclusion from an invariant subring. -/
def is_invariant_subring.subtype_hom : U →+*[M] R' :=
{ map_smul' := λ m s, rfl, .. is_subring.subtype U }
@[simp] theorem is_invariant_subring.coe_subtype_hom :
(is_invariant_subring.subtype_hom M U : U → R') = coe := rfl
@[simp] theorem is_invariant_subring.coe_subtype_hom' :
(is_invariant_subring.subtype_hom M U : U →+* R') = is_subring.subtype U := rfl
end
|
d9b97f3fa4c47d3aede81ce823e32109e94909e6 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/measure_theory/measure/finite_measure_weak_convergence.lean | 2d650850eb1b362831c7a262a6e449e872e7ca34 | [
"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,392 | lean | /-
Copyright (c) 2021 Kalle Kytölä. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kalle Kytölä
-/
import measure_theory.measure.measure_space
import measure_theory.integral.set_integral
import topology.continuous_function.bounded
import topology.algebra.module.weak_dual
import topology.metric_space.thickened_indicator
/-!
# Weak convergence of (finite) measures
This file defines the topology of weak convergence of finite measures and probability measures
on topological spaces. The topology of weak convergence is the coarsest topology w.r.t. which
for every bounded continuous `ℝ≥0`-valued function `f`, the integration of `f` against the
measure is continuous.
TODOs:
* Include the portmanteau theorem on characterizations of weak convergence of (Borel) probability
measures.
## Main definitions
The main definitions are the
* types `finite_measure α` and `probability_measure α` with topologies of weak convergence;
* `to_weak_dual_bcnn : finite_measure α → (weak_dual ℝ≥0 (α →ᵇ ℝ≥0))`
allowing to interpret a finite measure as a continuous linear functional on the space of
bounded continuous nonnegative functions on `α`. This is used for the definition of the
topology of weak convergence.
## Main results
* Finite measures `μ` on `α` give rise to continuous linear functionals on the space of
bounded continuous nonnegative functions on `α` via integration:
`to_weak_dual_bcnn : finite_measure α → (weak_dual ℝ≥0 (α →ᵇ ℝ≥0))`.
* `tendsto_iff_forall_lintegral_tendsto`: Convergence of finite measures and probability measures
is characterized by the convergence of integrals of all bounded continuous (nonnegative)
functions. This essentially shows that the given definition of topology corresponds to the
common textbook definition of weak convergence of measures.
TODO:
* Portmanteau theorem:
* `finite_measure.limsup_measure_closed_le_of_tendsto` proves one implication.
The current formulation assumes `pseudo_emetric_space`. The only reason is to have
bounded continuous pointwise approximations to the indicator function of a closed set. Clearly
for example metrizability or pseudo-emetrizability would be sufficient assumptions. The
typeclass assumptions should be later adjusted in a way that takes into account use cases, but
the proof will presumably remain essentially the same.
* Prove the rest of the implications.
## Notations
No new notation is introduced.
## Implementation notes
The topology of weak convergence of finite Borel measures will be defined using a mapping from
`finite_measure α` to `weak_dual ℝ≥0 (α →ᵇ ℝ≥0)`, inheriting the topology from the latter.
The current implementation of `finite_measure α` and `probability_measure α` is directly as
subtypes of `measure α`, and the coercion to a function is the composition `ennreal.to_nnreal`
and the coercion to function of `measure α`. Another alternative would be to use a bijection
with `vector_measure α ℝ≥0` as an intermediate step. The choice of implementation should not have
drastic downstream effects, so it can be changed later if appropriate.
Potential advantages of using the `nnreal`-valued vector measure alternative:
* The coercion to function would avoid need to compose with `ennreal.to_nnreal`, the
`nnreal`-valued API could be more directly available.
Potential drawbacks of the vector measure alternative:
* The coercion to function would lose monotonicity, as non-measurable sets would be defined to
have measure 0.
* No integration theory directly. E.g., the topology definition requires `lintegral` w.r.t.
a coercion to `measure α` in any case.
## References
* [Billingsley, *Convergence of probability measures*][billingsley1999]
## Tags
weak convergence of measures, finite measure, probability measure
-/
noncomputable theory
open measure_theory
open set
open filter
open bounded_continuous_function
open_locale topological_space ennreal nnreal bounded_continuous_function
namespace measure_theory
namespace finite_measure
section finite_measure
/-! ### Finite measures
In this section we define the `Type` of `finite_measure α`, when `α` is a measurable space. Finite
measures on `α` are a module over `ℝ≥0`.
If `α` is moreover a topological space and the sigma algebra on `α` is finer than the Borel sigma
algebra (i.e. `[opens_measurable_space α]`), then `finite_measure α` is equipped with the topology
of weak convergence of measures. This is implemented by defining a pairing of finite measures `μ`
on `α` with continuous bounded nonnegative functions `f : α →ᵇ ℝ≥0` via integration, and using the
associated weak topology (essentially the weak-star topology on the dual of `α →ᵇ ℝ≥0`).
-/
variables {α : Type*} [measurable_space α]
/-- Finite measures are defined as the subtype of measures that have the property of being finite
measures (i.e., their total mass is finite). -/
def _root_.measure_theory.finite_measure (α : Type*) [measurable_space α] : Type* :=
{μ : measure α // is_finite_measure μ}
/-- A finite measure can be interpreted as a measure. -/
instance : has_coe (finite_measure α) (measure_theory.measure α) := coe_subtype
instance is_finite_measure (μ : finite_measure α) :
is_finite_measure (μ : measure α) := μ.prop
instance : has_coe_to_fun (finite_measure α) (λ _, set α → ℝ≥0) :=
⟨λ μ s, (μ s).to_nnreal⟩
lemma coe_fn_eq_to_nnreal_coe_fn_to_measure (ν : finite_measure α) :
(ν : set α → ℝ≥0) = λ s, ((ν : measure α) s).to_nnreal := rfl
@[simp] lemma ennreal_coe_fn_eq_coe_fn_to_measure (ν : finite_measure α) (s : set α) :
(ν s : ℝ≥0∞) = (ν : measure α) s := ennreal.coe_to_nnreal (measure_lt_top ↑ν s).ne
@[simp] lemma val_eq_to_measure (ν : finite_measure α) : ν.val = (ν : measure α) := rfl
lemma coe_injective : function.injective (coe : finite_measure α → measure α) :=
subtype.coe_injective
/-- The (total) mass of a finite measure `μ` is `μ univ`, i.e., the cast to `nnreal` of
`(μ : measure α) univ`. -/
def mass (μ : finite_measure α) : ℝ≥0 := μ univ
@[simp] lemma ennreal_mass {μ : finite_measure α} :
(μ.mass : ℝ≥0∞) = (μ : measure α) univ := ennreal_coe_fn_eq_coe_fn_to_measure μ set.univ
instance has_zero : has_zero (finite_measure α) :=
{ zero := ⟨0, measure_theory.is_finite_measure_zero⟩ }
@[simp] lemma zero.mass : (0 : finite_measure α).mass = 0 :=
by { simp only [mass], refl, }
@[simp] lemma mass_zero_iff (μ : finite_measure α) : μ.mass = 0 ↔ μ = 0 :=
begin
refine ⟨λ μ_mass, _, (λ hμ, by simp only [hμ, zero.mass])⟩,
ext1,
apply measure.measure_univ_eq_zero.mp,
rwa [← ennreal_mass, ennreal.coe_eq_zero],
end
@[ext] lemma extensionality (μ ν : finite_measure α)
(h : ∀ (s : set α), measurable_set s → μ s = ν s) :
μ = ν :=
begin
ext1, ext1 s s_mble,
simpa [ennreal_coe_fn_eq_coe_fn_to_measure] using congr_arg (coe : ℝ≥0 → ℝ≥0∞) (h s s_mble),
end
instance : inhabited (finite_measure α) := ⟨0⟩
instance : has_add (finite_measure α) :=
{ add := λ μ ν, ⟨μ + ν, measure_theory.is_finite_measure_add⟩ }
variables {R : Type*} [has_smul R ℝ≥0] [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0 ℝ≥0∞]
[is_scalar_tower R ℝ≥0∞ ℝ≥0∞]
instance : has_smul R (finite_measure α) :=
{ smul := λ (c : R) μ, ⟨c • μ, measure_theory.is_finite_measure_smul_of_nnreal_tower⟩, }
@[simp, norm_cast] lemma coe_zero : (coe : finite_measure α → measure α) 0 = 0 := rfl
@[simp, norm_cast] lemma coe_add (μ ν : finite_measure α) : ↑(μ + ν) = (↑μ + ↑ν : measure α) := rfl
@[simp, norm_cast] lemma coe_smul (c : R) (μ : finite_measure α) :
↑(c • μ) = (c • ↑μ : measure α) := rfl
@[simp, norm_cast] lemma coe_fn_zero :
(⇑(0 : finite_measure α) : set α → ℝ≥0) = (0 : set α → ℝ≥0) := by { funext, refl, }
@[simp, norm_cast] lemma coe_fn_add (μ ν : finite_measure α) :
(⇑(μ + ν) : set α → ℝ≥0) = (⇑μ + ⇑ν : set α → ℝ≥0) :=
by { funext, simp [← ennreal.coe_eq_coe], }
@[simp, norm_cast] lemma coe_fn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] (c : R) (μ : finite_measure α) :
(⇑(c • μ) : set α → ℝ≥0) = c • (⇑μ : set α → ℝ≥0) :=
by { funext, simp [← ennreal.coe_eq_coe, ennreal.coe_smul], }
instance : add_comm_monoid (finite_measure α) :=
coe_injective.add_comm_monoid coe coe_zero coe_add (λ _ _, coe_smul _ _)
/-- Coercion is an `add_monoid_hom`. -/
@[simps]
def coe_add_monoid_hom : finite_measure α →+ measure α :=
{ to_fun := coe, map_zero' := coe_zero, map_add' := coe_add }
instance {α : Type*} [measurable_space α] : module ℝ≥0 (finite_measure α) :=
function.injective.module _ coe_add_monoid_hom coe_injective coe_smul
@[simp] lemma coe_fn_smul_apply [is_scalar_tower R ℝ≥0 ℝ≥0]
(c : R) (μ : finite_measure α) (s : set α) :
(c • μ) s = c • (μ s) :=
by { simp only [coe_fn_smul, pi.smul_apply], }
variables [topological_space α]
/-- The pairing of a finite (Borel) measure `μ` with a nonnegative bounded continuous
function is obtained by (Lebesgue) integrating the (test) function against the measure.
This is `finite_measure.test_against_nn`. -/
def test_against_nn (μ : finite_measure α) (f : α →ᵇ ℝ≥0) : ℝ≥0 :=
(∫⁻ x, f x ∂(μ : measure α)).to_nnreal
lemma _root_.bounded_continuous_function.nnreal.to_ennreal_comp_measurable {α : Type*}
[topological_space α] [measurable_space α] [opens_measurable_space α] (f : α →ᵇ ℝ≥0) :
measurable (λ x, (f x : ℝ≥0∞)) :=
measurable_coe_nnreal_ennreal.comp f.continuous.measurable
lemma _root_.measure_theory.lintegral_lt_top_of_bounded_continuous_to_nnreal
(μ : measure α) [is_finite_measure μ] (f : α →ᵇ ℝ≥0) :
∫⁻ x, f x ∂μ < ∞ :=
begin
apply is_finite_measure.lintegral_lt_top_of_bounded_to_ennreal,
use nndist f 0,
intros x,
have key := bounded_continuous_function.nnreal.upper_bound f x,
rw ennreal.coe_le_coe,
have eq : nndist f 0 = ⟨dist f 0, dist_nonneg⟩,
{ ext,
simp only [real.coe_to_nnreal', max_eq_left_iff, subtype.coe_mk, coe_nndist], },
rwa eq at key,
end
@[simp] lemma test_against_nn_coe_eq {μ : finite_measure α} {f : α →ᵇ ℝ≥0} :
(μ.test_against_nn f : ℝ≥0∞) = ∫⁻ x, f x ∂(μ : measure α) :=
ennreal.coe_to_nnreal (lintegral_lt_top_of_bounded_continuous_to_nnreal _ f).ne
lemma test_against_nn_const (μ : finite_measure α) (c : ℝ≥0) :
μ.test_against_nn (bounded_continuous_function.const α c) = c * μ.mass :=
by simp [← ennreal.coe_eq_coe]
lemma test_against_nn_mono (μ : finite_measure α)
{f g : α →ᵇ ℝ≥0} (f_le_g : (f : α → ℝ≥0) ≤ g) :
μ.test_against_nn f ≤ μ.test_against_nn g :=
begin
simp only [←ennreal.coe_le_coe, test_against_nn_coe_eq],
apply lintegral_mono,
exact λ x, ennreal.coe_mono (f_le_g x),
end
@[simp] lemma zero.test_against_nn_apply (f : α →ᵇ ℝ≥0) :
(0 : finite_measure α).test_against_nn f = 0 :=
by simp only [test_against_nn, coe_zero, lintegral_zero_measure, ennreal.zero_to_nnreal]
lemma zero.test_against_nn : (0 : finite_measure α).test_against_nn = 0 :=
by { funext, simp only [zero.test_against_nn_apply, pi.zero_apply], }
@[simp] lemma smul_test_against_nn_apply (c : ℝ≥0) (μ : finite_measure α) (f : α →ᵇ ℝ≥0) :
(c • μ).test_against_nn f = c • (μ.test_against_nn f) :=
begin
simp only [test_against_nn, coe_smul, smul_eq_mul ℝ≥0, ← ennreal.smul_to_nnreal],
congr,
rw [(show c • (μ : measure α) = (c : ℝ≥0∞) • (μ : measure α), by refl),
lintegral_smul_measure],
refl,
end
variables [opens_measurable_space α]
lemma test_against_nn_add (μ : finite_measure α) (f₁ f₂ : α →ᵇ ℝ≥0) :
μ.test_against_nn (f₁ + f₂) = μ.test_against_nn f₁ + μ.test_against_nn f₂ :=
begin
simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_add, ennreal.coe_add,
pi.add_apply, test_against_nn_coe_eq],
exact lintegral_add_left (bounded_continuous_function.nnreal.to_ennreal_comp_measurable _) _
end
lemma test_against_nn_smul [is_scalar_tower R ℝ≥0 ℝ≥0] [pseudo_metric_space R] [has_zero R]
[has_bounded_smul R ℝ≥0]
(μ : finite_measure α) (c : R) (f : α →ᵇ ℝ≥0) :
μ.test_against_nn (c • f) = c • μ.test_against_nn f :=
begin
simp only [←ennreal.coe_eq_coe, bounded_continuous_function.coe_smul,
test_against_nn_coe_eq, ennreal.coe_smul],
simp_rw [←smul_one_smul ℝ≥0∞ c (f _ : ℝ≥0∞), ←smul_one_smul ℝ≥0∞ c (lintegral _ _ : ℝ≥0∞),
smul_eq_mul],
exact @lintegral_const_mul _ _ (μ : measure α) (c • 1) _
(bounded_continuous_function.nnreal.to_ennreal_comp_measurable f),
end
lemma test_against_nn_lipschitz_estimate (μ : finite_measure α) (f g : α →ᵇ ℝ≥0) :
μ.test_against_nn f ≤ μ.test_against_nn g + (nndist f g) * μ.mass :=
begin
simp only [←μ.test_against_nn_const (nndist f g), ←test_against_nn_add, ←ennreal.coe_le_coe,
bounded_continuous_function.coe_add, const_apply, ennreal.coe_add, pi.add_apply,
coe_nnreal_ennreal_nndist, test_against_nn_coe_eq],
apply lintegral_mono,
have le_dist : ∀ x, dist (f x) (g x) ≤ nndist f g :=
bounded_continuous_function.dist_coe_le_dist,
intros x,
have le' : f(x) ≤ g(x) + nndist f g,
{ apply (nnreal.le_add_nndist (f x) (g x)).trans,
rw add_le_add_iff_left,
exact dist_le_coe.mp (le_dist x), },
have le : (f(x) : ℝ≥0∞) ≤ (g(x) : ℝ≥0∞) + (nndist f g),
by { rw ←ennreal.coe_add, exact ennreal.coe_mono le', },
rwa [coe_nnreal_ennreal_nndist] at le,
end
lemma test_against_nn_lipschitz (μ : finite_measure α) :
lipschitz_with μ.mass (λ (f : α →ᵇ ℝ≥0), μ.test_against_nn f) :=
begin
rw lipschitz_with_iff_dist_le_mul,
intros f₁ f₂,
suffices : abs (μ.test_against_nn f₁ - μ.test_against_nn f₂ : ℝ) ≤ μ.mass * (dist f₁ f₂),
{ rwa nnreal.dist_eq, },
apply abs_le.mpr,
split,
{ have key' := μ.test_against_nn_lipschitz_estimate f₂ f₁,
rw mul_comm at key',
suffices : ↑(μ.test_against_nn f₂) ≤ ↑(μ.test_against_nn f₁) + ↑(μ.mass) * dist f₁ f₂,
{ linarith, },
have key := nnreal.coe_mono key',
rwa [nnreal.coe_add, nnreal.coe_mul, nndist_comm] at key, },
{ have key' := μ.test_against_nn_lipschitz_estimate f₁ f₂,
rw mul_comm at key',
suffices : ↑(μ.test_against_nn f₁) ≤ ↑(μ.test_against_nn f₂) + ↑(μ.mass) * dist f₁ f₂,
{ linarith, },
have key := nnreal.coe_mono key',
rwa [nnreal.coe_add, nnreal.coe_mul] at key, },
end
/-- Finite measures yield elements of the `weak_dual` of bounded continuous nonnegative
functions via `finite_measure.test_against_nn`, i.e., integration. -/
def to_weak_dual_bcnn (μ : finite_measure α) :
weak_dual ℝ≥0 (α →ᵇ ℝ≥0) :=
{ to_fun := λ f, μ.test_against_nn f,
map_add' := test_against_nn_add μ,
map_smul' := test_against_nn_smul μ,
cont := μ.test_against_nn_lipschitz.continuous, }
@[simp] lemma coe_to_weak_dual_bcnn (μ : finite_measure α) :
⇑μ.to_weak_dual_bcnn = μ.test_against_nn := rfl
@[simp] lemma to_weak_dual_bcnn_apply (μ : finite_measure α) (f : α →ᵇ ℝ≥0) :
μ.to_weak_dual_bcnn f = (∫⁻ x, f x ∂(μ : measure α)).to_nnreal := rfl
/-- The topology of weak convergence on `finite_measures α` is inherited (induced) from the weak-*
topology on `weak_dual ℝ≥0 (α →ᵇ ℝ≥0)` via the function `finite_measures.to_weak_dual_bcnn`. -/
instance : topological_space (finite_measure α) :=
topological_space.induced to_weak_dual_bcnn infer_instance
lemma to_weak_dual_bcnn_continuous :
continuous (@to_weak_dual_bcnn α _ _ _) :=
continuous_induced_dom
/- Integration of (nonnegative bounded continuous) test functions against finite Borel measures
depends continuously on the measure. -/
lemma continuous_test_against_nn_eval (f : α →ᵇ ℝ≥0) :
continuous (λ (μ : finite_measure α), μ.test_against_nn f) :=
(by apply (weak_bilin.eval_continuous _ _).comp to_weak_dual_bcnn_continuous :
continuous ((λ φ : weak_dual ℝ≥0 (α →ᵇ ℝ≥0), φ f) ∘ to_weak_dual_bcnn))
lemma tendsto_iff_weak_star_tendsto {γ : Type*} {F : filter γ}
{μs : γ → finite_measure α} {μ : finite_measure α} :
tendsto μs F (𝓝 μ) ↔ tendsto (λ i, (μs(i)).to_weak_dual_bcnn) F (𝓝 μ.to_weak_dual_bcnn) :=
inducing.tendsto_nhds_iff ⟨rfl⟩
theorem tendsto_iff_forall_test_against_nn_tendsto {γ : Type*} {F : filter γ}
{μs : γ → finite_measure α} {μ : finite_measure α} :
tendsto μs F (𝓝 μ) ↔
∀ (f : α →ᵇ ℝ≥0), tendsto (λ i, (μs i).to_weak_dual_bcnn f) F (𝓝 (μ.to_weak_dual_bcnn f)) :=
by { rw [tendsto_iff_weak_star_tendsto, tendsto_iff_forall_eval_tendsto_top_dual_pairing], refl, }
/-- A characterization of weak convergence in terms of integrals of bounded continuous
nonnegative functions. -/
theorem tendsto_iff_forall_lintegral_tendsto {γ : Type*} {F : filter γ}
{μs : γ → finite_measure α} {μ : finite_measure α} :
tendsto μs F (𝓝 μ) ↔
∀ (f : α →ᵇ ℝ≥0),
tendsto (λ i, (∫⁻ x, (f x) ∂(μs(i) : measure α))) F (𝓝 ((∫⁻ x, (f x) ∂(μ : measure α)))) :=
begin
rw tendsto_iff_forall_test_against_nn_tendsto,
simp_rw [to_weak_dual_bcnn_apply _ _, ←test_against_nn_coe_eq,
ennreal.tendsto_coe, ennreal.to_nnreal_coe],
end
end finite_measure -- section
section finite_measure_bounded_convergence
/-! ### Bounded convergence results for finite measures
This section is about bounded convergence theorems for finite measures.
-/
variables {α : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α]
/-- A bounded convergence theorem for a finite measure:
If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a
limit, then their integrals against the finite measure tend to the integral of the limit.
This formulation assumes:
* the functions tend to a limit along a countably generated filter;
* the limit is in the almost everywhere sense;
* boundedness holds almost everywhere;
* integration is `lintegral`, i.e., the functions and their integrals are `ℝ≥0∞`-valued.
-/
lemma tendsto_lintegral_nn_filter_of_le_const {ι : Type*} {L : filter ι} [L.is_countably_generated]
(μ : measure α) [is_finite_measure μ] {fs : ι → (α →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ᶠ i in L, ∀ᵐ (a : α) ∂(μ : measure α), fs i a ≤ c) {f : α → ℝ≥0}
(fs_lim : ∀ᵐ (a : α) ∂(μ : measure α), tendsto (λ i, fs i a) L (𝓝 (f a))) :
tendsto (λ i, (∫⁻ a, fs i a ∂μ)) L (𝓝 (∫⁻ a, (f a) ∂μ)) :=
begin
simpa only using tendsto_lintegral_filter_of_dominated_convergence (λ _, c)
(eventually_of_forall ((λ i, (ennreal.continuous_coe.comp (fs i).continuous).measurable)))
_ ((@lintegral_const_lt_top _ _ (μ : measure α) _ _ (@ennreal.coe_ne_top c)).ne) _,
{ simpa only [ennreal.coe_le_coe] using fs_le_const, },
{ simpa only [ennreal.tendsto_coe] using fs_lim, },
end
/-- A bounded convergence theorem for a finite measure:
If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant
and tend pointwise to a limit, then their integrals (`lintegral`) against the finite measure tend
to the integral of the limit.
A related result with more general assumptions is `tendsto_lintegral_nn_filter_of_le_const`.
-/
lemma tendsto_lintegral_nn_of_le_const (μ : finite_measure α) {fs : ℕ → (α →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ n a, fs n a ≤ c) {f : α → ℝ≥0}
(fs_lim : ∀ a, tendsto (λ n, fs n a) at_top (𝓝 (f a))) :
tendsto (λ n, (∫⁻ a, fs n a ∂(μ : measure α))) at_top (𝓝 (∫⁻ a, (f a) ∂(μ : measure α))) :=
tendsto_lintegral_nn_filter_of_le_const μ
(eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim)
/-- A bounded convergence theorem for a finite measure:
If bounded continuous non-negative functions are uniformly bounded by a constant and tend to a
limit, then their integrals against the finite measure tend to the integral of the limit.
This formulation assumes:
* the functions tend to a limit along a countably generated filter;
* the limit is in the almost everywhere sense;
* boundedness holds almost everywhere;
* integration is the pairing against non-negative continuous test functions (`test_against_nn`).
A related result using `lintegral` for integration is `tendsto_lintegral_nn_filter_of_le_const`.
-/
lemma tendsto_test_against_nn_filter_of_le_const {ι : Type*} {L : filter ι}
[L.is_countably_generated] {μ : finite_measure α} {fs : ι → (α →ᵇ ℝ≥0)} {c : ℝ≥0}
(fs_le_const : ∀ᶠ i in L, ∀ᵐ (a : α) ∂(μ : measure α), fs i a ≤ c) {f : α →ᵇ ℝ≥0}
(fs_lim : ∀ᵐ (a : α) ∂(μ : measure α), tendsto (λ i, fs i a) L (𝓝 (f a))) :
tendsto (λ i, μ.test_against_nn (fs i)) L (𝓝 (μ.test_against_nn f)) :=
begin
apply (ennreal.tendsto_to_nnreal
(lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure α) f).ne).comp,
exact tendsto_lintegral_nn_filter_of_le_const μ fs_le_const fs_lim,
end
/-- A bounded convergence theorem for a finite measure:
If a sequence of bounded continuous non-negative functions are uniformly bounded by a constant
and tend pointwise to a limit, then their integrals (`test_against_nn`) against the finite measure
tend to the integral of the limit.
Related results:
* `tendsto_test_against_nn_filter_of_le_const`: more general assumptions
* `tendsto_lintegral_nn_of_le_const`: using `lintegral` for integration.
-/
lemma tendsto_test_against_nn_of_le_const {μ : finite_measure α}
{fs : ℕ → (α →ᵇ ℝ≥0)} {c : ℝ≥0} (fs_le_const : ∀ n a, fs n a ≤ c) {f : α →ᵇ ℝ≥0}
(fs_lim : ∀ a, tendsto (λ n, fs n a) at_top (𝓝 (f a))) :
tendsto (λ n, μ.test_against_nn (fs n)) at_top (𝓝 (μ.test_against_nn f)) :=
tendsto_test_against_nn_filter_of_le_const
(eventually_of_forall (λ n, eventually_of_forall (fs_le_const n))) (eventually_of_forall fs_lim)
end finite_measure_bounded_convergence -- section
section finite_measure_convergence_by_bounded_continuous_functions
/-! ### Weak convergence of finite measures with bounded continuous real-valued functions
In this section we characterize the weak convergence of finite measures by the usual (defining)
condition that the integrals of all bounded continuous real-valued functions converge.
-/
variables {α : Type*} [measurable_space α] [topological_space α] [opens_measurable_space α]
lemma integrable_of_bounded_continuous_to_nnreal
(μ : measure α) [is_finite_measure μ] (f : α →ᵇ ℝ≥0) :
integrable ((coe : ℝ≥0 → ℝ) ∘ ⇑f) μ :=
begin
refine ⟨(nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable, _⟩,
simp only [has_finite_integral, nnreal.nnnorm_eq],
exact lintegral_lt_top_of_bounded_continuous_to_nnreal _ f,
end
lemma integrable_of_bounded_continuous_to_real
(μ : measure α) [is_finite_measure μ] (f : α →ᵇ ℝ) :
integrable ⇑f μ :=
begin
refine ⟨f.continuous.measurable.ae_strongly_measurable, _⟩,
have aux : (coe : ℝ≥0 → ℝ) ∘ ⇑f.nnnorm = (λ x, ∥f x∥),
{ ext x,
simp only [function.comp_app, bounded_continuous_function.nnnorm_coe_fun_eq, coe_nnnorm], },
apply (has_finite_integral_iff_norm ⇑f).mpr,
rw ← of_real_integral_eq_lintegral_of_real,
{ exact ennreal.of_real_lt_top, },
{ exact aux ▸ integrable_of_bounded_continuous_to_nnreal μ f.nnnorm, },
{ exact eventually_of_forall (λ x, norm_nonneg (f x)), },
end
lemma _root_.bounded_continuous_function.integral_eq_integral_nnreal_part_sub
(μ : measure α) [is_finite_measure μ] (f : α →ᵇ ℝ) :
∫ x, f x ∂μ = ∫ x, f.nnreal_part x ∂μ - ∫ x, (-f).nnreal_part x ∂μ :=
by simp only [f.self_eq_nnreal_part_sub_nnreal_part_neg,
pi.sub_apply, integral_sub, integrable_of_bounded_continuous_to_nnreal]
lemma lintegral_lt_top_of_bounded_continuous_to_real
{α : Type*} [measurable_space α] [topological_space α] (μ : measure α) [is_finite_measure μ]
(f : α →ᵇ ℝ) :
∫⁻ x, ennreal.of_real (f x) ∂μ < ∞ :=
lintegral_lt_top_of_bounded_continuous_to_nnreal _ f.nnreal_part
theorem tendsto_of_forall_integral_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure α} {μ : finite_measure α}
(h : (∀ (f : α →ᵇ ℝ),
tendsto (λ i, (∫ x, (f x) ∂(μs i : measure α))) F (𝓝 ((∫ x, (f x) ∂(μ : measure α)))))) :
tendsto μs F (𝓝 μ) :=
begin
apply (@tendsto_iff_forall_lintegral_tendsto α _ _ _ γ F μs μ).mpr,
intro f,
have key := @ennreal.tendsto_to_real_iff _ F
_ (λ i, (lintegral_lt_top_of_bounded_continuous_to_nnreal (μs i : measure α) f).ne)
_ (lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure α) f).ne,
simp only [ennreal.of_real_coe_nnreal] at key,
apply key.mp,
have lip : lipschitz_with 1 (coe : ℝ≥0 → ℝ), from isometry_subtype_coe.lipschitz,
set f₀ := bounded_continuous_function.comp _ lip f with def_f₀,
have f₀_eq : ⇑f₀ = (coe : ℝ≥0 → ℝ) ∘ ⇑f, by refl,
have f₀_nn : 0 ≤ ⇑f₀, from λ _, by simp only [f₀_eq, pi.zero_apply, nnreal.zero_le_coe],
have f₀_ae_nn : 0 ≤ᵐ[(μ : measure α)] ⇑f₀, from eventually_of_forall f₀_nn,
have f₀_ae_nns : ∀ i, 0 ≤ᵐ[(μs i : measure α)] ⇑f₀, from λ i, eventually_of_forall f₀_nn,
have aux := integral_eq_lintegral_of_nonneg_ae f₀_ae_nn
f₀.continuous.measurable.ae_strongly_measurable,
have auxs := λ i, integral_eq_lintegral_of_nonneg_ae (f₀_ae_nns i)
f₀.continuous.measurable.ae_strongly_measurable,
simp only [f₀_eq, ennreal.of_real_coe_nnreal] at aux auxs,
simpa only [←aux, ←auxs] using h f₀,
end
lemma _root_.bounded_continuous_function.nnreal.to_real_lintegral_eq_integral
(f : α →ᵇ ℝ≥0) (μ : measure α) :
(∫⁻ x, (f x : ℝ≥0∞) ∂μ).to_real = (∫ x, f x ∂μ) :=
begin
rw integral_eq_lintegral_of_nonneg_ae _
(nnreal.continuous_coe.comp f.continuous).measurable.ae_strongly_measurable,
{ simp only [ennreal.of_real_coe_nnreal], },
{ apply eventually_of_forall,
simp only [pi.zero_apply, nnreal.zero_le_coe, implies_true_iff], },
end
/-- A characterization of weak convergence in terms of integrals of bounded continuous
real-valued functions. -/
theorem tendsto_iff_forall_integral_tendsto
{γ : Type*} {F : filter γ} {μs : γ → finite_measure α} {μ : finite_measure α} :
tendsto μs F (𝓝 μ) ↔
∀ (f : α →ᵇ ℝ),
tendsto (λ i, (∫ x, (f x) ∂(μs i : measure α))) F (𝓝 ((∫ x, (f x) ∂(μ : measure α)))) :=
begin
refine ⟨_, tendsto_of_forall_integral_tendsto⟩,
rw tendsto_iff_forall_lintegral_tendsto,
intros h f,
simp_rw bounded_continuous_function.integral_eq_integral_nnreal_part_sub,
set f_pos := f.nnreal_part with def_f_pos,
set f_neg := (-f).nnreal_part with def_f_neg,
have tends_pos := (ennreal.tendsto_to_real
((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure α) f_pos).ne)).comp (h f_pos),
have tends_neg := (ennreal.tendsto_to_real
((lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure α) f_neg).ne)).comp (h f_neg),
have aux : ∀ (g : α →ᵇ ℝ≥0), ennreal.to_real ∘ (λ (i : γ), ∫⁻ (x : α), ↑(g x) ∂(μs i : measure α))
= λ (i : γ), (∫⁻ (x : α), ↑(g x) ∂(μs i : measure α)).to_real, from λ _, rfl,
simp_rw [aux, bounded_continuous_function.nnreal.to_real_lintegral_eq_integral]
at tends_pos tends_neg,
exact tendsto.sub tends_pos tends_neg,
end
end finite_measure_convergence_by_bounded_continuous_functions -- section
end finite_measure -- namespace
section probability_measure
/-! ### Probability measures
In this section we define the `Type*` of probability measures on a measurable space `α`, denoted by
`probability_measure α`. TODO: Probability measures form a convex space.
If `α` is moreover a topological space and the sigma algebra on `α` is finer than the Borel sigma
algebra (i.e. `[opens_measurable_space α]`), then `probability_measure α` is equipped with the
topology of weak convergence of measures. Since every probability measure is a finite measure, this
is implemented as the induced topology from the coercion `probability_measure.to_finite_measure`.
-/
/-- Probability measures are defined as the subtype of measures that have the property of being
probability measures (i.e., their total mass is one). -/
def probability_measure (α : Type*) [measurable_space α] : Type* :=
{μ : measure α // is_probability_measure μ}
namespace probability_measure
variables {α : Type*} [measurable_space α]
instance [inhabited α] : inhabited (probability_measure α) :=
⟨⟨measure.dirac default, measure.dirac.is_probability_measure⟩⟩
/-- A probability measure can be interpreted as a measure. -/
instance : has_coe (probability_measure α) (measure_theory.measure α) := coe_subtype
instance : has_coe_to_fun (probability_measure α) (λ _, set α → ℝ≥0) :=
⟨λ μ s, (μ s).to_nnreal⟩
instance (μ : probability_measure α) : is_probability_measure (μ : measure α) := μ.prop
lemma coe_fn_eq_to_nnreal_coe_fn_to_measure (ν : probability_measure α) :
(ν : set α → ℝ≥0) = λ s, ((ν : measure α) s).to_nnreal := rfl
@[simp] lemma val_eq_to_measure (ν : probability_measure α) : ν.val = (ν : measure α) := rfl
lemma coe_injective : function.injective (coe : probability_measure α → measure α) :=
subtype.coe_injective
@[simp] lemma coe_fn_univ (ν : probability_measure α) : ν univ = 1 :=
congr_arg ennreal.to_nnreal ν.prop.measure_univ
/-- A probability measure can be interpreted as a finite measure. -/
def to_finite_measure (μ : probability_measure α) : finite_measure α := ⟨μ, infer_instance⟩
@[simp] lemma coe_comp_to_finite_measure_eq_coe (ν : probability_measure α) :
(ν.to_finite_measure : measure α) = (ν : measure α) := rfl
@[simp] lemma coe_fn_comp_to_finite_measure_eq_coe_fn (ν : probability_measure α) :
(ν.to_finite_measure : set α → ℝ≥0) = (ν : set α → ℝ≥0) := rfl
@[simp] lemma ennreal_coe_fn_eq_coe_fn_to_measure (ν : probability_measure α) (s : set α) :
(ν s : ℝ≥0∞) = (ν : measure α) s :=
by { rw [← coe_fn_comp_to_finite_measure_eq_coe_fn,
finite_measure.ennreal_coe_fn_eq_coe_fn_to_measure], refl, }
@[ext] lemma extensionality (μ ν : probability_measure α)
(h : ∀ (s : set α), measurable_set s → μ s = ν s) :
μ = ν :=
begin
ext1, ext1 s s_mble,
simpa [ennreal_coe_fn_eq_coe_fn_to_measure] using congr_arg (coe : ℝ≥0 → ℝ≥0∞) (h s s_mble),
end
@[simp] lemma mass_to_finite_measure (μ : probability_measure α) :
μ.to_finite_measure.mass = 1 := μ.coe_fn_univ
variables [topological_space α] [opens_measurable_space α]
lemma test_against_nn_lipschitz (μ : probability_measure α) :
lipschitz_with 1 (λ (f : α →ᵇ ℝ≥0), μ.to_finite_measure.test_against_nn f) :=
μ.mass_to_finite_measure ▸ μ.to_finite_measure.test_against_nn_lipschitz
/-- The topology of weak convergence on `probability_measures α`. This is inherited (induced) from
the weak-* topology on `weak_dual ℝ≥0 (α →ᵇ ℝ≥0)` via the function
`probability_measures.to_weak_dual_bcnn`. -/
instance : topological_space (probability_measure α) :=
topological_space.induced to_finite_measure infer_instance
lemma to_finite_measure_continuous :
continuous (to_finite_measure : probability_measure α → finite_measure α) :=
continuous_induced_dom
/-- Probability measures yield elements of the `weak_dual` of bounded continuous nonnegative
functions via `finite_measure.test_against_nn`, i.e., integration. -/
def to_weak_dual_bcnn : probability_measure α → weak_dual ℝ≥0 (α →ᵇ ℝ≥0) :=
finite_measure.to_weak_dual_bcnn ∘ to_finite_measure
@[simp] lemma coe_to_weak_dual_bcnn (μ : probability_measure α) :
⇑μ.to_weak_dual_bcnn = μ.to_finite_measure.test_against_nn := rfl
@[simp] lemma to_weak_dual_bcnn_apply (μ : probability_measure α) (f : α →ᵇ ℝ≥0) :
μ.to_weak_dual_bcnn f = (∫⁻ x, f x ∂(μ : measure α)).to_nnreal := rfl
lemma to_weak_dual_bcnn_continuous :
continuous (λ (μ : probability_measure α), μ.to_weak_dual_bcnn) :=
finite_measure.to_weak_dual_bcnn_continuous.comp to_finite_measure_continuous
/- Integration of (nonnegative bounded continuous) test functions against Borel probability
measures depends continuously on the measure. -/
lemma continuous_test_against_nn_eval (f : α →ᵇ ℝ≥0) :
continuous (λ (μ : probability_measure α), μ.to_finite_measure.test_against_nn f) :=
(finite_measure.continuous_test_against_nn_eval f).comp to_finite_measure_continuous
/- The canonical mapping from probability measures to finite measures is an embedding. -/
lemma to_finite_measure_embedding (α : Type*)
[measurable_space α] [topological_space α] [opens_measurable_space α] :
embedding (to_finite_measure : probability_measure α → finite_measure α) :=
{ induced := rfl,
inj := λ μ ν h, subtype.eq (by convert congr_arg coe h) }
lemma tendsto_nhds_iff_to_finite_measures_tendsto_nhds {δ : Type*}
(F : filter δ) {μs : δ → probability_measure α} {μ₀ : probability_measure α} :
tendsto μs F (𝓝 μ₀) ↔ tendsto (to_finite_measure ∘ μs) F (𝓝 (μ₀.to_finite_measure)) :=
embedding.tendsto_nhds_iff (to_finite_measure_embedding α)
/-- A characterization of weak convergence of probability measures by the condition that the
integrals of every continuous bounded nonnegative function converge to the integral of the function
against the limit measure. -/
theorem tendsto_iff_forall_lintegral_tendsto {γ : Type*} {F : filter γ}
{μs : γ → probability_measure α} {μ : probability_measure α} :
tendsto μs F (𝓝 μ) ↔
∀ (f : α →ᵇ ℝ≥0), tendsto (λ i, (∫⁻ x, (f x) ∂(μs(i) : measure α))) F
(𝓝 ((∫⁻ x, (f x) ∂(μ : measure α)))) :=
begin
rw tendsto_nhds_iff_to_finite_measures_tendsto_nhds,
exact finite_measure.tendsto_iff_forall_lintegral_tendsto,
end
/-- The characterization of weak convergence of probability measures by the usual (defining)
condition that the integrals of every continuous bounded function converge to the integral of the
function against the limit measure. -/
theorem tendsto_iff_forall_integral_tendsto
{γ : Type*} {F : filter γ} {μs : γ → probability_measure α} {μ : probability_measure α} :
tendsto μs F (𝓝 μ) ↔
∀ (f : α →ᵇ ℝ),
tendsto (λ i, (∫ x, (f x) ∂(μs i : measure α))) F (𝓝 ((∫ x, (f x) ∂(μ : measure α)))) :=
begin
rw tendsto_nhds_iff_to_finite_measures_tendsto_nhds,
rw finite_measure.tendsto_iff_forall_integral_tendsto,
simp only [coe_comp_to_finite_measure_eq_coe],
end
end probability_measure -- namespace
end probability_measure -- section
section convergence_implies_limsup_closed_le
/-! ### Portmanteau implication: weak convergence implies a limsup condition for closed sets
In this section we prove, under the assumption that the underlying topological space `α` is
pseudo-emetrizable, that the weak convergence of measures on `finite_measure α` implies that for
any closed set `F` in `α` the limsup of the measures of `F` is at most the limit measure of `F`.
This is one implication of the portmanteau theorem characterizing weak convergence of measures.
-/
variables {α : Type*} [measurable_space α]
/-- If bounded continuous functions tend to the indicator of a measurable set and are
uniformly bounded, then their integrals against a finite measure tend to the measure of the set.
This formulation assumes:
* the functions tend to a limit along a countably generated filter;
* the limit is in the almost everywhere sense;
* boundedness holds almost everywhere.
-/
lemma measure_of_cont_bdd_of_tendsto_filter_indicator {ι : Type*} {L : filter ι}
[L.is_countably_generated] [topological_space α] [opens_measurable_space α]
(μ : measure α) [is_finite_measure μ] {c : ℝ≥0} {E : set α} (E_mble : measurable_set E)
(fs : ι → (α →ᵇ ℝ≥0)) (fs_bdd : ∀ᶠ i in L, ∀ᵐ (a : α) ∂μ, fs i a ≤ c)
(fs_lim : ∀ᵐ (a : α) ∂μ,
tendsto (λ (i : ι), (coe_fn : (α →ᵇ ℝ≥0) → (α → ℝ≥0)) (fs i) a) L
(𝓝 (indicator E (λ x, (1 : ℝ≥0)) a))) :
tendsto (λ n, lintegral μ (λ a, fs n a)) L (𝓝 (μ E)) :=
begin
convert finite_measure.tendsto_lintegral_nn_filter_of_le_const μ fs_bdd fs_lim,
have aux : ∀ a, indicator E (λ x, (1 : ℝ≥0∞)) a = ↑(indicator E (λ x, (1 : ℝ≥0)) a),
from λ a, by simp only [ennreal.coe_indicator, ennreal.coe_one],
simp_rw [←aux, lintegral_indicator _ E_mble],
simp only [lintegral_one, measure.restrict_apply, measurable_set.univ, univ_inter],
end
/-- If a sequence of bounded continuous functions tends to the indicator of a measurable set and
the functions are uniformly bounded, then their integrals against a finite measure tend to the
measure of the set.
A similar result with more general assumptions is `measure_of_cont_bdd_of_tendsto_filter_indicator`.
-/
lemma measure_of_cont_bdd_of_tendsto_indicator
[topological_space α] [opens_measurable_space α]
(μ : measure α) [is_finite_measure μ] {c : ℝ≥0} {E : set α} (E_mble : measurable_set E)
(fs : ℕ → (α →ᵇ ℝ≥0)) (fs_bdd : ∀ n a, fs n a ≤ c)
(fs_lim : tendsto (λ (n : ℕ), (coe_fn : (α →ᵇ ℝ≥0) → (α → ℝ≥0)) (fs n))
at_top (𝓝 (indicator E (λ x, (1 : ℝ≥0))))) :
tendsto (λ n, lintegral μ (λ a, fs n a)) at_top (𝓝 (μ E)) :=
begin
have fs_lim' : ∀ a, tendsto (λ (n : ℕ), (fs n a : ℝ≥0))
at_top (𝓝 (indicator E (λ x, (1 : ℝ≥0)) a)),
by { rw tendsto_pi_nhds at fs_lim, exact λ a, fs_lim a, },
apply measure_of_cont_bdd_of_tendsto_filter_indicator μ E_mble fs
(eventually_of_forall (λ n, eventually_of_forall (fs_bdd n))) (eventually_of_forall fs_lim'),
end
/-- The integrals of thickened indicators of a closed set against a finite measure tend to the
measure of the closed set if the thickening radii tend to zero.
-/
lemma tendsto_lintegral_thickened_indicator_of_is_closed
{α : Type*} [measurable_space α] [pseudo_emetric_space α] [opens_measurable_space α]
(μ : measure α) [is_finite_measure μ] {F : set α} (F_closed : is_closed F) {δs : ℕ → ℝ}
(δs_pos : ∀ n, 0 < δs n) (δs_lim : tendsto δs at_top (𝓝 0)) :
tendsto (λ n, lintegral μ (λ a, (thickened_indicator (δs_pos n) F a : ℝ≥0∞)))
at_top (𝓝 (μ F)) :=
begin
apply measure_of_cont_bdd_of_tendsto_indicator μ F_closed.measurable_set
(λ n, thickened_indicator (δs_pos n) F)
(λ n a, thickened_indicator_le_one (δs_pos n) F a),
have key := thickened_indicator_tendsto_indicator_closure δs_pos δs_lim F,
rwa F_closed.closure_eq at key,
end
/-- One implication of the portmanteau theorem:
Weak convergence of finite measures implies that the limsup of the measures of any closed set is
at most the measure of the closed set under the limit measure.
-/
lemma finite_measure.limsup_measure_closed_le_of_tendsto
{α ι : Type*} {L : filter ι}
[measurable_space α] [pseudo_emetric_space α] [opens_measurable_space α]
{μ : finite_measure α} {μs : ι → finite_measure α}
(μs_lim : tendsto μs L (𝓝 μ)) {F : set α} (F_closed : is_closed F) :
L.limsup (λ i, (μs i : measure α) F) ≤ (μ : measure α) F :=
begin
by_cases L = ⊥,
{ simp only [h, limsup, filter.map_bot, Limsup_bot, ennreal.bot_eq_zero, zero_le], },
apply ennreal.le_of_forall_pos_le_add,
intros ε ε_pos μ_F_finite,
set δs := λ (n : ℕ), (1 : ℝ) / (n+1) with def_δs,
have δs_pos : ∀ n, 0 < δs n, from λ n, nat.one_div_pos_of_nat,
have δs_lim : tendsto δs at_top (𝓝 0), from tendsto_one_div_add_at_top_nhds_0_nat,
have key₁ := tendsto_lintegral_thickened_indicator_of_is_closed
(μ : measure α) F_closed δs_pos δs_lim,
have room₁ : (μ : measure α) F < (μ : measure α) F + ε / 2,
{ apply ennreal.lt_add_right (measure_lt_top (μ : measure α) F).ne
((ennreal.div_pos_iff.mpr
⟨(ennreal.coe_pos.mpr ε_pos).ne.symm, ennreal.two_ne_top⟩).ne.symm), },
rcases eventually_at_top.mp (eventually_lt_of_tendsto_lt room₁ key₁) with ⟨M, hM⟩,
have key₂ := finite_measure.tendsto_iff_forall_lintegral_tendsto.mp
μs_lim (thickened_indicator (δs_pos M) F),
have room₂ : lintegral (μ : measure α) (λ a, thickened_indicator (δs_pos M) F a)
< lintegral (μ : measure α) (λ a, thickened_indicator (δs_pos M) F a) + ε / 2,
{ apply ennreal.lt_add_right
(lintegral_lt_top_of_bounded_continuous_to_nnreal (μ : measure α) _).ne
((ennreal.div_pos_iff.mpr
⟨(ennreal.coe_pos.mpr ε_pos).ne.symm, ennreal.two_ne_top⟩).ne.symm), },
have ev_near := eventually.mono (eventually_lt_of_tendsto_lt room₂ key₂) (λ n, le_of_lt),
have aux := λ n, le_trans (measure_le_lintegral_thickened_indicator
(μs n : measure α) F_closed.measurable_set (δs_pos M)),
have ev_near' := eventually.mono ev_near aux,
apply (filter.limsup_le_limsup ev_near').trans,
haveI : ne_bot L, from ⟨h⟩,
rw limsup_const,
apply le_trans (add_le_add (hM M rfl.le).le (le_refl (ε/2 : ℝ≥0∞))),
simp only [add_assoc, ennreal.add_halves, le_refl],
end
end convergence_implies_limsup_closed_le --section
end measure_theory --namespace
|
4470c81778aecbaf9a10dc496511a3a47540eab5 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/data/set_like.lean | 568e0f800699ff57029f7b5fae3096423365e173 | [
"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 | 4,322 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import data.set.basic
import tactic.monotonicity.basic
/-!
# Typeclass for a type `A` with an injective map to `set B`
This typeclass is primarily for use by subobjects like `submonoid` and `submodule`.
A typical subobject should be declared as:
```
structure my_subobject (X : Type*) :=
(carrier : set X)
(op_mem : ∀ {x : X}, x ∈ carrier → sorry ∈ carrier)
namespace my_subobject
variables (X : Type*)
instance : set_like (my_subobject X) X :=
⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩
@[simp] lemma mem_carrier {p : my_subobject X} : x ∈ p.carrier ↔ x ∈ (p : set X) := iff.rfl
@[ext] theorem ext {p q : my_subobject X} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h
/-- Copy of a `my_subobject` with a new `carrier` equal to the old one. Useful to fix definitional
equalities. -/
protected def copy (p : my_subobject X) (s : set X) (hs : s = ↑p) : my_subobject X :=
{ carrier := s,
op_mem' := hs.symm ▸ p.op_mem' }
end my_subobject
```
This file will then provide a `coe_sort`, a `coe` to set, a `partial_order`, and various
extensionality and simp lemmas.
-/
set_option old_structure_cmd true
/-- A class to indicate that there is a canonical injection between `A` and `set B`. -/
@[protect_proj]
class set_like (A : Type*) (B : out_param $ Type*) :=
(coe : A → set B)
(coe_injective' : function.injective coe)
namespace set_like
variables {A : Type*} {B : Type*} [i : set_like A B]
include i
instance : has_coe_t A (set B) := ⟨set_like.coe⟩
@[priority 100]
instance : has_mem B A := ⟨λ x p, x ∈ (p : set B)⟩
-- `dangerous_instance` does not know that `B` is used only as an `out_param`
@[nolint dangerous_instance, priority 100]
instance : has_coe_to_sort A := ⟨_, λ p, {x : B // x ∈ p}⟩
variables (p q : A)
@[simp, norm_cast] theorem coe_sort_coe : ↥(p : set B) = p := rfl
variables {p q}
protected theorem «exists» {q : p → Prop} :
(∃ x, q x) ↔ (∃ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.exists
protected theorem «forall» {q : p → Prop} :
(∀ x, q x) ↔ (∀ x ∈ p, q ⟨x, ‹_›⟩) := set_coe.forall
theorem coe_injective : function.injective (coe : A → set B) :=
λ x y h, set_like.coe_injective' h
@[simp, norm_cast] theorem coe_set_eq : (p : set B) = q ↔ p = q := coe_injective.eq_iff
theorem ext' (h : (p : set B) = q) : p = q := coe_injective h
theorem ext'_iff : p = q ↔ (p : set B) = q := coe_set_eq.symm
/-- Note: implementers of `set_like` must copy this lemma in order to tag it with `@[ext]`. -/
theorem ext (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := coe_injective $ set.ext h
theorem ext_iff : p = q ↔ (∀ x, x ∈ p ↔ x ∈ q) := coe_injective.eq_iff.symm.trans set.ext_iff
@[simp] theorem mem_coe {x : B} : x ∈ (p : set B) ↔ x ∈ p := iff.rfl
@[simp, norm_cast] lemma coe_eq_coe {x y : p} : (x : B) = y ↔ x = y := subtype.ext_iff_val.symm
@[simp, norm_cast] lemma coe_mk (x : B) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : B) = x := rfl
@[simp] lemma coe_mem (x : p) : (x : B) ∈ p := x.2
@[simp] protected lemma eta (x : p) (hx : (x : B) ∈ p) : (⟨x, hx⟩ : p) = x := subtype.eta x hx
-- `dangerous_instance` does not know that `B` is used only as an `out_param`
@[nolint dangerous_instance, priority 100]
instance : partial_order A :=
{ le := λ H K, ∀ ⦃x⦄, x ∈ H → x ∈ K,
.. partial_order.lift (coe : A → set B) coe_injective }
lemma le_def {S T : A} : S ≤ T ↔ ∀ ⦃x : B⦄, x ∈ S → x ∈ T := iff.rfl
@[simp, norm_cast]
lemma coe_subset_coe {S T : A} : (S : set B) ⊆ T ↔ S ≤ T := iff.rfl
@[mono] lemma coe_mono : monotone (coe : A → set B) := λ a b, coe_subset_coe.mpr
@[simp, norm_cast]
lemma coe_ssubset_coe {S T : A} : (S : set B) ⊂ T ↔ S < T := iff.rfl
@[mono] lemma coe_strict_mono : strict_mono (coe : A → set B) := λ a b, coe_ssubset_coe.mpr
lemma not_le_iff_exists : ¬(p ≤ q) ↔ ∃ x ∈ p, x ∉ q := set.not_subset
lemma exists_of_lt : p < q → ∃ x ∈ q, x ∉ p := set.exists_of_ssubset
lemma lt_iff_le_and_exists : p < q ↔ p ≤ q ∧ ∃ x ∈ q, x ∉ p :=
by rw [lt_iff_le_not_le, not_le_iff_exists]
end set_like
|
c7ceea9da2754f3bd509087c582b3375214cee2f | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/list/permutation.lean | 9ef8ea26c1b3fe72c4cf8c2f1a48c414740e3f44 | [
"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 | 10,807 | lean | /-
Copyright (c) 2014 Parikshit Khanna. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro
-/
import data.list.join
/-!
# Permutations of a list
In this file we prove properties about `list.permutations`, a list of all permutations of a list. It
is defined in `data.list.defs`.
## Order of the permutations
Designed for performance, the order in which the permutations appear in `list.permutations` is
rather intricate and not very amenable to induction. That's why we also provide `list.permutations'`
as a less efficient but more straightforward way of listing permutations.
### `list.permutations`
TODO. In the meantime, you can try decrypting the docstrings.
### `list.permutations'`
The list of partitions is built by recursion. The permutations of `[]` are `[[]]`. Then, the
permutations of `a :: l` are obtained by taking all permutations of `l` in order and adding `a` in
all positions. Hence, to build `[0, 1, 2, 3].permutations'`, it does
* `[[]]`
* `[[3]]`
* `[[2, 3], [3, 2]]]`
* `[[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]]`
* `[[0, 1, 2, 3], [1, 0, 2, 3], [1, 2, 0, 3], [1, 2, 3, 0],`
`[0, 2, 1, 3], [2, 0, 1, 3], [2, 1, 0, 3], [2, 1, 3, 0],`
`[0, 2, 3, 1], [2, 0, 3, 1], [2, 3, 0, 1], [2, 3, 1, 0],`
`[0, 1, 3, 2], [1, 0, 3, 2], [1, 3, 0, 2], [1, 3, 2, 0],`
`[0, 3, 1, 2], [3, 0, 1, 2], [3, 1, 0, 2], [3, 1, 2, 0],`
`[0, 3, 2, 1], [3, 0, 2, 1], [3, 2, 0, 1], [3, 2, 1, 0]]`
## TODO
Show that `l.nodup → l.permutations.nodup`. See `data.fintype.list`.
-/
open nat
variables {α β : Type*}
namespace list
lemma permutations_aux2_fst (t : α) (ts : list α) (r : list β) : ∀ (ys : list α) (f : list α → β),
(permutations_aux2 t ts r ys f).1 = ys ++ ts
| [] f := rfl
| (y::ys) f := match _, permutations_aux2_fst ys _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).1 = y :: ys ++ ts with
| ⟨_, zs⟩, rfl := rfl
end
@[simp] lemma permutations_aux2_snd_nil (t : α) (ts : list α) (r : list β) (f : list α → β) :
(permutations_aux2 t ts r [] f).2 = r := rfl
@[simp] lemma permutations_aux2_snd_cons (t : α) (ts : list α) (r : list β) (y : α) (ys : list α)
(f : list α → β) :
(permutations_aux2 t ts r (y::ys) f).2 = f (t :: y :: ys ++ ts) ::
(permutations_aux2 t ts r ys (λx : list α, f (y::x))).2 :=
match _, permutations_aux2_fst t ts r _ _ : ∀ o : list α × list β, o.1 = ys ++ ts →
(permutations_aux2._match_1 t y f o).2 = f (t :: y :: ys ++ ts) :: o.2 with
| ⟨_, zs⟩, rfl := rfl
end
/-- The `r` argument to `permutations_aux2` is the same as appending. -/
lemma permutations_aux2_append (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts nil ys f).2 ++ r = (permutations_aux2 t ts r ys f).2 :=
by induction ys generalizing f; simp *
/-- The `ts` argument to `permutations_aux2` can be folded into the `f` argument. -/
lemma permutations_aux2_comp_append {t : α} {ts ys : list α} {r : list β} (f : list α → β) :
(permutations_aux2 t [] r ys $ λ x, f (x ++ ts)).2 = (permutations_aux2 t ts r ys f).2 :=
begin
induction ys generalizing f,
{ simp },
{ simp [ys_ih (λ xs, f (ys_hd :: xs))] },
end
lemma map_permutations_aux2' {α β α' β'} (g : α → α') (g' : β → β')
(t : α) (ts ys : list α) (r : list β) (f : list α → β) (f' : list α' → β')
(H : ∀ a, g' (f a) = f' (map g a)) :
map g' (permutations_aux2 t ts r ys f).2 =
(permutations_aux2 (g t) (map g ts) (map g' r) (map g ys) f').2 :=
begin
induction ys generalizing f f'; simp *,
apply ys_ih, simp [H],
end
/-- The `f` argument to `permutations_aux2` when `r = []` can be eliminated. -/
lemma map_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts [] ys id).2.map f = (permutations_aux2 t ts [] ys f).2 :=
begin
rw [map_permutations_aux2' id, map_id, map_id], refl,
simp
end
/-- An expository lemma to show how all of `ts`, `r`, and `f` can be eliminated from
`permutations_aux2`.
`(permutations_aux2 t [] [] ys id).2`, which appears on the RHS, is a list whose elements are
produced by inserting `t` into every non-terminal position of `ys` in order. As an example:
```lean
#eval permutations_aux2 1 [] [] [2, 3, 4] id
-- [[1, 2, 3, 4], [2, 1, 3, 4], [2, 3, 1, 4]]
```
-/
lemma permutations_aux2_snd_eq (t : α) (ts : list α) (r : list β) (ys : list α) (f : list α → β) :
(permutations_aux2 t ts r ys f).2 =
(permutations_aux2 t [] [] ys id).2.map (λ x, f (x ++ ts)) ++ r :=
by rw [← permutations_aux2_append, map_permutations_aux2, permutations_aux2_comp_append]
lemma map_map_permutations_aux2 {α α'} (g : α → α') (t : α) (ts ys : list α) :
map (map g) (permutations_aux2 t ts [] ys id).2 =
(permutations_aux2 (g t) (map g ts) [] (map g ys) id).2 :=
map_permutations_aux2' _ _ _ _ _ _ _ _ (λ _, rfl)
lemma map_map_permutations'_aux (f : α → β) (t : α) (ts : list α) :
map (map f) (permutations'_aux t ts) = permutations'_aux (f t) (map f ts) :=
by induction ts with a ts ih; [refl, {simp [← ih], refl}]
lemma permutations'_aux_eq_permutations_aux2 (t : α) (ts : list α) :
permutations'_aux t ts = (permutations_aux2 t [] [ts ++ [t]] ts id).2 :=
begin
induction ts with a ts ih, {refl},
simp [permutations'_aux, permutations_aux2_snd_cons, ih],
simp only [← permutations_aux2_append] {single_pass := tt},
simp [map_permutations_aux2],
end
lemma mem_permutations_aux2 {t : α} {ts : list α} {ys : list α} {l l' : list α} :
l' ∈ (permutations_aux2 t ts [] ys (append l)).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l' = l ++ l₁ ++ t :: l₂ ++ ts :=
begin
induction ys with y ys ih generalizing l,
{ simp {contextual := tt} },
rw [permutations_aux2_snd_cons, show (λ (x : list α), l ++ y :: x) = append (l ++ [y]),
by funext; simp, mem_cons_iff, ih], split,
{ rintro (e | ⟨l₁, l₂, l0, ye, _⟩),
{ subst l', exact ⟨[], y::ys, by simp⟩ },
{ substs l' ys, exact ⟨y::l₁, l₂, l0, by simp⟩ } },
{ rintro ⟨_ | ⟨y', l₁⟩, l₂, l0, ye, rfl⟩,
{ simp [ye] },
{ simp only [cons_append] at ye, rcases ye with ⟨rfl, rfl⟩,
exact or.inr ⟨l₁, l₂, l0, by simp⟩ } }
end
lemma mem_permutations_aux2' {t : α} {ts : list α} {ys : list α} {l : list α} :
l ∈ (permutations_aux2 t ts [] ys id).2 ↔
∃ l₁ l₂, l₂ ≠ [] ∧ ys = l₁ ++ l₂ ∧ l = l₁ ++ t :: l₂ ++ ts :=
by rw [show @id (list α) = append nil, by funext; refl]; apply mem_permutations_aux2
lemma length_permutations_aux2 (t : α) (ts : list α) (ys : list α) (f : list α → β) :
length (permutations_aux2 t ts [] ys f).2 = length ys :=
by induction ys generalizing f; simp *
lemma foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
foldr (λy r, (permutations_aux2 t ts r y id).2) r L =
L.bind (λ y, (permutations_aux2 t ts [] y id).2) ++ r :=
by induction L with l L ih; [refl, {simp [ih], rw ← permutations_aux2_append}]
lemma mem_foldr_permutations_aux2 {t : α} {ts : list α} {r L : list (list α)} {l' : list α} :
l' ∈ foldr (λy r, (permutations_aux2 t ts r y id).2) r L ↔
l' ∈ r ∨ ∃ l₁ l₂, l₁ ++ l₂ ∈ L ∧ l₂ ≠ [] ∧ l' = l₁ ++ t :: l₂ ++ ts :=
have (∃ (a : list α), a ∈ L ∧
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ a = l₁ ++ l₂ ∧ l' = l₁ ++ t :: (l₂ ++ ts)) ↔
∃ (l₁ l₂ : list α), ¬l₂ = nil ∧ l₁ ++ l₂ ∈ L ∧ l' = l₁ ++ t :: (l₂ ++ ts),
from ⟨λ ⟨a, aL, l₁, l₂, l0, e, h⟩, ⟨l₁, l₂, l0, e ▸ aL, h⟩,
λ ⟨l₁, l₂, l0, aL, h⟩, ⟨_, aL, l₁, l₂, l0, rfl, h⟩⟩,
by rw foldr_permutations_aux2; simp [mem_permutations_aux2', this,
or.comm, or.left_comm, or.assoc, and.comm, and.left_comm, and.assoc]
lemma length_foldr_permutations_aux2 (t : α) (ts : list α) (r L : list (list α)) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = sum (map length L) + length r :=
by simp [foldr_permutations_aux2, (∘), length_permutations_aux2]
lemma length_foldr_permutations_aux2' (t : α) (ts : list α) (r L : list (list α))
(n) (H : ∀ l ∈ L, length l = n) :
length (foldr (λy r, (permutations_aux2 t ts r y id).2) r L) = n * length L + length r :=
begin
rw [length_foldr_permutations_aux2, (_ : sum (map length L) = n * length L)],
induction L with l L ih, {simp},
have sum_map : sum (map length L) = n * length L :=
ih (λ l m, H l (mem_cons_of_mem _ m)),
have length_l : length l = n := H _ (mem_cons_self _ _),
simp [sum_map, length_l, mul_add, add_comm]
end
@[simp] lemma permutations_aux_nil (is : list α) : permutations_aux [] is = [] :=
by rw [permutations_aux, permutations_aux.rec]
@[simp] lemma permutations_aux_cons (t : α) (ts is : list α) :
permutations_aux (t :: ts) is = foldr (λy r, (permutations_aux2 t ts r y id).2)
(permutations_aux ts (t::is)) (permutations is) :=
by rw [permutations_aux, permutations_aux.rec]; refl
@[simp] lemma permutations_nil : permutations ([] : list α) = [[]] :=
by rw [permutations, permutations_aux_nil]
lemma map_permutations_aux (f : α → β) : ∀ (ts is : list α),
map (map f) (permutations_aux ts is) = permutations_aux (map f ts) (map f is) :=
begin
refine permutations_aux.rec (by simp) _,
introv IH1 IH2, rw map at IH2,
simp only [foldr_permutations_aux2, map_append, map, map_map_permutations_aux2, permutations,
bind_map, IH1, append_assoc, permutations_aux_cons, cons_bind, ← IH2, map_bind],
end
lemma map_permutations (f : α → β) (ts : list α) :
map (map f) (permutations ts) = permutations (map f ts) :=
by rw [permutations, permutations, map, map_permutations_aux, map]
lemma map_permutations' (f : α → β) (ts : list α) :
map (map f) (permutations' ts) = permutations' (map f ts) :=
by induction ts with t ts ih; [refl, simp [← ih, map_bind, ← map_map_permutations'_aux, bind_map]]
lemma permutations_aux_append (is is' ts : list α) :
permutations_aux (is ++ ts) is' =
(permutations_aux is is').map (++ ts) ++ permutations_aux ts (is.reverse ++ is') :=
begin
induction is with t is ih generalizing is', {simp},
simp [foldr_permutations_aux2, ih, bind_map],
congr' 2, funext ys, rw [map_permutations_aux2],
simp only [← permutations_aux2_comp_append] {single_pass := tt},
simp only [id, append_assoc],
end
lemma permutations_append (is ts : list α) :
permutations (is ++ ts) = (permutations is).map (++ ts) ++ permutations_aux ts is.reverse :=
by simp [permutations, permutations_aux_append]
end list
|
12e124d4c1ffd0899c3717ace6d5a9ef98b6eb6f | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/stuckTC.lean | ef58060470a64b4eba296f6f8be3ec060a2abbb8 | [
"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,256 | lean | namespace Ex1
inductive Ty where
| int
| bool
| fn (a ty : Ty)
@[reducible] def Ty.interp : Ty → Type
| int => Int
| bool => Bool
| fn a b => a.interp → b.interp
def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp :=
f x y
def f (a b : Ty.bool.interp) : Ty.bool.interp :=
test (.==.) a b
end Ex1
namespace Ex2
inductive Ty where
| int
| bool
@[reducible] def Ty.interp : Ty → Type
| int => Int
| bool => Bool
def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp :=
f x y
def f (a b : Ty.bool.interp) : Ty.bool.interp :=
test (.==.) a b
end Ex2
namespace Ex3
inductive Ty where
| int
| bool
@[reducible] def Ty.interp (ty : Ty) : Type :=
Ty.casesOn (motive := fun _ => Type) ty Int Bool
/-
The discrimination tree module does not perform iota reduction. Thus, it does
not reduce the definition above, and we cannot synthesize `BEq Ty.bool.interp`.
We can workaround using `match` as in the ex
-/
def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp :=
f x y
def f (a b : Ty.bool.interp) : Ty.bool.interp :=
test (.==.) a b
end Ex3
|
d00f221eaf7234ba281a537af741ca1cefe68112 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/ResolveName.lean | 62818f0046910244338af63bacea12ec044f3411 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 10,246 | 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, Sebastian Ullrich
-/
import Lean.Data.OpenDecl
import Lean.Hygiene
import Lean.Modifiers
import Lean.Exception
namespace Lean
/-!
We use aliases to implement the `export <id> (<id>+)` command.
An `export A (x)` in the namespace `B` produces an alias `B.x ~> A.x`.
-/
abbrev AliasState := SMap Name (List Name)
abbrev AliasEntry := Name × Name
def addAliasEntry (s : AliasState) (e : AliasEntry) : AliasState :=
match s.find? e.1 with
| none => s.insert e.1 [e.2]
| some es => if es.elem e.2 then s else s.insert e.1 (e.2 :: es)
builtin_initialize aliasExtension : SimplePersistentEnvExtension AliasEntry AliasState ←
registerSimplePersistentEnvExtension {
name := `aliasesExt,
addEntryFn := addAliasEntry,
addImportedFn := fun es => mkStateFromImportedEntries addAliasEntry {} es |>.switch
}
/- Add alias `a` for `e` -/
@[export lean_add_alias] def addAlias (env : Environment) (a : Name) (e : Name) : Environment :=
aliasExtension.addEntry env (a, e)
def getAliasState (env : Environment) : AliasState :=
aliasExtension.getState env
def getAliases (env : Environment) (a : Name) : List Name :=
match aliasExtension.getState env |>.find? a with
| none => []
| some es => es
-- slower, but only used in the pretty printer
def getRevAliases (env : Environment) (e : Name) : List Name :=
(aliasExtension.getState env).fold (fun as a es => if List.contains es e then a :: as else as) []
/- Global name resolution -/
namespace ResolveName
/- Check whether `ns ++ id` is a valid namepace name and/or there are aliases names `ns ++ id`. -/
private def resolveQualifiedName (env : Environment) (ns : Name) (id : Name) : List Name :=
let resolvedId := ns ++ id
let resolvedIds := getAliases env resolvedId
if env.contains resolvedId && (!id.isAtomic || !isProtected env resolvedId) then
resolvedId :: resolvedIds
else
-- Check whether environment contains the private version. That is, `_private.<module_name>.ns.id`.
let resolvedIdPrv := mkPrivateName env resolvedId
if env.contains resolvedIdPrv then resolvedIdPrv :: resolvedIds
else resolvedIds
/- Check surrounding namespaces -/
private def resolveUsingNamespace (env : Environment) (id : Name) : Name → List Name
| ns@(Name.str p _ _) =>
match resolveQualifiedName env ns id with
| [] => resolveUsingNamespace env id p
| resolvedIds => resolvedIds
| _ => []
/- Check exact name -/
private def resolveExact (env : Environment) (id : Name) : Option Name :=
if id.isAtomic then none
else
let resolvedId := id.replacePrefix rootNamespace Name.anonymous
if env.contains resolvedId then some resolvedId
else
-- We also allow `_root` when accessing private declarations.
-- If we change our minds, we should just replace `resolvedId` with `id`
let resolvedIdPrv := mkPrivateName env resolvedId
if env.contains resolvedIdPrv then some resolvedIdPrv
else none
/- Check `OpenDecl`s -/
private def resolveOpenDecls (env : Environment) (id : Name) : List OpenDecl → List Name → List Name
| [], resolvedIds => resolvedIds
| OpenDecl.simple ns exs :: openDecls, resolvedIds =>
if exs.elem id then
resolveOpenDecls env id openDecls resolvedIds
else
let newResolvedIds := resolveQualifiedName env ns id
resolveOpenDecls env id openDecls (newResolvedIds ++ resolvedIds)
| OpenDecl.explicit openedId resolvedId :: openDecls, resolvedIds =>
let resolvedIds :=
if openedId == id then
resolvedId :: resolvedIds
else if openedId.isPrefixOf id then
let candidate := id.replacePrefix openedId resolvedId
if env.contains candidate then
candidate :: resolvedIds
else
resolvedIds
else
resolvedIds
resolveOpenDecls env id openDecls resolvedIds
def resolveGlobalName (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : List (Name × List String) :=
-- decode macro scopes from name before recursion
let extractionResult := extractMacroScopes id
let rec loop (id : Name) (projs : List String) : List (Name × List String) :=
match id with
| Name.str p s _ =>
-- NOTE: we assume that macro scopes always belong to the projected constant, not the projections
let id := { extractionResult with name := id }.review
match resolveUsingNamespace env id ns with
| resolvedIds@(_ :: _) => resolvedIds.eraseDups.map fun id => (id, projs)
| [] =>
match resolveExact env id with
| some newId => [(newId, projs)]
| none =>
let resolvedIds := if env.contains id then [id] else []
let idPrv := mkPrivateName env id
let resolvedIds := if env.contains idPrv then [idPrv] ++ resolvedIds else resolvedIds
let resolvedIds := resolveOpenDecls env id openDecls resolvedIds
let resolvedIds := getAliases env id ++ resolvedIds
match resolvedIds with
| _ :: _ => resolvedIds.eraseDups.map fun id => (id, projs)
| [] => loop p (s::projs)
| _ => []
loop extractionResult.name []
/- Namespace resolution -/
def resolveNamespaceUsingScope (env : Environment) (n : Name) : Name → Option Name
| Name.anonymous => if env.isNamespace n then some n else none
| ns@(Name.str p _ _) => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingScope env n p
| _ => unreachable!
def resolveNamespaceUsingOpenDecls (env : Environment) (n : Name) : List OpenDecl → Option Name
| [] => none
| OpenDecl.simple ns [] :: ds => if env.isNamespace (ns ++ n) then some (ns ++ n) else resolveNamespaceUsingOpenDecls env n ds
| _ :: ds => resolveNamespaceUsingOpenDecls env n ds
/-
Given a name `id` try to find namespace it refers to. The resolution procedure works as follows
1- If `id` is in the scope of `namespace` commands the namespace `s_1. ... . s_n`,
then return `s_1 . ... . s_i ++ n` if it is the name of an existing namespace. We search "backwards".
2- If `id` is the extact name of an existing namespace, then return `id`
3- Finally, for each command `open N`, return `N ++ n` if it is the name of an existing namespace.
We search "backwards" again. That is, we try the most recent `open` command first.
We only consider simple `open` commands. -/
def resolveNamespace? (env : Environment) (ns : Name) (openDecls : List OpenDecl) (id : Name) : Option Name :=
match resolveNamespaceUsingScope env id ns with
| some n => some n
| none =>
match resolveNamespaceUsingOpenDecls env id openDecls with
| some n => some n
| none => none
end ResolveName
class MonadResolveName (m : Type → Type) where
getCurrNamespace : m Name
getOpenDecls : m (List OpenDecl)
export MonadResolveName (getCurrNamespace getOpenDecls)
instance (m n) [MonadLift m n] [MonadResolveName m] : MonadResolveName n where
getCurrNamespace := liftM (m:=m) getCurrNamespace
getOpenDecls := liftM (m:=m) getOpenDecls
/-
Given a name `n`, return a list of possible interpretations.
Each interpretation is a pair `(declName, fieldList)`, where `declName`
is the name of a declaration in the current environment, and `fieldList` are
(potential) field names.
The pair is needed because in Lean `.` may be part of a qualified name or
a field (aka dot-notation).
As an example, consider the following definitions
```
def Boo.x := 1
def Foo.x := 2
def Foo.x.y := 3
```
After `open Foo`, we have
- `resolveGlobalName x` => `[(Foo.x, [])]`
- `resolveGlobalName x.y` => `[(Foo.x.y, [])]`
- `resolveGlobalName x.z.w` => `[(Foo.x, [z, w])]`
After `open Foo open Boo`, we have
- `resolveGlobalName x` => `[(Foo.x, []), (Boo.x, [])]`
- `resolveGlobalName x.y` => `[(Foo.x.y, [])]`
- `resolveGlobalName x.z.w` => `[(Foo.x, [z, w]), (Boo.x, [z, w])]`
-/
def resolveGlobalName [Monad m] [MonadResolveName m] [MonadEnv m] (id : Name) : m (List (Name × List String)) := do
return ResolveName.resolveGlobalName (← getEnv) (← getCurrNamespace) (← getOpenDecls) id
def resolveNamespace [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Name) : m Name := do
match ResolveName.resolveNamespace? (← getEnv) (← getCurrNamespace) (← getOpenDecls) id with
| some ns => return ns
| none => throwError s!"unknown namespace '{id}'"
/--
Similar to `resolveGlobalName`, but discard any candidate whose `fieldList` is not empty.
For identifiers taken from syntax, use `resolveGlobalConst` instead, which respects preresolved names. -/
def resolveGlobalConstCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m (List Name) := do
let cs ← resolveGlobalName n
let cs := cs.filter fun (_, fieldList) => fieldList.isEmpty
if cs.isEmpty then throwUnknownConstant n
return cs.map (·.1)
/-- For identifiers taken from syntax, use `resolveGlobalConstNoOverload` instead, which respects preresolved names. -/
def resolveGlobalConstNoOverloadCore [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (n : Name) : m Name := do
let cs ← resolveGlobalConstCore n
match cs with
| [c] => pure c
| _ => throwError s!"ambiguous identifier '{mkConst n}', possible interpretations: {cs.map mkConst}"
def resolveGlobalConst [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] : Syntax → m (List Name)
| stx@(Syntax.ident _ _ n pre) => do
let pre := pre.filterMap fun (n, fields) => if fields.isEmpty then some n else none
if pre.isEmpty then
withRef stx <| resolveGlobalConstCore n
else
return pre
| stx => throwErrorAt stx s!"expected identifier"
def resolveGlobalConstNoOverload [Monad m] [MonadResolveName m] [MonadEnv m] [MonadError m] (id : Syntax) : m Name := do
let cs ← resolveGlobalConst id
match cs with
| [c] => pure c
| _ => throwErrorAt id s!"ambiguous identifier '{id}', possible interpretations: {cs.map mkConst}"
end Lean
|
95cbbe3dd1c1bc7049914974dcb128ef77293d58 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/geometry/euclidean/angle/oriented/basic.lean | 34957f68fe9b25d718b6ca17025c01051c8739fe | [
"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 | 48,332 | lean | /-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Heather Macbeth
-/
import analysis.inner_product_space.two_dim
import geometry.euclidean.angle.unoriented.basic
/-!
# Oriented angles.
This file defines oriented angles in real inner product spaces.
## Main definitions
* `orientation.oangle` is the oriented angle between two vectors with respect to an orientation.
## Implementation notes
The definitions here use the `real.angle` type, angles modulo `2 * π`. For some purposes,
angles modulo `π` are more convenient, because results are true for such angles with less
configuration dependence. Results that are only equalities modulo `π` can be represented
modulo `2 * π` as equalities of `(2 : ℤ) • θ`.
## References
* Evan Chen, Euclidean Geometry in Mathematical Olympiads.
-/
noncomputable theory
open finite_dimensional complex
open_locale real real_inner_product_space complex_conjugate
namespace orientation
local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ
local attribute [instance] complex.finrank_real_complex_fact
variables {V V' : Type*}
variables [normed_add_comm_group V] [normed_add_comm_group V']
variables [inner_product_space ℝ V] [inner_product_space ℝ V']
variables [fact (finrank ℝ V = 2)] [fact (finrank ℝ V' = 2)] (o : orientation ℝ V (fin 2))
local notation `ω` := o.area_form
/-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0.
See `inner_product_geometry.angle` for the corresponding unoriented angle definition. -/
def oangle (x y : V) : real.angle :=
complex.arg (o.kahler x y)
/-- Oriented angles are continuous when the vectors involved are nonzero. -/
lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) :
continuous_at (λ y : V × V, o.oangle y.1 y.2) x :=
begin
refine (complex.continuous_at_arg_coe_angle _).comp _,
{ exact o.kahler_ne_zero hx1 hx2 },
exact ((continuous_of_real.comp continuous_inner).add
((continuous_of_real.comp o.area_form'.continuous₂).mul continuous_const)).continuous_at,
end
/-- If the first vector passed to `oangle` is 0, the result is 0. -/
@[simp] lemma oangle_zero_left (x : V) : o.oangle 0 x = 0 :=
by simp [oangle]
/-- If the second vector passed to `oangle` is 0, the result is 0. -/
@[simp] lemma oangle_zero_right (x : V) : o.oangle x 0 = 0 :=
by simp [oangle]
/-- If the two vectors passed to `oangle` are the same, the result is 0. -/
@[simp] lemma oangle_self (x : V) : o.oangle x x = 0 :=
begin
simp only [oangle, kahler_apply_self, ← complex.of_real_pow],
convert quotient_add_group.coe_zero _,
apply arg_of_real_of_nonneg,
positivity,
end
/-- If the angle between two vectors is nonzero, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : x ≠ 0 :=
by { rintro rfl, simpa using h }
/-- If the angle between two vectors is nonzero, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : y ≠ 0 :=
by { rintro rfl, simpa using h }
/-- If the angle between two vectors is nonzero, the vectors are not equal. -/
lemma ne_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : x ≠ y :=
by { rintro rfl, simpa using h }
/-- If the angle between two vectors is `π`, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : x ≠ 0 :=
o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `π`, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : y ≠ 0 :=
o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `π`, the vectors are not equal. -/
lemma ne_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : x ≠ y :=
o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `π / 2`, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : x ≠ 0 :=
o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `π / 2`, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : y ≠ 0 :=
o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `π / 2`, the vectors are not equal. -/
lemma ne_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : x ≠ y :=
o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `-π / 2`, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) :
x ≠ 0 :=
o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `-π / 2`, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) :
y ≠ 0 :=
o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the angle between two vectors is `-π / 2`, the vectors are not equal. -/
lemma ne_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) :
x ≠ y :=
o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0)
/-- If the sign of the angle between two vectors is nonzero, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : x ≠ 0 :=
o.left_ne_zero_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1
/-- If the sign of the angle between two vectors is nonzero, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : y ≠ 0 :=
o.right_ne_zero_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1
/-- If the sign of the angle between two vectors is nonzero, the vectors are not equal. -/
lemma ne_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : x ≠ y :=
o.ne_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1
/-- If the sign of the angle between two vectors is positive, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : x ≠ 0 :=
o.left_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- If the sign of the angle between two vectors is positive, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : y ≠ 0 :=
o.right_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- If the sign of the angle between two vectors is positive, the vectors are not equal. -/
lemma ne_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : x ≠ y :=
o.ne_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- If the sign of the angle between two vectors is negative, the first vector is nonzero. -/
lemma left_ne_zero_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : x ≠ 0 :=
o.left_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- If the sign of the angle between two vectors is negative, the second vector is nonzero. -/
lemma right_ne_zero_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : y ≠ 0 :=
o.right_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- If the sign of the angle between two vectors is negative, the vectors are not equal. -/
lemma ne_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : x ≠ y :=
o.ne_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0)
/-- Swapping the two vectors passed to `oangle` negates the angle. -/
lemma oangle_rev (x y : V) : o.oangle y x = -o.oangle x y :=
by simp only [oangle, o.kahler_swap y x, complex.arg_conj_coe_angle]
/-- Adding the angles between two vectors in each order results in 0. -/
@[simp] lemma oangle_add_oangle_rev (x y : V) : o.oangle x y + o.oangle y x = 0 :=
by simp [o.oangle_rev y x]
/-- Negating the first vector passed to `oangle` adds `π` to the angle. -/
lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
o.oangle (-x) y = o.oangle x y + π :=
begin
simp only [oangle, map_neg],
convert complex.arg_neg_coe_angle _,
exact o.kahler_ne_zero hx hy,
end
/-- Negating the second vector passed to `oangle` adds `π` to the angle. -/
lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
o.oangle x (-y) = o.oangle x y + π :=
begin
simp only [oangle, map_neg],
convert complex.arg_neg_coe_angle _,
exact o.kahler_ne_zero hx hy,
end
/-- Negating the first vector passed to `oangle` does not change twice the angle. -/
@[simp] lemma two_zsmul_oangle_neg_left (x y : V) :
(2 : ℤ) • o.oangle (-x) y = (2 : ℤ) • o.oangle x y :=
begin
by_cases hx : x = 0,
{ simp [hx] },
{ by_cases hy : y = 0,
{ simp [hy] },
{ simp [o.oangle_neg_left hx hy] } }
end
/-- Negating the second vector passed to `oangle` does not change twice the angle. -/
@[simp] lemma two_zsmul_oangle_neg_right (x y : V) :
(2 : ℤ) • o.oangle x (-y) = (2 : ℤ) • o.oangle x y :=
begin
by_cases hx : x = 0,
{ simp [hx] },
{ by_cases hy : y = 0,
{ simp [hy] },
{ simp [o.oangle_neg_right hx hy] } }
end
/-- Negating both vectors passed to `oangle` does not change the angle. -/
@[simp] lemma oangle_neg_neg (x y : V) : o.oangle (-x) (-y) = o.oangle x y :=
by simp [oangle]
/-- Negating the first vector produces the same angle as negating the second vector. -/
lemma oangle_neg_left_eq_neg_right (x y : V) : o.oangle (-x) y = o.oangle x (-y) :=
by rw [←neg_neg y, oangle_neg_neg, neg_neg]
/-- The angle between the negation of a nonzero vector and that vector is `π`. -/
@[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : o.oangle (-x) x = π :=
by simp [oangle_neg_left, hx]
/-- The angle between a nonzero vector and its negation is `π`. -/
@[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : o.oangle x (-x) = π :=
by simp [oangle_neg_right, hx]
/-- Twice the angle between the negation of a vector and that vector is 0. -/
@[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • o.oangle (-x) x = 0 :=
begin
by_cases hx : x = 0;
simp [hx]
end
/-- Twice the angle between a vector and its negation is 0. -/
@[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • o.oangle x (-x) = 0 :=
begin
by_cases hx : x = 0;
simp [hx]
end
/-- Adding the angles between two vectors in each order, with the first vector in each angle
negated, results in 0. -/
@[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) :
o.oangle (-x) y + o.oangle (-y) x = 0 :=
by rw [oangle_neg_left_eq_neg_right, oangle_rev, add_left_neg]
/-- Adding the angles between two vectors in each order, with the second vector in each angle
negated, results in 0. -/
@[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) :
o.oangle x (-y) + o.oangle y (-x) = 0 :=
by rw [o.oangle_rev (-x), oangle_neg_left_eq_neg_right, add_neg_self]
/-- Multiplying the first vector passed to `oangle` by a positive real does not change the
angle. -/
@[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
o.oangle (r • x) y = o.oangle x y :=
by simp [oangle, complex.arg_real_mul _ hr]
/-- Multiplying the second vector passed to `oangle` by a positive real does not change the
angle. -/
@[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) :
o.oangle x (r • y) = o.oangle x y :=
by simp [oangle, complex.arg_real_mul _ hr]
/-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle
as negating that vector. -/
@[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
o.oangle (r • x) y = o.oangle (-x) y :=
by rw [←neg_neg r, neg_smul, ←smul_neg, o.oangle_smul_left_of_pos _ _ (neg_pos_of_neg hr)]
/-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle
as negating that vector. -/
@[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) :
o.oangle x (r • y) = o.oangle x (-y) :=
by rw [←neg_neg r, neg_smul, ←smul_neg, o.oangle_smul_right_of_pos _ _ (neg_pos_of_neg hr)]
/-- The angle between a nonnegative multiple of a vector and that vector is 0. -/
@[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) :
o.oangle (r • x) x = 0 :=
begin
rcases hr.lt_or_eq with (h|h),
{ simp [h] },
{ simp [h.symm] }
end
/-- The angle between a vector and a nonnegative multiple of that vector is 0. -/
@[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) :
o.oangle x (r • x) = 0 :=
begin
rcases hr.lt_or_eq with (h|h),
{ simp [h] },
{ simp [h.symm] }
end
/-- The angle between two nonnegative multiples of the same vector is 0. -/
@[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) :
o.oangle (r₁ • x) (r₂ • x) = 0 :=
begin
rcases hr₁.lt_or_eq with (h|h),
{ simp [h, hr₂] },
{ simp [h.symm] }
end
/-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the
angle. -/
@[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) :
(2 : ℤ) • o.oangle (r • x) y = (2 : ℤ) • o.oangle x y :=
begin
rcases hr.lt_or_lt with (h|h);
simp [h]
end
/-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the
angle. -/
@[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) :
(2 : ℤ) • o.oangle x (r • y) = (2 : ℤ) • o.oangle x y :=
begin
rcases hr.lt_or_lt with (h|h);
simp [h]
end
/-- Twice the angle between a multiple of a vector and that vector is 0. -/
@[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} :
(2 : ℤ) • o.oangle (r • x) x = 0 :=
begin
rcases lt_or_le r 0 with (h|h);
simp [h]
end
/-- Twice the angle between a vector and a multiple of that vector is 0. -/
@[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} :
(2 : ℤ) • o.oangle x (r • x) = 0 :=
begin
rcases lt_or_le r 0 with (h|h);
simp [h]
end
/-- Twice the angle between two multiples of a vector is 0. -/
@[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} :
(2 : ℤ) • o.oangle (r₁ • x) (r₂ • x) = 0 :=
begin
by_cases h : r₁ = 0;
simp [h]
end
/-- If the spans of two vectors are equal, twice angles with those vectors on the left are
equal. -/
lemma two_zsmul_oangle_left_of_span_eq {x y : V} (z : V) (h : (ℝ ∙ x) = ℝ ∙ y) :
(2 : ℤ) • o.oangle x z = (2 : ℤ) • o.oangle y z :=
begin
rw submodule.span_singleton_eq_span_singleton at h,
rcases h with ⟨r, rfl⟩,
exact (o.two_zsmul_oangle_smul_left_of_ne_zero _ _ (units.ne_zero _)).symm
end
/-- If the spans of two vectors are equal, twice angles with those vectors on the right are
equal. -/
lemma two_zsmul_oangle_right_of_span_eq (x : V) {y z : V} (h : (ℝ ∙ y) = ℝ ∙ z) :
(2 : ℤ) • o.oangle x y = (2 : ℤ) • o.oangle x z :=
begin
rw submodule.span_singleton_eq_span_singleton at h,
rcases h with ⟨r, rfl⟩,
exact (o.two_zsmul_oangle_smul_right_of_ne_zero _ _ (units.ne_zero _)).symm
end
/-- If the spans of two pairs of vectors are equal, twice angles between those vectors are
equal. -/
lemma two_zsmul_oangle_of_span_eq_of_span_eq {w x y z : V} (hwx : (ℝ ∙ w) = ℝ ∙ x)
(hyz : (ℝ ∙ y) = ℝ ∙ z) : (2 : ℤ) • o.oangle w y = (2 : ℤ) • o.oangle x z :=
by rw [(o).two_zsmul_oangle_left_of_span_eq y hwx, (o).two_zsmul_oangle_right_of_span_eq x hyz]
/-- The oriented angle between two vectors is zero if and only if the angle with the vectors
swapped is zero. -/
lemma oangle_eq_zero_iff_oangle_rev_eq_zero {x y : V} : o.oangle x y = 0 ↔ o.oangle y x = 0 :=
by rw [oangle_rev, neg_eq_zero]
/-- The oriented angle between two vectors is zero if and only if they are on the same ray. -/
lemma oangle_eq_zero_iff_same_ray {x y : V} : o.oangle x y = 0 ↔ same_ray ℝ x y :=
begin
rw [oangle, kahler_apply_apply, complex.arg_coe_angle_eq_iff_eq_to_real, real.angle.to_real_zero,
complex.arg_eq_zero_iff],
simpa using o.nonneg_inner_and_area_form_eq_zero_iff_same_ray x y,
end
/-- The oriented angle between two vectors is `π` if and only if the angle with the vectors
swapped is `π`. -/
lemma oangle_eq_pi_iff_oangle_rev_eq_pi {x y : V} : o.oangle x y = π ↔ o.oangle y x = π :=
by rw [oangle_rev, neg_eq_iff_eq_neg, real.angle.neg_coe_pi]
/-- The oriented angle between two vectors is `π` if and only they are nonzero and the first is
on the same ray as the negation of the second. -/
lemma oangle_eq_pi_iff_same_ray_neg {x y : V} :
o.oangle x y = π ↔ x ≠ 0 ∧ y ≠ 0 ∧ same_ray ℝ x (-y) :=
begin
rw [←o.oangle_eq_zero_iff_same_ray],
split,
{ intro h,
by_cases hx : x = 0, { simpa [hx, real.angle.pi_ne_zero.symm] using h },
by_cases hy : y = 0, { simpa [hy, real.angle.pi_ne_zero.symm] using h },
refine ⟨hx, hy, _⟩,
rw [o.oangle_neg_right hx hy, h, real.angle.coe_pi_add_coe_pi] },
{ rintro ⟨hx, hy, h⟩,
rwa [o.oangle_neg_right hx hy, ←real.angle.sub_coe_pi_eq_add_coe_pi, sub_eq_zero] at h }
end
/-- The oriented angle between two vectors is zero or `π` if and only if those two vectors are
not linearly independent. -/
lemma oangle_eq_zero_or_eq_pi_iff_not_linear_independent {x y : V} :
(o.oangle x y = 0 ∨ o.oangle x y = π) ↔ ¬ linear_independent ℝ ![x, y] :=
by rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg,
same_ray_or_ne_zero_and_same_ray_neg_iff_not_linear_independent]
/-- The oriented angle between two vectors is zero or `π` if and only if the first vector is zero
or the second is a multiple of the first. -/
lemma oangle_eq_zero_or_eq_pi_iff_right_eq_smul {x y : V} :
(o.oangle x y = 0 ∨ o.oangle x y = π) ↔ (x = 0 ∨ ∃ r : ℝ, y = r • x) :=
begin
rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg],
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with h|⟨-, -, h⟩,
{ by_cases hx : x = 0, { simp [hx] },
obtain ⟨r, -, rfl⟩ := h.exists_nonneg_left hx,
exact or.inr ⟨r, rfl⟩ },
{ by_cases hx : x = 0, { simp [hx] },
obtain ⟨r, -, hy⟩ := h.exists_nonneg_left hx,
refine or.inr ⟨-r, _⟩,
simp [hy] } },
{ rcases h with rfl|⟨r, rfl⟩, { simp },
by_cases hx : x = 0, { simp [hx] },
rcases lt_trichotomy r 0 with hr|hr|hr,
{ rw ←neg_smul,
exact or.inr ⟨hx, smul_ne_zero hr.ne hx,
same_ray_pos_smul_right x (left.neg_pos_iff.2 hr)⟩ },
{ simp [hr] },
{ exact or.inl (same_ray_pos_smul_right x hr) } }
end
/-- The oriented angle between two vectors is not zero or `π` if and only if those two vectors
are linearly independent. -/
lemma oangle_ne_zero_and_ne_pi_iff_linear_independent {x y : V} :
(o.oangle x y ≠ 0 ∧ o.oangle x y ≠ π) ↔ linear_independent ℝ ![x, y] :=
by rw [←not_or_distrib, ←not_iff_not, not_not, oangle_eq_zero_or_eq_pi_iff_not_linear_independent]
/-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/
lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ‖x‖ = ‖y‖ ∧ o.oangle x y = 0 :=
begin
rw oangle_eq_zero_iff_same_ray,
split,
{ rintros rfl,
simp },
{ rcases eq_or_ne y 0 with rfl | hy,
{ simp },
rintros ⟨h₁, h₂⟩,
obtain ⟨r, hr, rfl⟩ := h₂.exists_nonneg_right hy,
have : ‖y‖ ≠ 0 := by simpa using hy,
obtain rfl : r = 1,
{ apply mul_right_cancel₀ this,
simpa [norm_smul, _root_.abs_of_nonneg hr] using h₁ },
simp },
end
/-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/
lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) : x = y ↔ o.oangle x y = 0 :=
⟨λ he, ((o.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).2,
λ ha, (o.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨h, ha⟩⟩
/-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/
lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : o.oangle x y = 0) : x = y ↔ ‖x‖ = ‖y‖ :=
⟨λ he, ((o.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).1,
λ hn, (o.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨hn, h⟩⟩
/-- Given three nonzero vectors, the angle between the first and the second plus the angle
between the second and the third equals the angle between the first and the third. -/
@[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle x y + o.oangle y z = o.oangle x z :=
begin
simp_rw [oangle],
rw [←complex.arg_mul_coe_angle, o.kahler_mul y x z],
congr' 1,
convert complex.arg_real_mul _ (_ : 0 < ‖y‖ ^ 2) using 2,
{ norm_cast },
{ have : 0 < ‖y‖ := by simpa using hy,
positivity },
{ exact o.kahler_ne_zero hx hy, },
{ exact o.kahler_ne_zero hy hz }
end
/-- Given three nonzero vectors, the angle between the second and the third plus the angle
between the first and the second equals the angle between the first and the third. -/
@[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle y z + o.oangle x y = o.oangle x z :=
by rw [add_comm, o.oangle_add hx hy hz]
/-- Given three nonzero vectors, the angle between the first and the third minus the angle
between the first and the second equals the angle between the second and the third. -/
@[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle x z - o.oangle x y = o.oangle y z :=
by rw [sub_eq_iff_eq_add, o.oangle_add_swap hx hy hz]
/-- Given three nonzero vectors, the angle between the first and the third minus the angle
between the second and the third equals the angle between the first and the second. -/
@[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle x z - o.oangle y z = o.oangle x y :=
by rw [sub_eq_iff_eq_add, o.oangle_add hx hy hz]
/-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/
@[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle x y + o.oangle y z + o.oangle z x = 0 :=
by simp [hx, hy, hz]
/-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first
vector in each angle negated, results in π. If the vectors add to 0, this is a version of the
sum of the angles of a triangle. -/
@[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle (-x) y + o.oangle (-y) z + o.oangle (-z) x = π :=
by rw [o.oangle_neg_left hx hy, o.oangle_neg_left hy hz, o.oangle_neg_left hz hx,
(show o.oangle x y + π + (o.oangle y z + π) + (o.oangle z x + π) =
o.oangle x y + o.oangle y z + o.oangle z x + (π + π + π : real.angle), by abel),
o.oangle_add_cyc3 hx hy hz, real.angle.coe_pi_add_coe_pi, zero_add, zero_add]
/-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second
vector in each angle negated, results in π. If the vectors add to 0, this is a version of the
sum of the angles of a triangle. -/
@[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) :
o.oangle x (-y) + o.oangle y (-z) + o.oangle z (-x) = π :=
by simp_rw [←oangle_neg_left_eq_neg_right, o.oangle_add_cyc3_neg_left hx hy hz]
/-- Pons asinorum, oriented vector angle form. -/
lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) :
o.oangle x (x - y) = o.oangle (y - x) y :=
by simp [oangle, h]
/-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented
vector angle form. -/
lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ‖x‖ = ‖y‖) :
o.oangle y x = π - (2 : ℤ) • o.oangle (y - x) y :=
begin
rw two_zsmul,
rw [←o.oangle_sub_eq_oangle_sub_rev_of_norm_eq h] { occs := occurrences.pos [1] },
rw [eq_sub_iff_add_eq, ←oangle_neg_neg, ←add_assoc],
have hy : y ≠ 0,
{ rintro rfl,
rw [norm_zero, norm_eq_zero] at h,
exact hn h },
have hx : x ≠ 0 := norm_ne_zero_iff.1 (h.symm ▸ norm_ne_zero_iff.2 hy),
convert o.oangle_add_cyc3_neg_right (neg_ne_zero.2 hy) hx (sub_ne_zero_of_ne hn.symm);
simp
end
/-- The angle between two vectors, with respect to an orientation given by `orientation.map`
with a linear isometric equivalence, equals the angle between those two vectors, transformed by
the inverse of that equivalence, with respect to the original orientation. -/
@[simp] lemma oangle_map (x y : V') (f : V ≃ₗᵢ[ℝ] V') :
(orientation.map (fin 2) f.to_linear_equiv o).oangle x y = o.oangle (f.symm x) (f.symm y) :=
by simp [oangle, o.kahler_map]
@[simp] protected lemma _root_.complex.oangle (w z : ℂ) :
complex.orientation.oangle w z = complex.arg (conj w * z) :=
by simp [oangle]
/-- The oriented angle on an oriented real inner product space of dimension 2 can be evaluated in
terms of a complex-number representation of the space. -/
lemma oangle_map_complex (f : V ≃ₗᵢ[ℝ] ℂ)
(hf : (orientation.map (fin 2) f.to_linear_equiv o) = complex.orientation) (x y : V) :
o.oangle x y = complex.arg (conj (f x) * f y) :=
begin
rw [← complex.oangle, ← hf, o.oangle_map],
simp,
end
/-- Negating the orientation negates the value of `oangle`. -/
lemma oangle_neg_orientation_eq_neg (x y : V) : (-o).oangle x y = -(o.oangle x y) :=
by simp [oangle]
/-- The inner product of two vectors is the product of the norms and the cosine of the oriented
angle between the vectors. -/
lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) :
⟪x, y⟫ = ‖x‖ * ‖y‖ * real.angle.cos (o.oangle x y) :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
have : ‖x‖ ≠ 0 := by simpa using hx,
have : ‖y‖ ≠ 0 := by simpa using hy,
rw [oangle, real.angle.cos_coe, complex.cos_arg, o.abs_kahler],
{ simp only [kahler_apply_apply, real_smul, add_re, of_real_re, mul_re, I_re, of_real_im],
field_simp,
ring },
{ exact o.kahler_ne_zero hx hy }
end
/-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by
the product of the norms. -/
lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.angle.cos (o.oangle x y) = ⟪x, y⟫ / (‖x‖ * ‖y‖) :=
begin
rw o.inner_eq_norm_mul_norm_mul_cos_oangle,
field_simp [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy],
ring
end
/-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented
angle. -/
lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
real.angle.cos (o.oangle x y) = real.cos (inner_product_geometry.angle x y) :=
by rw [o.cos_oangle_eq_inner_div_norm_mul_norm hx hy, inner_product_geometry.cos_angle]
/-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/
lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
o.oangle x y = inner_product_geometry.angle x y ∨
o.oangle x y = -inner_product_geometry.angle x y :=
real.angle.cos_eq_real_cos_iff_eq_or_eq_neg.1 $ o.cos_oangle_eq_cos_angle hx hy
/-- The unoriented angle between two nonzero vectors is the absolute value of the oriented angle,
converted to a real. -/
lemma angle_eq_abs_oangle_to_real {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
inner_product_geometry.angle x y = |(o.oangle x y).to_real| :=
begin
have h0 := inner_product_geometry.angle_nonneg x y,
have hpi := inner_product_geometry.angle_le_pi x y,
rcases o.oangle_eq_angle_or_eq_neg_angle hx hy with (h|h),
{ rw [h, eq_comm, real.angle.abs_to_real_coe_eq_self_iff],
exact ⟨h0, hpi⟩ },
{ rw [h, eq_comm, real.angle.abs_to_real_neg_coe_eq_self_iff],
exact ⟨h0, hpi⟩ }
end
/-- If the sign of the oriented angle between two vectors is zero, either one of the vectors is
zero or the unoriented angle is 0 or π. -/
lemma eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero {x y : V}
(h : (o.oangle x y).sign = 0) :
x = 0 ∨ y = 0 ∨ inner_product_geometry.angle x y = 0 ∨ inner_product_geometry.angle x y = π :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
rw o.angle_eq_abs_oangle_to_real hx hy,
rw real.angle.sign_eq_zero_iff at h,
rcases h with h|h;
simp [h, real.pi_pos.le]
end
/-- If two unoriented angles are equal, and the signs of the corresponding oriented angles are
equal, then the oriented angles are equal (even in degenerate cases). -/
lemma oangle_eq_of_angle_eq_of_sign_eq {w x y z : V}
(h : inner_product_geometry.angle w x = inner_product_geometry.angle y z)
(hs : (o.oangle w x).sign = (o.oangle y z).sign) : o.oangle w x = o.oangle y z :=
begin
by_cases h0 : (w = 0 ∨ x = 0) ∨ (y = 0 ∨ z = 0),
{ have hs' : (o.oangle w x).sign = 0 ∧ (o.oangle y z).sign = 0,
{ rcases h0 with (rfl|rfl)|rfl|rfl,
{ simpa using hs.symm },
{ simpa using hs.symm },
{ simpa using hs },
{ simpa using hs } },
rcases hs' with ⟨hswx, hsyz⟩,
have h' : inner_product_geometry.angle w x = π / 2 ∧ inner_product_geometry.angle y z = π / 2,
{ rcases h0 with (rfl|rfl)|rfl|rfl,
{ simpa using h.symm },
{ simpa using h.symm },
{ simpa using h },
{ simpa using h } },
rcases h' with ⟨hwx, hyz⟩,
have hpi : π / 2 ≠ π,
{ intro hpi,
rw [div_eq_iff, eq_comm, ←sub_eq_zero, mul_two, add_sub_cancel] at hpi,
{ exact real.pi_pos.ne.symm hpi },
{ exact two_ne_zero } },
have h0wx : (w = 0 ∨ x = 0),
{ have h0' := o.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hswx,
simpa [hwx, real.pi_pos.ne.symm, hpi] using h0' },
have h0yz : (y = 0 ∨ z = 0),
{ have h0' := o.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hsyz,
simpa [hyz, real.pi_pos.ne.symm, hpi] using h0' },
rcases h0wx with h0wx|h0wx; rcases h0yz with h0yz|h0yz;
simp [h0wx, h0yz] },
{ push_neg at h0,
rw real.angle.eq_iff_abs_to_real_eq_of_sign_eq hs,
rwa [o.angle_eq_abs_oangle_to_real h0.1.1 h0.1.2,
o.angle_eq_abs_oangle_to_real h0.2.1 h0.2.2] at h }
end
/-- If the signs of two oriented angles between nonzero vectors are equal, the oriented angles are
equal if and only if the unoriented angles are equal. -/
lemma angle_eq_iff_oangle_eq_of_sign_eq {w x y z : V} (hw : w ≠ 0) (hx : x ≠ 0) (hy : y ≠ 0)
(hz : z ≠ 0) (hs : (o.oangle w x).sign = (o.oangle y z).sign) :
inner_product_geometry.angle w x = inner_product_geometry.angle y z ↔
o.oangle w x = o.oangle y z :=
begin
refine ⟨λ h, o.oangle_eq_of_angle_eq_of_sign_eq h hs, λ h, _⟩,
rw [o.angle_eq_abs_oangle_to_real hw hx, o.angle_eq_abs_oangle_to_real hy hz, h]
end
/-- The oriented angle between two vectors equals the unoriented angle if the sign is positive. -/
lemma oangle_eq_angle_of_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) :
o.oangle x y = inner_product_geometry.angle x y :=
begin
by_cases hx : x = 0, { exfalso, simpa [hx] using h },
by_cases hy : y = 0, { exfalso, simpa [hy] using h },
refine (o.oangle_eq_angle_or_eq_neg_angle hx hy).resolve_right _,
intro hxy,
rw [hxy, real.angle.sign_neg, neg_eq_iff_eq_neg, ←sign_type.neg_iff, ←not_le] at h,
exact h (real.angle.sign_coe_nonneg_of_nonneg_of_le_pi (inner_product_geometry.angle_nonneg _ _)
(inner_product_geometry.angle_le_pi _ _))
end
/-- The oriented angle between two vectors equals minus the unoriented angle if the sign is
negative. -/
lemma oangle_eq_neg_angle_of_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) :
o.oangle x y = -inner_product_geometry.angle x y :=
begin
by_cases hx : x = 0, { exfalso, simpa [hx] using h },
by_cases hy : y = 0, { exfalso, simpa [hy] using h },
refine (o.oangle_eq_angle_or_eq_neg_angle hx hy).resolve_left _,
intro hxy,
rw [hxy, ←sign_type.neg_iff, ←not_le] at h,
exact h (real.angle.sign_coe_nonneg_of_nonneg_of_le_pi (inner_product_geometry.angle_nonneg _ _)
(inner_product_geometry.angle_le_pi _ _))
end
/-- The oriented angle between two nonzero vectors is zero if and only if the unoriented angle
is zero. -/
lemma oangle_eq_zero_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) :
o.oangle x y = 0 ↔ inner_product_geometry.angle x y = 0 :=
begin
refine ⟨λ h, _, λ h, _⟩,
{ simpa [o.angle_eq_abs_oangle_to_real hx hy] },
{ have ha := o.oangle_eq_angle_or_eq_neg_angle hx hy,
rw h at ha,
simpa using ha }
end
/-- The oriented angle between two vectors is `π` if and only if the unoriented angle is `π`. -/
lemma oangle_eq_pi_iff_angle_eq_pi {x y : V} :
o.oangle x y = π ↔ inner_product_geometry.angle x y = π :=
begin
by_cases hx : x = 0, { simp [hx, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀,
not_or_distrib, real.pi_ne_zero], norm_num },
by_cases hy : y = 0, { simp [hy, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀,
not_or_distrib, real.pi_ne_zero], norm_num },
refine ⟨λ h, _, λ h, _⟩,
{ rw [o.angle_eq_abs_oangle_to_real hx hy, h],
simp [real.pi_pos.le] },
{ have ha := o.oangle_eq_angle_or_eq_neg_angle hx hy,
rw h at ha,
simpa using ha }
end
/-- One of two vectors is zero or the oriented angle between them is plus or minus `π / 2` if
and only if the inner product of those vectors is zero. -/
lemma eq_zero_or_oangle_eq_iff_inner_eq_zero {x y : V} :
(x = 0 ∨ y = 0 ∨ o.oangle x y = (π / 2 : ℝ) ∨ o.oangle x y = (-π / 2 : ℝ)) ↔ ⟪x, y⟫ = 0 :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
rw [inner_product_geometry.inner_eq_zero_iff_angle_eq_pi_div_two, or_iff_right hx,
or_iff_right hy],
refine ⟨λ h, _, λ h, _⟩,
{ rwa [o.angle_eq_abs_oangle_to_real hx hy, real.angle.abs_to_real_eq_pi_div_two_iff] },
{ convert o.oangle_eq_angle_or_eq_neg_angle hx hy; rw [h],
exact neg_div _ _ }
end
/-- If the oriented angle between two vectors is `π / 2`, the inner product of those vectors
is zero. -/
lemma inner_eq_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) :
⟪x, y⟫ = 0 :=
o.eq_zero_or_oangle_eq_iff_inner_eq_zero.1 $ or.inr $ or.inr $ or.inl h
/-- If the oriented angle between two vectors is `π / 2`, the inner product of those vectors
(reversed) is zero. -/
lemma inner_rev_eq_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) :
⟪y, x⟫ = 0 :=
by rw [real_inner_comm, o.inner_eq_zero_of_oangle_eq_pi_div_two h]
/-- If the oriented angle between two vectors is `-π / 2`, the inner product of those vectors
is zero. -/
lemma inner_eq_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) :
⟪x, y⟫ = 0 :=
o.eq_zero_or_oangle_eq_iff_inner_eq_zero.1 $ or.inr $ or.inr $ or.inr h
/-- If the oriented angle between two vectors is `-π / 2`, the inner product of those vectors
(reversed) is zero. -/
lemma inner_rev_eq_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) :
⟪y, x⟫ = 0 :=
by rw [real_inner_comm, o.inner_eq_zero_of_oangle_eq_neg_pi_div_two h]
/-- Negating the first vector passed to `oangle` negates the sign of the angle. -/
@[simp] lemma oangle_sign_neg_left (x y : V) :
(o.oangle (-x) y).sign = -((o.oangle x y).sign) :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
rw [o.oangle_neg_left hx hy, real.angle.sign_add_pi]
end
/-- Negating the second vector passed to `oangle` negates the sign of the angle. -/
@[simp] lemma oangle_sign_neg_right (x y : V) :
(o.oangle x (-y)).sign = -((o.oangle x y).sign) :=
begin
by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
rw [o.oangle_neg_right hx hy, real.angle.sign_add_pi]
end
/-- Multiplying the first vector passed to `oangle` by a real multiplies the sign of the angle by
the sign of the real. -/
@[simp] lemma oangle_sign_smul_left (x y : V) (r : ℝ) :
(o.oangle (r • x) y).sign = sign r * (o.oangle x y).sign :=
begin
rcases lt_trichotomy r 0 with h|h|h;
simp [h]
end
/-- Multiplying the second vector passed to `oangle` by a real multiplies the sign of the angle by
the sign of the real. -/
@[simp] lemma oangle_sign_smul_right (x y : V) (r : ℝ) :
(o.oangle x (r • y)).sign = sign r * (o.oangle x y).sign :=
begin
rcases lt_trichotomy r 0 with h|h|h;
simp [h]
end
/-- Auxiliary lemma for the proof of `oangle_sign_smul_add_right`; not intended to be used
outside of that proof. -/
lemma oangle_smul_add_right_eq_zero_or_eq_pi_iff {x y : V} (r : ℝ) :
(o.oangle x (r • x + y) = 0 ∨ o.oangle x (r • x + y) = π) ↔
(o.oangle x y = 0 ∨ o.oangle x y = π) :=
begin
simp_rw [oangle_eq_zero_or_eq_pi_iff_not_linear_independent,
fintype.not_linear_independent_iff, fin.sum_univ_two, fin.exists_fin_two],
refine ⟨λ h, _, λ h, _⟩,
{ rcases h with ⟨m, h, hm⟩,
change m 0 • x + m 1 • (r • x + y) = 0 at h,
refine ⟨![m 0 + m 1 * r, m 1], _⟩,
change (m 0 + m 1 * r) • x + m 1 • y = 0 ∧ (m 0 + m 1 * r ≠ 0 ∨ m 1 ≠ 0),
rw [smul_add, smul_smul, ←add_assoc, ←add_smul] at h,
refine ⟨h, not_and_distrib.1 (λ h0, _)⟩,
obtain ⟨h0, h1⟩ := h0,
rw h1 at h0 hm,
rw [zero_mul, add_zero] at h0,
simpa [h0] using hm },
{ rcases h with ⟨m, h, hm⟩,
change m 0 • x + m 1 • y = 0 at h,
refine ⟨![m 0 - m 1 * r, m 1], _⟩,
change (m 0 - m 1 * r) • x + m 1 • (r • x + y) = 0 ∧ (m 0 - m 1 * r ≠ 0 ∨ m 1 ≠ 0),
rw [sub_smul, smul_add, smul_smul, ←add_assoc, sub_add_cancel],
refine ⟨h, not_and_distrib.1 (λ h0, _)⟩,
obtain ⟨h0, h1⟩ := h0,
rw h1 at h0 hm,
rw [zero_mul, sub_zero] at h0,
simpa [h0] using hm }
end
/-- Adding a multiple of the first vector passed to `oangle` to the second vector does not change
the sign of the angle. -/
@[simp] lemma oangle_sign_smul_add_right (x y : V) (r : ℝ) :
(o.oangle x (r • x + y)).sign = (o.oangle x y).sign :=
begin
by_cases h : o.oangle x y = 0 ∨ o.oangle x y = π,
{ rwa [real.angle.sign_eq_zero_iff.2 h, real.angle.sign_eq_zero_iff,
oangle_smul_add_right_eq_zero_or_eq_pi_iff] },
have h' : ∀ r' : ℝ, o.oangle x (r' • x + y) ≠ 0 ∧ o.oangle x (r' • x + y) ≠ π,
{ intro r',
rwa [←o.oangle_smul_add_right_eq_zero_or_eq_pi_iff r', not_or_distrib] at h },
let s : set (V × V) := (λ r' : ℝ, (x, r' • x + y)) '' set.univ,
have hc : is_connected s := is_connected_univ.image _ ((continuous_const.prod_mk
((continuous_id.smul continuous_const).add continuous_const)).continuous_on),
have hf : continuous_on (λ z : V × V, o.oangle z.1 z.2) s,
{ refine continuous_at.continuous_on (λ z hz, o.continuous_at_oangle _ _),
all_goals { simp_rw [s, set.mem_image] at hz,
obtain ⟨r', -, rfl⟩ := hz,
simp only [prod.fst, prod.snd],
intro hz },
{ simpa [hz] using (h' 0).1 },
{ simpa [hz] using (h' r').1 } },
have hs : ∀ z : V × V, z ∈ s → o.oangle z.1 z.2 ≠ 0 ∧ o.oangle z.1 z.2 ≠ π,
{ intros z hz,
simp_rw [s, set.mem_image] at hz,
obtain ⟨r', -, rfl⟩ := hz,
exact h' r' },
have hx : (x, y) ∈ s,
{ convert set.mem_image_of_mem (λ r' : ℝ, (x, r' • x + y)) (set.mem_univ 0),
simp },
have hy : (x, r • x + y) ∈ s := set.mem_image_of_mem _ (set.mem_univ _),
convert real.angle.sign_eq_of_continuous_on hc hf hs hx hy
end
/-- Adding a multiple of the second vector passed to `oangle` to the first vector does not change
the sign of the angle. -/
@[simp] lemma oangle_sign_add_smul_left (x y : V) (r : ℝ) :
(o.oangle (x + r • y) y).sign = (o.oangle x y).sign :=
by simp_rw [o.oangle_rev y, real.angle.sign_neg, add_comm x, oangle_sign_smul_add_right]
/-- Subtracting a multiple of the first vector passed to `oangle` from the second vector does
not change the sign of the angle. -/
@[simp] lemma oangle_sign_sub_smul_right (x y : V) (r : ℝ) :
(o.oangle x (y - r • x)).sign = (o.oangle x y).sign :=
by rw [sub_eq_add_neg, ←neg_smul, add_comm, oangle_sign_smul_add_right]
/-- Subtracting a multiple of the second vector passed to `oangle` from the first vector does
not change the sign of the angle. -/
@[simp] lemma oangle_sign_sub_smul_left (x y : V) (r : ℝ) :
(o.oangle (x - r • y) y).sign = (o.oangle x y).sign :=
by rw [sub_eq_add_neg, ←neg_smul, oangle_sign_add_smul_left]
/-- Adding the first vector passed to `oangle` to the second vector does not change the sign of
the angle. -/
@[simp] lemma oangle_sign_add_right (x y : V) : (o.oangle x (x + y)).sign = (o.oangle x y).sign :=
by rw [←o.oangle_sign_smul_add_right x y 1, one_smul]
/-- Adding the second vector passed to `oangle` to the first vector does not change the sign of
the angle. -/
@[simp] lemma oangle_sign_add_left (x y : V) : (o.oangle (x + y) y).sign = (o.oangle x y).sign :=
by rw [←o.oangle_sign_add_smul_left x y 1, one_smul]
/-- Subtracting the first vector passed to `oangle` from the second vector does not change the
sign of the angle. -/
@[simp] lemma oangle_sign_sub_right (x y : V) :
(o.oangle x (y - x)).sign = (o.oangle x y).sign :=
by rw [←o.oangle_sign_sub_smul_right x y 1, one_smul]
/-- Subtracting the second vector passed to `oangle` from the first vector does not change the
sign of the angle. -/
@[simp] lemma oangle_sign_sub_left (x y : V) :
(o.oangle (x - y) y).sign = (o.oangle x y).sign :=
by rw [←o.oangle_sign_sub_smul_left x y 1, one_smul]
/-- Subtracting the second vector passed to `oangle` from a multiple of the first vector negates
the sign of the angle. -/
@[simp] lemma oangle_sign_smul_sub_right (x y : V) (r : ℝ) :
(o.oangle x (r • x - y)).sign = -(o.oangle x y).sign :=
by rw [←oangle_sign_neg_right, sub_eq_add_neg, oangle_sign_smul_add_right]
/-- Subtracting the first vector passed to `oangle` from a multiple of the second vector negates
the sign of the angle. -/
@[simp] lemma oangle_sign_smul_sub_left (x y : V) (r : ℝ) :
(o.oangle (r • y - x) y).sign = -(o.oangle x y).sign :=
by rw [←oangle_sign_neg_left, sub_eq_neg_add, oangle_sign_add_smul_left]
/-- Subtracting the second vector passed to `oangle` from the first vector negates the sign of
the angle. -/
lemma oangle_sign_sub_right_eq_neg (x y : V) :
(o.oangle x (x - y)).sign = -(o.oangle x y).sign :=
by rw [←o.oangle_sign_smul_sub_right x y 1, one_smul]
/-- Subtracting the first vector passed to `oangle` from the second vector negates the sign of
the angle. -/
lemma oangle_sign_sub_left_eq_neg (x y : V) :
(o.oangle (y - x) y).sign = -(o.oangle x y).sign :=
by rw [←o.oangle_sign_smul_sub_left x y 1, one_smul]
/-- Subtracting the first vector passed to `oangle` from the second vector then swapping the
vectors does not change the sign of the angle. -/
@[simp] lemma oangle_sign_sub_right_swap (x y : V) :
(o.oangle y (y - x)).sign = (o.oangle x y).sign :=
by rw [oangle_sign_sub_right_eq_neg, o.oangle_rev y x, real.angle.sign_neg]
/-- Subtracting the second vector passed to `oangle` from the first vector then swapping the
vectors does not change the sign of the angle. -/
@[simp] lemma oangle_sign_sub_left_swap (x y : V) :
(o.oangle (x - y) x).sign = (o.oangle x y).sign :=
by rw [oangle_sign_sub_left_eq_neg, o.oangle_rev y x, real.angle.sign_neg]
/-- The sign of the angle between a vector, and a linear combination of that vector with a second
vector, is the sign of the factor by which the second vector is multiplied in that combination
multiplied by the sign of the angle between the two vectors. -/
@[simp] lemma oangle_sign_smul_add_smul_right (x y : V) (r₁ r₂ : ℝ) :
(o.oangle x (r₁ • x + r₂ • y)).sign = sign r₂ * (o.oangle x y).sign :=
begin
rw ←o.oangle_sign_smul_add_right x (r₁ • x + r₂ • y) (-r₁),
simp
end
/-- The sign of the angle between a linear combination of two vectors and the second vector is
the sign of the factor by which the first vector is multiplied in that combination multiplied by
the sign of the angle between the two vectors. -/
@[simp] lemma oangle_sign_smul_add_smul_left (x y : V) (r₁ r₂ : ℝ) :
(o.oangle (r₁ • x + r₂ • y) y).sign = sign r₁ * (o.oangle x y).sign :=
by simp_rw [o.oangle_rev y, real.angle.sign_neg, add_comm (r₁ • x),
oangle_sign_smul_add_smul_right, mul_neg]
/-- The sign of the angle between two linear combinations of two vectors is the sign of the
determinant of the factors in those combinations multiplied by the sign of the angle between the
two vectors. -/
lemma oangle_sign_smul_add_smul_smul_add_smul (x y : V) (r₁ r₂ r₃ r₄ : ℝ) :
(o.oangle (r₁ • x + r₂ • y) (r₃ • x + r₄ • y)).sign =
sign (r₁ * r₄ - r₂ * r₃) * (o.oangle x y).sign :=
begin
by_cases hr₁ : r₁ = 0,
{ rw [hr₁, zero_smul, zero_mul, zero_add, zero_sub, left.sign_neg, oangle_sign_smul_left,
add_comm, oangle_sign_smul_add_smul_right, oangle_rev, real.angle.sign_neg, sign_mul,
mul_neg, mul_neg, neg_mul, mul_assoc] },
{ rw [←o.oangle_sign_smul_add_right (r₁ • x + r₂ • y) (r₃ • x + r₄ • y) (-r₃ / r₁),
smul_add, smul_smul, smul_smul, div_mul_cancel _ hr₁, neg_smul, ←add_assoc,
add_comm (-(r₃ • x)), ←sub_eq_add_neg, sub_add_cancel, ←add_smul,
oangle_sign_smul_right, oangle_sign_smul_add_smul_left, ←mul_assoc, ←sign_mul,
add_mul, mul_assoc, mul_comm r₂ r₁, ←mul_assoc, div_mul_cancel _ hr₁, add_comm,
neg_mul, ←sub_eq_add_neg, mul_comm r₄, mul_comm r₃] }
end
/-- A base angle of an isosceles triangle is acute, oriented vector angle form. -/
lemma abs_oangle_sub_left_to_real_lt_pi_div_two {x y : V} (h : ‖x‖ = ‖y‖) :
|(o.oangle (y - x) y).to_real| < π / 2 :=
begin
by_cases hn : x = y, { simp [hn, div_pos, real.pi_pos] },
have hs : ((2 : ℤ) • (o.oangle (y - x) y)).sign = (o.oangle (y - x) y).sign,
{ conv_rhs { rw oangle_sign_sub_left_swap },
rw [o.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hn h, real.angle.sign_pi_sub] },
rw real.angle.sign_two_zsmul_eq_sign_iff at hs,
rcases hs with hs | hs,
{ rw [oangle_eq_pi_iff_oangle_rev_eq_pi, oangle_eq_pi_iff_same_ray_neg, neg_sub] at hs,
rcases hs with ⟨hy, -, hr⟩,
rw ←exists_nonneg_left_iff_same_ray hy at hr,
rcases hr with ⟨r, hr0, hr⟩,
rw [eq_sub_iff_add_eq] at hr,
nth_rewrite 1 ←one_smul ℝ y at hr,
rw ←add_smul at hr,
rw [←hr, norm_smul, real.norm_eq_abs, abs_of_pos (left.add_pos_of_nonneg_of_pos hr0 one_pos),
mul_left_eq_self₀, or_iff_left (norm_ne_zero_iff.2 hy), add_left_eq_self] at h,
rw [h, zero_add, one_smul] at hr,
exact false.elim (hn hr.symm) },
{ exact hs }
end
/-- A base angle of an isosceles triangle is acute, oriented vector angle form. -/
lemma abs_oangle_sub_right_to_real_lt_pi_div_two {x y : V} (h : ‖x‖ = ‖y‖) :
|(o.oangle x (x - y)).to_real| < π / 2 :=
(o.oangle_sub_eq_oangle_sub_rev_of_norm_eq h).symm ▸ o.abs_oangle_sub_left_to_real_lt_pi_div_two h
end orientation
|
2bdced16589062be9d77945d6bdda10e2f1fe6a0 | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/metric_space/gromov_hausdorff.lean | 363b944d0575fe57323282a30e2046f042d44de7 | [
"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 | 55,768 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sébastien Gouëzel
-/
import topology.metric_space.closeds
import set_theory.cardinal
import topology.metric_space.gromov_hausdorff_realized
import topology.metric_space.completion
/-!
# Gromov-Hausdorff distance
This file defines the Gromov-Hausdorff distance on the space of nonempty compact metric spaces
up to isometry.
We introduce the space of all nonempty compact metric spaces, up to isometry,
called `GH_space`, and endow it with a metric space structure. The distance,
known as the Gromov-Hausdorff distance, is defined as follows: given two
nonempty compact spaces `X` and `Y`, their distance is the minimum Hausdorff distance
between all possible isometric embeddings of `X` and `Y` in all metric spaces.
To define properly the Gromov-Hausdorff space, we consider the non-empty
compact subsets of `ℓ^∞(ℝ)` up to isometry, which is a well-defined type,
and define the distance as the infimum of the Hausdorff distance over all
embeddings in `ℓ^∞(ℝ)`. We prove that this coincides with the previous description,
as all separable metric spaces embed isometrically into `ℓ^∞(ℝ)`, through an
embedding called the Kuratowski embedding.
To prove that we have a distance, we should show that if spaces can be coupled
to be arbitrarily close, then they are isometric. More generally, the Gromov-Hausdorff
distance is realized, i.e., there is a coupling for which the Hausdorff distance
is exactly the Gromov-Hausdorff distance. This follows from a compactness
argument, essentially following from Arzela-Ascoli.
## Main results
We prove the most important properties of the Gromov-Hausdorff space: it is a polish space,
i.e., it is complete and second countable. We also prove the Gromov compactness criterion.
-/
noncomputable theory
open_locale classical topological_space
universes u v w
open classical set function topological_space filter metric quotient
open bounded_continuous_function nat Kuratowski_embedding
open sum (inl inr)
local attribute [instance] metric_space_sum
namespace Gromov_Hausdorff
section GH_space
/- In this section, we define the Gromov-Hausdorff space, denoted `GH_space` as the quotient
of nonempty compact subsets of `ℓ^∞(ℝ)` by identifying isometric sets.
Using the Kuratwoski embedding, we get a canonical map `to_GH_space` mapping any nonempty
compact type to `GH_space`. -/
/-- Equivalence relation identifying two nonempty compact sets which are isometric -/
private definition isometry_rel : nonempty_compacts ℓ_infty_ℝ → nonempty_compacts ℓ_infty_ℝ → Prop :=
λx y, nonempty (x.val ≃ᵢ y.val)
/-- This is indeed an equivalence relation -/
private lemma is_equivalence_isometry_rel : equivalence isometry_rel :=
⟨λx, ⟨isometric.refl _⟩, λx y ⟨e⟩, ⟨e.symm⟩, λ x y z ⟨e⟩ ⟨f⟩, ⟨e.trans f⟩⟩
/-- setoid instance identifying two isometric nonempty compact subspaces of ℓ^∞(ℝ) -/
instance isometry_rel.setoid : setoid (nonempty_compacts ℓ_infty_ℝ) :=
setoid.mk isometry_rel is_equivalence_isometry_rel
/-- The Gromov-Hausdorff space -/
definition GH_space : Type := quotient (isometry_rel.setoid)
/-- Map any nonempty compact type to `GH_space` -/
definition to_GH_space (α : Type u) [metric_space α] [compact_space α] [nonempty α] : GH_space :=
⟦nonempty_compacts.Kuratowski_embedding α⟧
instance : inhabited GH_space := ⟨quot.mk _ ⟨{0}, by simp⟩⟩
/-- A metric space representative of any abstract point in `GH_space` -/
definition GH_space.rep (p : GH_space) : Type := (quot.out p).val
lemma eq_to_GH_space_iff {α : Type u} [metric_space α] [compact_space α] [nonempty α] {p : nonempty_compacts ℓ_infty_ℝ} :
⟦p⟧ = to_GH_space α ↔ ∃Ψ : α → ℓ_infty_ℝ, isometry Ψ ∧ range Ψ = p.val :=
begin
simp only [to_GH_space, quotient.eq],
split,
{ assume h,
rcases setoid.symm h with ⟨e⟩,
have f := (Kuratowski_embedding.isometry α).isometric_on_range.trans e,
use λx, f x,
split,
{ apply isometry_subtype_val.comp f.isometry },
{ rw [range_comp, f.range_coe, set.image_univ, set.range_coe_subtype] } },
{ rintros ⟨Ψ, ⟨isomΨ, rangeΨ⟩⟩,
have f := ((Kuratowski_embedding.isometry α).isometric_on_range.symm.trans
isomΨ.isometric_on_range).symm,
have E : (range Ψ ≃ᵢ (nonempty_compacts.Kuratowski_embedding α).val) = (p.val ≃ᵢ range (Kuratowski_embedding α)),
by { dunfold nonempty_compacts.Kuratowski_embedding, rw [rangeΨ]; refl },
have g := cast E f,
exact ⟨g⟩ }
end
lemma eq_to_GH_space {p : nonempty_compacts ℓ_infty_ℝ} : ⟦p⟧ = to_GH_space p.val :=
begin
refine eq_to_GH_space_iff.2 ⟨((λx, x) : p.val → ℓ_infty_ℝ), _, subtype.val_range⟩,
apply isometry_subtype_val
end
section
local attribute [reducible] GH_space.rep
instance rep_GH_space_metric_space {p : GH_space} : metric_space (p.rep) :=
by apply_instance
instance rep_GH_space_compact_space {p : GH_space} : compact_space (p.rep) :=
by apply_instance
instance rep_GH_space_nonempty {p : GH_space} : nonempty (p.rep) :=
by apply_instance
end
lemma GH_space.to_GH_space_rep (p : GH_space) : to_GH_space (p.rep) = p :=
begin
change to_GH_space (quot.out p).val = p,
rw ← eq_to_GH_space,
exact quot.out_eq p
end
/-- Two nonempty compact spaces have the same image in `GH_space` if and only if they are isometric -/
lemma to_GH_space_eq_to_GH_space_iff_isometric {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type u} [metric_space β] [compact_space β] [nonempty β] :
to_GH_space α = to_GH_space β ↔ nonempty (α ≃ᵢ β) :=
⟨begin
simp only [to_GH_space, quotient.eq],
assume h,
rcases h with e,
have I : ((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val)
= ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have e' := cast I e,
have f := (Kuratowski_embedding.isometry α).isometric_on_range,
have g := (Kuratowski_embedding.isometry β).isometric_on_range.symm,
have h := (f.trans e').trans g,
exact ⟨h⟩
end,
begin
rintros ⟨e⟩,
simp only [to_GH_space, quotient.eq],
have f := (Kuratowski_embedding.isometry α).isometric_on_range.symm,
have g := (Kuratowski_embedding.isometry β).isometric_on_range,
have h := (f.trans e).trans g,
have I : ((range (Kuratowski_embedding α)) ≃ᵢ (range (Kuratowski_embedding β))) =
((nonempty_compacts.Kuratowski_embedding α).val ≃ᵢ (nonempty_compacts.Kuratowski_embedding β).val),
by { dunfold nonempty_compacts.Kuratowski_embedding, refl },
have h' := cast I h,
exact ⟨h'⟩
end⟩
/-- Distance on `GH_space`: the distance between two nonempty compact spaces is the infimum
Hausdorff distance between isometric copies of the two spaces in a metric space. For the definition,
we only consider embeddings in `ℓ^∞(ℝ)`, but we will prove below that it works for all spaces. -/
instance : has_dist (GH_space) :=
{ dist := λx y, Inf ((λp : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ, Hausdorff_dist p.1.val p.2.val) ''
(set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})) }
/-- The Gromov-Hausdorff distance between two nonempty compact metric spaces, equal by definition to
the distance of the equivalence classes of these spaces in the Gromov-Hausdorff space. -/
def GH_dist (α : Type u) (β : Type v) [metric_space α] [nonempty α] [compact_space α]
[metric_space β] [nonempty β] [compact_space β] : ℝ := dist (to_GH_space α) (to_GH_space β)
lemma dist_GH_dist (p q : GH_space) : dist p q = GH_dist (p.rep) (q.rep) :=
by rw [GH_dist, p.to_GH_space_rep, q.to_GH_space_rep]
/-- The Gromov-Hausdorff distance between two spaces is bounded by the Hausdorff distance
of isometric copies of the spaces, in any metric space. -/
theorem GH_dist_le_Hausdorff_dist {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
{γ : Type w} [metric_space γ] {Φ : α → γ} {Ψ : β → γ} (ha : isometry Φ) (hb : isometry Ψ) :
GH_dist α β ≤ Hausdorff_dist (range Φ) (range Ψ) :=
begin
/- For the proof, we want to embed `γ` in `ℓ^∞(ℝ)`, to say that the Hausdorff distance is realized
in `ℓ^∞(ℝ)` and therefore bounded below by the Gromov-Hausdorff-distance. However, `γ` is not
separable in general. We restrict to the union of the images of `α` and `β` in `γ`, which is
separable and therefore embeddable in `ℓ^∞(ℝ)`. -/
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
letI : inhabited α := ⟨xα⟩,
letI : inhabited β := classical.inhabited_of_nonempty (by assumption),
let s : set γ := (range Φ) ∪ (range Ψ),
let Φ' : α → subtype s := λy, ⟨Φ y, mem_union_left _ (mem_range_self _)⟩,
let Ψ' : β → subtype s := λy, ⟨Ψ y, mem_union_right _ (mem_range_self _)⟩,
have IΦ' : isometry Φ' := λx y, ha x y,
have IΨ' : isometry Ψ' := λx y, hb x y,
have : compact s, from (compact_range ha.continuous).union (compact_range hb.continuous),
letI : metric_space (subtype s) := by apply_instance,
haveI : compact_space (subtype s) := ⟨compact_iff_compact_univ.1 ‹compact s›⟩,
haveI : nonempty (subtype s) := ⟨Φ' xα⟩,
have ΦΦ' : Φ = subtype.val ∘ Φ', by { funext, refl },
have ΨΨ' : Ψ = subtype.val ∘ Ψ', by { funext, refl },
have : Hausdorff_dist (range Φ) (range Ψ) = Hausdorff_dist (range Φ') (range Ψ'),
{ rw [ΦΦ', ΨΨ', range_comp, range_comp],
exact Hausdorff_dist_image (isometry_subtype_val) },
rw this,
-- Embed `s` in `ℓ^∞(ℝ)` through its Kuratowski embedding
let F := Kuratowski_embedding (subtype s),
have : Hausdorff_dist (F '' (range Φ')) (F '' (range Ψ')) = Hausdorff_dist (range Φ') (range Ψ') :=
Hausdorff_dist_image (Kuratowski_embedding.isometry _),
rw ← this,
-- Let `A` and `B` be the images of `α` and `β` under this embedding. They are in `ℓ^∞(ℝ)`, and
-- their Hausdorff distance is the same as in the original space.
let A : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Φ'), ⟨(range_nonempty _).image _,
(compact_range IΦ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
let B : nonempty_compacts ℓ_infty_ℝ := ⟨F '' (range Ψ'), ⟨(range_nonempty _).image _,
(compact_range IΨ'.continuous).image (Kuratowski_embedding.isometry _).continuous⟩⟩,
have Aα : ⟦A⟧ = to_GH_space α,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Φ' x), ⟨(Kuratowski_embedding.isometry _).comp IΦ', by rw range_comp⟩⟩ },
have Bβ : ⟦B⟧ = to_GH_space β,
{ rw eq_to_GH_space_iff,
exact ⟨λx, F (Ψ' x), ⟨(Kuratowski_embedding.isometry _).comp IΨ', by rw range_comp⟩⟩ },
refine cInf_le ⟨0,
begin simp [lower_bounds], assume t _ _ _ _ ht, rw ← ht, exact Hausdorff_dist_nonneg end⟩ _,
apply (mem_image _ _ _).2,
existsi (⟨A, B⟩ : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
simp [Aα, Bβ]
end
/-- The optimal coupling constructed above realizes exactly the Gromov-Hausdorff distance,
essentially by design. -/
lemma Hausdorff_dist_optimal {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β] :
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) = GH_dist α β :=
begin
inhabit α, inhabit β,
/- we only need to check the inequality `≤`, as the other one follows from the previous lemma.
As the Gromov-Hausdorff distance is an infimum, we need to check that the Hausdorff distance
in the optimal coupling is smaller than the Hausdorff distance of any coupling.
First, we check this for couplings which already have small Hausdorff distance: in this
case, the induced "distance" on `α ⊕ β` belongs to the candidates family introduced in the
definition of the optimal coupling, and the conclusion follows from the optimality
of the optimal coupling within this family.
-/
have A : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β) →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq bound,
rcases eq_to_GH_space_iff.1 hp with ⟨Φ, ⟨Φisom, Φrange⟩⟩,
rcases eq_to_GH_space_iff.1 hq with ⟨Ψ, ⟨Ψisom, Ψrange⟩⟩,
have I : diam (range Φ ∪ range Ψ) ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β),
{ rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
have : ∃y ∈ range Ψ, dist (Φ xα) y < diam (univ : set α) + 1 + diam (univ : set β),
{ rw Ψrange,
have : Φ xα ∈ p.val := Φrange ▸ mem_range_self _,
exact exists_dist_lt_of_Hausdorff_dist_lt this bound
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded) },
rcases this with ⟨y, hy, dy⟩,
rcases mem_range.1 hy with ⟨z, hzy⟩,
rw ← hzy at dy,
have DΦ : diam (range Φ) = diam (univ : set α) := Φisom.diam_range,
have DΨ : diam (range Ψ) = diam (univ : set β) := Ψisom.diam_range,
calc
diam (range Φ ∪ range Ψ) ≤ diam (range Φ) + dist (Φ xα) (Ψ z) + diam (range Ψ) :
diam_union (mem_range_self _) (mem_range_self _)
... ≤ diam (univ : set α) + (diam (univ : set α) + 1 + diam (univ : set β)) + diam (univ : set β) :
by { rw [DΦ, DΨ], apply add_le_add (add_le_add (le_refl _) (le_of_lt dy)) (le_refl _) }
... = 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : by ring },
let f : α ⊕ β → ℓ_infty_ℝ := λx, match x with | inl y := Φ y | inr z := Ψ z end,
let F : (α ⊕ β) × (α ⊕ β) → ℝ := λp, dist (f p.1) (f p.2),
-- check that the induced "distance" is a candidate
have Fgood : F ∈ candidates α β,
{ simp only [candidates, forall_const, and_true, add_comm, eq_self_iff_true, dist_eq_zero,
and_self, set.mem_set_of_eq],
repeat {split},
{ exact λx y, calc
F (inl x, inl y) = dist (Φ x) (Φ y) : rfl
... = dist x y : Φisom.dist_eq x y },
{ exact λx y, calc
F (inr x, inr y) = dist (Ψ x) (Ψ y) : rfl
... = dist x y : Ψisom.dist_eq x y },
{ exact λx y, dist_comm _ _ },
{ exact λx y z, dist_triangle _ _ _ },
{ exact λx y, calc
F (x, y) ≤ diam (range Φ ∪ range Ψ) :
begin
have A : ∀z : α ⊕ β, f z ∈ range Φ ∪ range Ψ,
{ assume z,
cases z,
{ apply mem_union_left, apply mem_range_self },
{ apply mem_union_right, apply mem_range_self } },
refine dist_le_diam_of_mem _ (A _) (A _),
rw [Φrange, Ψrange],
exact (p.2.2.union q.2.2).bounded,
end
... ≤ 2 * diam (univ : set α) + 1 + 2 * diam (univ : set β) : I } },
let Fb := candidates_b_of_candidates F Fgood,
have : Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD Fb :=
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_of_candidates_mem F Fgood),
refine le_trans this (le_of_forall_le_of_dense (λr hr, _)),
have I1 : ∀x : α, infi (λy:β, Fb (inl x, inr y)) ≤ r,
{ assume x,
have : f (inl x) ∈ p.val, by { rw [← Φrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Ψ, by rwa [← Ψrange] at zq,
rcases mem_range.1 this with ⟨y, hy⟩,
calc infi (λy:β, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux1 0) y
... = dist (Φ x) (Ψ y) : rfl
... = dist (f (inl x)) z : by rw hy
... ≤ r : le_of_lt hz },
have I2 : ∀y : β, infi (λx:α, Fb (inl x, inr y)) ≤ r,
{ assume y,
have : f (inr y) ∈ q.val, by { rw [← Ψrange], apply mem_range_self },
rcases exists_dist_lt_of_Hausdorff_dist_lt' this hr
(Hausdorff_edist_ne_top_of_nonempty_of_bounded p.2.1 q.2.1 p.2.2.bounded q.2.2.bounded)
with ⟨z, zq, hz⟩,
have : z ∈ range Φ, by rwa [← Φrange] at zq,
rcases mem_range.1 this with ⟨x, hx⟩,
calc infi (λx:α, Fb (inl x, inr y)) ≤ Fb (inl x, inr y) :
cinfi_le (by simpa using HD_below_aux2 0) x
... = dist (Φ x) (Ψ y) : rfl
... = dist z (f (inr y)) : by rw hx
... ≤ r : le_of_lt hz },
simp [HD, csupr_le I1, csupr_le I2] },
/- Get the same inequality for any coupling. If the coupling is quite good, the desired
inequality has been proved above. If it is bad, then the inequality is obvious. -/
have B : ∀p q : nonempty_compacts (ℓ_infty_ℝ), ⟦p⟧ = to_GH_space α → ⟦q⟧ = to_GH_space β →
Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ Hausdorff_dist (p.val) (q.val),
{ assume p q hp hq,
by_cases h : Hausdorff_dist (p.val) (q.val) < diam (univ : set α) + 1 + diam (univ : set β),
{ exact A p q hp hq h },
{ calc Hausdorff_dist (range (optimal_GH_injl α β)) (range (optimal_GH_injr α β)) ≤ HD (candidates_b_dist α β) :
Hausdorff_dist_optimal_le_HD _ _ (candidates_b_dist_mem_candidates_b)
... ≤ diam (univ : set α) + 1 + diam (univ : set β) : HD_candidates_b_dist_le
... ≤ Hausdorff_dist (p.val) (q.val) : not_lt.1 h } },
refine le_antisymm _ _,
{ apply le_cInf,
{ refine (set.nonempty.prod _ _).image _; exact ⟨_, rfl⟩ },
{ rintro b ⟨⟨p, q⟩, ⟨hp, hq⟩, rfl⟩,
exact B p q hp hq } },
{ exact GH_dist_le_Hausdorff_dist (isometry_optimal_GH_injl α β) (isometry_optimal_GH_injr α β) }
end
/-- The Gromov-Hausdorff distance can also be realized by a coupling in `ℓ^∞(ℝ)`, by embedding
the optimal coupling through its Kuratowski embedding. -/
theorem GH_dist_eq_Hausdorff_dist (α : Type u) [metric_space α] [compact_space α] [nonempty α]
(β : Type v) [metric_space β] [compact_space β] [nonempty β] :
∃Φ : α → ℓ_infty_ℝ, ∃Ψ : β → ℓ_infty_ℝ, isometry Φ ∧ isometry Ψ ∧
GH_dist α β = Hausdorff_dist (range Φ) (range Ψ) :=
begin
let F := Kuratowski_embedding (optimal_GH_coupling α β),
let Φ := F ∘ optimal_GH_injl α β,
let Ψ := F ∘ optimal_GH_injr α β,
refine ⟨Φ, Ψ, _, _, _⟩,
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injl α β) },
{ exact (Kuratowski_embedding.isometry _).comp (isometry_optimal_GH_injr α β) },
{ rw [← image_univ, ← image_univ, image_comp F, image_univ, image_comp F (optimal_GH_injr α β),
image_univ, ← Hausdorff_dist_optimal],
exact (Hausdorff_dist_image (Kuratowski_embedding.isometry _)).symm },
end
-- without the next two lines, `{ exact closed_of_compact (range Φ) hΦ }` in the next
-- proof is very slow, as the `t2_space` instance is very hard to find
local attribute [instance, priority 10] order_topology.t2_space
local attribute [instance, priority 10] order_closed_topology.to_t2_space
/-- The Gromov-Hausdorff distance defines a genuine distance on the Gromov-Hausdorff space. -/
instance GH_space_metric_space : metric_space GH_space :=
{ dist_self := λx, begin
rcases exists_rep x with ⟨y, hy⟩,
refine le_antisymm _ _,
{ apply cInf_le,
{ exact ⟨0, by { rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } ⟩},
{ simp, existsi [y, y], simpa } },
{ apply le_cInf,
{ exact (nonempty.prod ⟨y, hy⟩ ⟨y, hy⟩).image _ },
{ rintro b ⟨⟨u, v⟩, ⟨hu, hv⟩, rfl⟩, exact Hausdorff_dist_nonneg } },
end,
dist_comm := λx y, begin
have A : (λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y})
= ((λ (p : nonempty_compacts ℓ_infty_ℝ × nonempty_compacts ℓ_infty_ℝ),
Hausdorff_dist ((p.fst).val) ((p.snd).val)) ∘ prod.swap) '' (set.prod {a | ⟦a⟧ = x} {b | ⟦b⟧ = y}) :=
by { congr, funext, simp, rw Hausdorff_dist_comm },
simp only [dist, A, image_comp, prod.swap, image_swap_prod],
end,
eq_of_dist_eq_zero := λx y hxy, begin
/- To show that two spaces at zero distance are isometric, we argue that the distance
is realized by some coupling. In this coupling, the two spaces are at zero Hausdorff distance,
i.e., they coincide. Therefore, the original spaces are isometric. -/
rcases GH_dist_eq_Hausdorff_dist x.rep y.rep with ⟨Φ, Ψ, Φisom, Ψisom, DΦΨ⟩,
rw [← dist_GH_dist, hxy] at DΦΨ,
have : range Φ = range Ψ,
{ have hΦ : compact (range Φ) := compact_range Φisom.continuous,
have hΨ : compact (range Ψ) := compact_range Ψisom.continuous,
apply (Hausdorff_dist_zero_iff_eq_of_closed _ _ _).1 (DΦΨ.symm),
{ exact closed_of_compact (range Φ) hΦ },
{ exact closed_of_compact (range Ψ) hΨ },
{ exact Hausdorff_edist_ne_top_of_nonempty_of_bounded (range_nonempty _)
(range_nonempty _) hΦ.bounded hΨ.bounded } },
have T : ((range Ψ) ≃ᵢ y.rep) = ((range Φ) ≃ᵢ y.rep), by rw this,
have eΨ := cast T Ψisom.isometric_on_range.symm,
have e := Φisom.isometric_on_range.trans eΨ,
rw [← x.to_GH_space_rep, ← y.to_GH_space_rep, to_GH_space_eq_to_GH_space_iff_isometric],
exact ⟨e⟩
end,
dist_triangle := λx y z, begin
/- To show the triangular inequality between `X`, `Y` and `Z`, realize an optimal coupling
between `X` and `Y` in a space `γ1`, and an optimal coupling between `Y`and `Z` in a space `γ2`.
Then, glue these metric spaces along `Y`. We get a new space `γ` in which `X` and `Y` are
optimally coupled, as well as `Y` and `Z`. Apply the triangle inequality for the Hausdorff
distance in `γ` to conclude. -/
let X := x.rep,
let Y := y.rep,
let Z := z.rep,
let γ1 := optimal_GH_coupling X Y,
let γ2 := optimal_GH_coupling Y Z,
let Φ : Y → γ1 := optimal_GH_injr X Y,
have hΦ : isometry Φ := isometry_optimal_GH_injr X Y,
let Ψ : Y → γ2 := optimal_GH_injl Y Z,
have hΨ : isometry Ψ := isometry_optimal_GH_injl Y Z,
let γ := glue_space hΦ hΨ,
letI : metric_space γ := metric.metric_space_glue_space hΦ hΨ,
have Comm : (to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y) = (to_glue_r hΦ hΨ) ∘ (optimal_GH_injl Y Z) :=
to_glue_commute hΦ hΨ,
calc dist x z = dist (to_GH_space X) (to_GH_space Z) :
by rw [x.to_GH_space_rep, z.to_GH_space_rep]
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
GH_dist_le_Hausdorff_dist
((to_glue_l_isometry hΦ hΨ).comp (isometry_optimal_GH_injl X Y))
((to_glue_r_isometry hΦ hΨ).comp (isometry_optimal_GH_injr Y Z))
... ≤ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injl X Y)))
(range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
+ Hausdorff_dist (range ((to_glue_l hΦ hΨ) ∘ (optimal_GH_injr X Y)))
(range ((to_glue_r hΦ hΨ) ∘ (optimal_GH_injr Y Z))) :
begin
refine Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (range_nonempty _) _ _),
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injl X Y)))).bounded },
{ exact (compact_range (isometry.continuous ((to_glue_l_isometry hΦ hΨ).comp
(isometry_optimal_GH_injr X Y)))).bounded }
end
... = Hausdorff_dist ((to_glue_l hΦ hΨ) '' (range (optimal_GH_injl X Y)))
((to_glue_l hΦ hΨ) '' (range (optimal_GH_injr X Y)))
+ Hausdorff_dist ((to_glue_r hΦ hΨ) '' (range (optimal_GH_injl Y Z)))
((to_glue_r hΦ hΨ) '' (range (optimal_GH_injr Y Z))) :
by simp only [eq.symm range_comp, Comm, eq_self_iff_true, add_right_inj]
... = Hausdorff_dist (range (optimal_GH_injl X Y))
(range (optimal_GH_injr X Y))
+ Hausdorff_dist (range (optimal_GH_injl Y Z))
(range (optimal_GH_injr Y Z)) :
by rw [Hausdorff_dist_image (to_glue_l_isometry hΦ hΨ),
Hausdorff_dist_image (to_glue_r_isometry hΦ hΨ)]
... = dist (to_GH_space X) (to_GH_space Y) + dist (to_GH_space Y) (to_GH_space Z) :
by rw [Hausdorff_dist_optimal, Hausdorff_dist_optimal, GH_dist, GH_dist]
... = dist x y + dist y z:
by rw [x.to_GH_space_rep, y.to_GH_space_rep, z.to_GH_space_rep]
end }
end GH_space --section
end Gromov_Hausdorff
/-- In particular, nonempty compacts of a metric space map to `GH_space`. We register this
in the topological_space namespace to take advantage of the notation `p.to_GH_space`. -/
definition topological_space.nonempty_compacts.to_GH_space {α : Type u} [metric_space α]
(p : nonempty_compacts α) : Gromov_Hausdorff.GH_space := Gromov_Hausdorff.to_GH_space p.val
open topological_space
namespace Gromov_Hausdorff
section nonempty_compacts
variables {α : Type u} [metric_space α]
theorem GH_dist_le_nonempty_compacts_dist (p q : nonempty_compacts α) :
dist p.to_GH_space q.to_GH_space ≤ dist p q :=
begin
have ha : isometry (subtype.val : p.val → α) := isometry_subtype_val,
have hb : isometry (subtype.val : q.val → α) := isometry_subtype_val,
have A : dist p q = Hausdorff_dist p.val q.val := rfl,
have I : p.val = range (subtype.val : p.val → α), by simp,
have J : q.val = range (subtype.val : q.val → α), by simp,
rw [I, J] at A,
rw A,
exact GH_dist_le_Hausdorff_dist ha hb
end
lemma to_GH_space_lipschitz :
lipschitz_with 1 (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
lipschitz_with.mk_one GH_dist_le_nonempty_compacts_dist
lemma to_GH_space_continuous :
continuous (nonempty_compacts.to_GH_space : nonempty_compacts α → GH_space) :=
to_GH_space_lipschitz.continuous
end nonempty_compacts
section
/- In this section, we show that if two metric spaces are isometric up to `ε₂`, then their
Gromov-Hausdorff distance is bounded by `ε₂ / 2`. More generally, if there are subsets which are
`ε₁`-dense and `ε₃`-dense in two spaces, and isometric up to `ε₂`, then the Gromov-Hausdorff distance
between the spaces is bounded by `ε₁ + ε₂/2 + ε₃`. For this, we construct a suitable coupling between
the two spaces, by gluing them (approximately) along the two matching subsets. -/
variables {α : Type u} [metric_space α] [compact_space α] [nonempty α]
{β : Type v} [metric_space β] [compact_space β] [nonempty β]
-- we want to ignore these instances in the following theorem
local attribute [instance, priority 10] sum.topological_space sum.uniform_space
/-- If there are subsets which are `ε₁`-dense and `ε₃`-dense in two spaces, and
isometric up to `ε₂`, then the Gromov-Hausdorff distance between the spaces is bounded by
`ε₁ + ε₂/2 + ε₃`. -/
theorem GH_dist_le_of_approx_subsets {s : set α} (Φ : s → β) {ε₁ ε₂ ε₃ : ℝ}
(hs : ∀x : α, ∃y ∈ s, dist x y ≤ ε₁) (hs' : ∀x : β, ∃y : s, dist x (Φ y) ≤ ε₃)
(H : ∀x y : s, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε₂) :
GH_dist α β ≤ ε₁ + ε₂ / 2 + ε₃ :=
begin
refine real.le_of_forall_epsilon_le (λδ δ0, _),
rcases exists_mem_of_nonempty α with ⟨xα, _⟩,
rcases hs xα with ⟨xs, hxs, Dxs⟩,
have sne : s.nonempty := ⟨xs, hxs⟩,
letI : nonempty s := sne.to_subtype,
have : 0 ≤ ε₂ := le_trans (abs_nonneg _) (H ⟨xs, hxs⟩ ⟨xs, hxs⟩),
have : ∀ p q : s, abs (dist p q - dist (Φ p) (Φ q)) ≤ 2 * (ε₂/2 + δ) := λp q, calc
abs (dist p q - dist (Φ p) (Φ q)) ≤ ε₂ : H p q
... ≤ 2 * (ε₂/2 + δ) : by linarith,
-- glue `α` and `β` along the almost matching subsets
letI : metric_space (α ⊕ β) := glue_metric_approx (λ x:s, (x:α)) (λx, Φ x) (ε₂/2 + δ) (by linarith) this,
let Fl := @sum.inl α β,
let Fr := @sum.inr α β,
have Il : isometry Fl := isometry_emetric_iff_metric.2 (λx y, rfl),
have Ir : isometry Fr := isometry_emetric_iff_metric.2 (λx y, rfl),
/- The proof goes as follows : the `GH_dist` is bounded by the Hausdorff distance of the images in the
coupling, which is bounded (using the triangular inequality) by the sum of the Hausdorff distances
of `α` and `s` (in the coupling or, equivalently in the original space), of `s` and `Φ s`, and of
`Φ s` and `β` (in the coupling or, equivalently, in the original space). The first term is bounded
by `ε₁`, by `ε₁`-density. The third one is bounded by `ε₃`. And the middle one is bounded by `ε₂/2`
as in the coupling the points `x` and `Φ x` are at distance `ε₂/2` by construction of the coupling
(in fact `ε₂/2 + δ` where `δ` is an arbitrarily small positive constant where positivity is used
to ensure that the coupling is really a metric space and not a premetric space on `α ⊕ β`). -/
have : GH_dist α β ≤ Hausdorff_dist (range Fl) (range Fr) :=
GH_dist_le_Hausdorff_dist Il Ir,
have : Hausdorff_dist (range Fl) (range Fr) ≤ Hausdorff_dist (range Fl) (Fl '' s)
+ Hausdorff_dist (Fl '' s) (range Fr),
{ have B : bounded (range Fl) := (compact_range Il.continuous).bounded,
exact Hausdorff_dist_triangle (Hausdorff_edist_ne_top_of_nonempty_of_bounded
(range_nonempty _) (sne.image _) B (B.subset (image_subset_range _ _))) },
have : Hausdorff_dist (Fl '' s) (range Fr) ≤ Hausdorff_dist (Fl '' s) (Fr '' (range Φ))
+ Hausdorff_dist (Fr '' (range Φ)) (range Fr),
{ have B : bounded (range Fr) := (compact_range Ir.continuous).bounded,
exact Hausdorff_dist_triangle' (Hausdorff_edist_ne_top_of_nonempty_of_bounded
((range_nonempty _).image _) (range_nonempty _)
(bounded.subset (image_subset_range _ _) B) B) },
have : Hausdorff_dist (range Fl) (Fl '' s) ≤ ε₁,
{ rw [← image_univ, Hausdorff_dist_image Il],
have : 0 ≤ ε₁ := le_trans dist_nonneg Dxs,
refine Hausdorff_dist_le_of_mem_dist this (λx hx, hs x)
(λx hx, ⟨x, mem_univ _, by simpa⟩) },
have : Hausdorff_dist (Fl '' s) (Fr '' (range Φ)) ≤ ε₂/2 + δ,
{ refine Hausdorff_dist_le_of_mem_dist (by linarith) _ _,
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨x, ⟨x_in_s, xx'⟩⟩,
rw ← xx',
use [Fr (Φ ⟨x, x_in_s⟩), mem_image_of_mem Fr (mem_range_self _)],
exact le_of_eq (glue_dist_glued_points (λ x:s, (x:α)) Φ (ε₂/2 + δ) ⟨x, x_in_s⟩) },
{ assume x' hx',
rcases (set.mem_image _ _ _).1 hx' with ⟨y, ⟨y_in_s', yx'⟩⟩,
rcases mem_range.1 y_in_s' with ⟨x, xy⟩,
use [Fl x, mem_image_of_mem _ x.2],
rw [← yx', ← xy, dist_comm],
exact le_of_eq (glue_dist_glued_points (@subtype.val α s) Φ (ε₂/2 + δ) x) } },
have : Hausdorff_dist (Fr '' (range Φ)) (range Fr) ≤ ε₃,
{ rw [← @image_univ _ _ Fr, Hausdorff_dist_image Ir],
rcases exists_mem_of_nonempty β with ⟨xβ, _⟩,
rcases hs' xβ with ⟨xs', Dxs'⟩,
have : 0 ≤ ε₃ := le_trans dist_nonneg Dxs',
refine Hausdorff_dist_le_of_mem_dist this (λx hx, ⟨x, mem_univ _, by simpa⟩) (λx _, _),
rcases hs' x with ⟨y, Dy⟩,
exact ⟨Φ y, mem_range_self _, Dy⟩ },
linarith
end
end --section
/-- The Gromov-Hausdorff space is second countable. -/
instance second_countable : second_countable_topology GH_space :=
begin
refine second_countable_of_countable_discretization (λδ δpos, _),
let ε := (2/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
have : ∀p:GH_space, ∃s : set (p.rep), finite s ∧ (univ ⊆ (⋃x∈s, ball x ε)) :=
λp, by simpa using finite_cover_balls_of_compact (@compact_univ p.rep _ _) εpos,
-- for each `p`, `s p` is a finite `ε`-dense subset of `p` (or rather the metric space
-- `p.rep` representing `p`)
choose s hs using this,
have : ∀p:GH_space, ∀t:set (p.rep), finite t → ∃n:ℕ, ∃e:equiv t (fin n), true,
{ assume p t ht,
letI : fintype t := finite.fintype ht,
rcases fintype.exists_equiv_fin t with ⟨n, hn⟩,
rcases hn with e,
exact ⟨n, e, trivial⟩ },
choose N e hne using this,
-- cardinality of the nice finite subset `s p` of `p.rep`, called `N p`
let N := λp:GH_space, N p (s p) (hs p).1,
-- equiv from `s p`, a nice finite subset of `p.rep`, to `fin (N p)`, called `E p`
let E := λp:GH_space, e p (s p) (hs p).1,
-- A function `F` associating to `p : GH_space` the data of all distances between points
-- in the `ε`-dense set `s p`.
let F : GH_space → Σn:ℕ, (fin n → fin n → ℤ) :=
λp, ⟨N p, λa b, floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))⟩,
refine ⟨_, by apply_instance, F, λp q hpq, _⟩,
/- As the target space of F is countable, it suffices to show that two points
`p` and `q` with `F p = F q` are at distance `≤ δ`.
For this, we construct a map `Φ` from `s p ⊆ p.rep` (representing `p`)
to `q.rep` (representing `q`) which is almost an isometry on `s p`, and
with image `s q`. For this, we compose the identification of `s p` with `fin (N p)`
and the inverse of the identification of `s q` with `fin (N q)`. Together with
the fact that `N p = N q`, this constructs `Ψ` between `s p` and `s q`, and then
composing with the canonical inclusion we get `Φ`. -/
have Npq : N p = N q := (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λx, Ψ x,
-- Use the almost isometry `Φ` to show that `p.rep` and `q.rep`
-- are within controlled Gromov-Hausdorff distance.
have main : GH_dist p.rep q.rep ≤ ε + ε/2 + ε,
{ refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y ε := (hs p).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_of_lt hy⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y ε := (hs q).2 (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i := ((E q) ⟨y, ys⟩).1,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_of_lt hy },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i := ((E p) x).1,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j := ((E p) y).1,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have : (F p).2 ((E p) x) ((E p) y) = floor (ε⁻¹ * dist x y),
by simp only [F, (E p).symm_apply_apply],
have Ap : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = floor (ε⁻¹ * dist x y),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; refl },
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have : (F q).2 ((E q) (Ψ x)) ((E q) (Ψ y)) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by simp only [F, (E q).symm_apply_apply],
have Aq : (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩ = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
by { rw ← this, congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] },
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : (F p).2 ⟨i, hip⟩ ⟨j, hjp⟩ = (F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
rw [Ap, Aq] at this,
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ : by { simp [ε], ring }
end
/-- Compactness criterion: a closed set of compact metric spaces is compact if the spaces have
a uniformly bounded diameter, and for all `ε` the number of balls of radius `ε` required
to cover the spaces is uniformly bounded. This is an equivalence, but we only prove the
interesting direction that these conditions imply compactness. -/
lemma totally_bounded {t : set GH_space} {C : ℝ} {u : ℕ → ℝ} {K : ℕ → ℕ}
(ulim : tendsto u at_top (𝓝 0))
(hdiam : ∀p ∈ t, diam (univ : set (GH_space.rep p)) ≤ C)
(hcov : ∀p ∈ t, ∀n:ℕ, ∃s : set (GH_space.rep p), cardinal.mk s ≤ K n ∧ univ ⊆ ⋃x∈s, ball x (u n)) :
totally_bounded t :=
begin
/- Let `δ>0`, and `ε = δ/5`. For each `p`, we construct a finite subset `s p` of `p`, which
is `ε`-dense and has cardinality at most `K n`. Encoding the mutual distances of points in `s p`,
up to `ε`, we will get a map `F` associating to `p` finitely many data, and making it possible to
reconstruct `p` up to `ε`. This is enough to prove total boundedness. -/
refine metric.totally_bounded_of_finite_discretization (λδ δpos, _),
let ε := (1/5) * δ,
have εpos : 0 < ε := mul_pos (by norm_num) δpos,
-- choose `n` for which `u n < ε`
rcases metric.tendsto_at_top.1 ulim ε εpos with ⟨n, hn⟩,
have u_le_ε : u n ≤ ε,
{ have := hn n (le_refl _),
simp only [real.dist_eq, add_zero, sub_eq_add_neg, neg_zero] at this,
exact le_of_lt (lt_of_le_of_lt (le_abs_self _) this) },
-- construct a finite subset `s p` of `p` which is `ε`-dense and has cardinal `≤ K n`
have : ∀p:GH_space, ∃s : set (p.rep), ∃N ≤ K n, ∃E : equiv s (fin N),
p ∈ t → univ ⊆ ⋃x∈s, ball x (u n),
{ assume p,
by_cases hp : p ∉ t,
{ have : nonempty (equiv (∅ : set (p.rep)) (fin 0)),
{ rw ← fintype.card_eq, simp },
use [∅, 0, bot_le, choice (this)] },
{ rcases hcov _ (set.not_not_mem.1 hp) n with ⟨s, ⟨scard, scover⟩⟩,
rcases cardinal.lt_omega.1 (lt_of_le_of_lt scard (cardinal.nat_lt_omega _)) with ⟨N, hN⟩,
rw [hN, cardinal.nat_cast_le] at scard,
have : cardinal.mk s = cardinal.mk (fin N), by rw [hN, cardinal.mk_fin],
cases quotient.exact this with E,
use [s, N, scard, E],
simp [hp, scover] } },
choose s N hN E hs using this,
-- Define a function `F` taking values in a finite type and associating to `p` enough data
-- to reconstruct it up to `ε`, namely the (discretized) distances between elements of `s p`.
let M := (floor (ε⁻¹ * max C 0)).to_nat,
let F : GH_space → (Σk:fin ((K n).succ), (fin k → fin k → fin (M.succ))) :=
λp, ⟨⟨N p, lt_of_le_of_lt (hN p) (nat.lt_succ_self _)⟩,
λa b, ⟨min M (floor (ε⁻¹ * dist ((E p).symm a) ((E p).symm b))).to_nat,
lt_of_le_of_lt ( min_le_left _ _) (nat.lt_succ_self _) ⟩ ⟩,
refine ⟨_, by apply_instance, (λp, F p), _⟩,
-- It remains to show that if `F p = F q`, then `p` and `q` are `ε`-close
rintros ⟨p, pt⟩ ⟨q, qt⟩ hpq,
have Npq : N p = N q := (fin.ext_iff _ _).1 (sigma.mk.inj_iff.1 hpq).1,
let Ψ : s p → s q := λx, (E q).symm (fin.cast Npq ((E p) x)),
let Φ : s p → q.rep := λx, Ψ x,
have main : GH_dist (p.rep) (q.rep) ≤ ε + ε/2 + ε,
{ -- to prove the main inequality, argue that `s p` is `ε`-dense in `p`, and `s q` is `ε`-dense
-- in `q`, and `s p` and `s q` are almost isometric. Then closeness follows
-- from `GH_dist_le_of_approx_subsets`
refine GH_dist_le_of_approx_subsets Φ _ _ _,
show ∀x : p.rep, ∃ (y : p.rep) (H : y ∈ s p), dist x y ≤ ε,
{ -- by construction, `s p` is `ε`-dense
assume x,
have : x ∈ ⋃y∈(s p), ball y (u n) := (hs p pt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
exact ⟨y, ys, le_trans (le_of_lt hy) u_le_ε⟩ },
show ∀x : q.rep, ∃ (z : s p), dist x (Φ z) ≤ ε,
{ -- by construction, `s q` is `ε`-dense, and it is the range of `Φ`
assume x,
have : x ∈ ⋃y∈(s q), ball y (u n) := (hs q qt) (mem_univ _),
rcases mem_bUnion_iff.1 this with ⟨y, ys, hy⟩,
let i := ((E q) ⟨y, ys⟩).1,
let hi := ((E q) ⟨y, ys⟩).2,
have ihi_eq : (⟨i, hi⟩ : fin (N q)) = (E q) ⟨y, ys⟩, by rw fin.ext_iff,
have hiq : i < N q := hi,
have hip : i < N p, { rwa Npq.symm at hiq },
let z := (E p).symm ⟨i, hip⟩,
use z,
have C1 : (E p) z = ⟨i, hip⟩ := (E p).apply_symm_apply ⟨i, hip⟩,
have C2 : fin.cast Npq ⟨i, hip⟩ = ⟨i, hi⟩ := rfl,
have C3 : (E q).symm ⟨i, hi⟩ = ⟨y, ys⟩, by { rw ihi_eq, exact (E q).symm_apply_apply ⟨y, ys⟩ },
have : Φ z = y :=
by { simp only [Φ, Ψ], rw [C1, C2, C3], refl },
rw this,
exact le_trans (le_of_lt hy) u_le_ε },
show ∀x y : s p, abs (dist x y - dist (Φ x) (Φ y)) ≤ ε,
{ /- the distance between `x` and `y` is encoded in `F p`, and the distance between
`Φ x` and `Φ y` (two points of `s q`) is encoded in `F q`, all this up to `ε`.
As `F p = F q`, the distances are almost equal. -/
assume x y,
have : dist (Φ x) (Φ y) = dist (Ψ x) (Ψ y) := rfl,
rw this,
-- introduce `i`, that codes both `x` and `Φ x` in `fin (N p) = fin (N q)`
let i := ((E p) x).1,
have hip : i < N p := ((E p) x).2,
have hiq : i < N q, by rwa Npq at hip,
have i' : i = ((E q) (Ψ x)).1, by { simp [Ψ] },
-- introduce `j`, that codes both `y` and `Φ y` in `fin (N p) = fin (N q)`
let j := ((E p) y).1,
have hjp : j < N p := ((E p) y).2,
have hjq : j < N q, by rwa Npq at hjp,
have j' : j = ((E q) (Ψ y)).1, by { simp [Ψ] },
-- Express `dist x y` in terms of `F p`
have Ap : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = (floor (ε⁻¹ * dist x y)).to_nat := calc
((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F p).2 ((E p) x) ((E p) y)).1 :
by { congr; apply (fin.ext_iff _ _).2; refl }
... = min M (floor (ε⁻¹ * dist x y)).to_nat :
by simp only [F, (E p).symm_apply_apply]
... = (floor (ε⁻¹ * dist x y)).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)),
change dist (x : p.rep) y ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam p pt
end,
-- Express `dist (Φ x) (Φ y)` in terms of `F q`
have Aq : ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat := calc
((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1 = ((F q).2 ((E q) (Ψ x)) ((E q) (Ψ y))).1 :
by { congr; apply (fin.ext_iff _ _).2; [exact i', exact j'] }
... = min M (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
by simp only [F, (E q).symm_apply_apply]
... = (floor (ε⁻¹ * dist (Ψ x) (Ψ y))).to_nat :
begin
refine min_eq_right (int.to_nat_le_to_nat (floor_mono _)),
refine mul_le_mul_of_nonneg_left (le_trans _ (le_max_left _ _)) (le_of_lt (inv_pos.2 εpos)),
change dist (Ψ x : q.rep) (Ψ y) ≤ C,
refine le_trans (dist_le_diam_of_mem compact_univ.bounded (mem_univ _) (mem_univ _)) _,
exact hdiam q qt
end,
-- use the equality between `F p` and `F q` to deduce that the distances have equal
-- integer parts
have : ((F p).2 ⟨i, hip⟩ ⟨j, hjp⟩).1 = ((F q).2 ⟨i, hiq⟩ ⟨j, hjq⟩).1,
{ -- we want to `subst hpq` where `hpq : F p = F q`, except that `subst` only works
-- with a constant, so replace `F q` (and everything that depends on it) by a constant `f`
-- then `subst`
revert hiq hjq,
change N q with (F q).1,
generalize_hyp : F q = f at hpq ⊢,
subst hpq,
intros,
refl },
have : floor (ε⁻¹ * dist x y) = floor (ε⁻¹ * dist (Ψ x) (Ψ y)),
{ rw [Ap, Aq] at this,
have D : 0 ≤ floor (ε⁻¹ * dist x y) :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
have D' : floor (ε⁻¹ * dist (Ψ x) (Ψ y)) ≥ 0 :=
floor_nonneg.2 (mul_nonneg (le_of_lt (inv_pos.2 εpos)) dist_nonneg),
rw [← int.to_nat_of_nonneg D, ← int.to_nat_of_nonneg D', this] },
-- deduce that the distances coincide up to `ε`, by a straightforward computation
-- that should be automated
have I := calc
abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) =
abs (ε⁻¹ * (dist x y - dist (Ψ x) (Ψ y))) : (abs_mul _ _).symm
... = abs ((ε⁻¹ * dist x y) - (ε⁻¹ * dist (Ψ x) (Ψ y))) : by { congr, ring }
... ≤ 1 : le_of_lt (abs_sub_lt_one_of_floor_eq_floor this),
calc
abs (dist x y - dist (Ψ x) (Ψ y)) = (ε * ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y)) :
by rw [mul_inv_cancel (ne_of_gt εpos), one_mul]
... = ε * (abs (ε⁻¹) * abs (dist x y - dist (Ψ x) (Ψ y))) :
by rw [abs_of_nonneg (le_of_lt (inv_pos.2 εpos)), mul_assoc]
... ≤ ε * 1 : mul_le_mul_of_nonneg_left I (le_of_lt εpos)
... = ε : mul_one _ } },
calc dist p q = GH_dist (p.rep) (q.rep) : dist_GH_dist p q
... ≤ ε + ε/2 + ε : main
... = δ/2 : by { simp [ε], ring }
... < δ : half_lt_self δpos
end
section complete
/- We will show that a sequence `u n` of compact metric spaces satisfying
`dist (u n) (u (n+1)) < 1/2^n` converges, which implies completeness of the Gromov-Hausdorff space.
We need to exhibit the limiting compact metric space. For this, start from
a sequence `X n` of representatives of `u n`, and glue in an optimal way `X n` to `X (n+1)`
for all `n`, in a common metric space. Formally, this is done as follows.
Start from `Y 0 = X 0`. Then, glue `X 0` to `X 1` in an optimal way, yielding a space
`Y 1` (with an embedding of `X 1`). Then, consider an optimal gluing of `X 1` and `X 2`, and
glue it to `Y 1` along their common subspace `X 1`. This gives a new space `Y 2`, with an
embedding of `X 2`. Go on, to obtain a sequence of spaces `Y n`. Let `Z0` be the inductive
limit of the `Y n`, and finally let `Z` be the completion of `Z0`.
The images `X2 n` of `X n` in `Z` are at Hausdorff distance `< 1/2^n` by construction, hence they
form a Cauchy sequence for the Hausdorff distance. By completeness (of `Z`, and therefore of its
set of nonempty compact subsets), they converge to a limit `L`. This is the nonempty
compact metric space we are looking for. -/
variables (X : ℕ → Type) [∀n, metric_space (X n)] [∀n, compact_space (X n)] [∀n, nonempty (X n)]
/-- Auxiliary structure used to glue metric spaces below, recording an isometric embedding
of a type `A` in another metric space. -/
structure aux_gluing_struct (A : Type) [metric_space A] : Type 1 :=
(space : Type)
(metric : metric_space space)
(embed : A → space)
(isom : isometry embed)
/-- Auxiliary sequence of metric spaces, containing copies of `X 0`, ..., `X n`, where each
`X i` is glued to `X (i+1)` in an optimal way. The space at step `n+1` is obtained from the space
at step `n` by adding `X (n+1)`, glued in an optimal way to the `X n` already sitting there. -/
def aux_gluing (n : ℕ) : aux_gluing_struct (X n) := nat.rec_on n
{ space := X 0,
metric := by apply_instance,
embed := id,
isom := λx y, rfl }
(λn a, by letI : metric_space a.space := a.metric; exact
{ space := glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
metric := metric.metric_space_glue_space a.isom (isometry_optimal_GH_injl (X n) (X n.succ)),
embed := (to_glue_r a.isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injr (X n) (X n.succ)),
isom := (to_glue_r_isometry _ _).comp (isometry_optimal_GH_injr (X n) (X n.succ)) })
/-- The Gromov-Hausdorff space is complete. -/
instance : complete_space (GH_space) :=
begin
have : ∀ (n : ℕ), 0 < ((1:ℝ) / 2) ^ n, by { apply _root_.pow_pos, norm_num },
-- start from a sequence of nonempty compact metric spaces within distance `1/2^n` of each other
refine metric.complete_of_convergent_controlled_sequences (λn, (1/2)^n) this (λu hu, _),
-- `X n` is a representative of `u n`
let X := λn, (u n).rep,
-- glue them together successively in an optimal way, getting a sequence of metric spaces `Y n`
let Y := aux_gluing X,
letI : ∀n, metric_space (Y n).space := λn, (Y n).metric,
have E : ∀n:ℕ, glue_space (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)) = (Y n.succ).space :=
λn, by { simp [Y, aux_gluing], refl },
let c := λn, cast (E n),
have ic : ∀n, isometry (c n) := λn x y, rfl,
-- there is a canonical embedding of `Y n` in `Y (n+1)`, by construction
let f : Πn, (Y n).space → (Y n.succ).space :=
λn, (c n) ∘ (to_glue_l (aux_gluing X n).isom (isometry_optimal_GH_injl (X n) (X n.succ))),
have I : ∀n, isometry (f n),
{ assume n,
apply isometry.comp,
{ assume x y, refl },
{ apply to_glue_l_isometry } },
-- consider the inductive limit `Z0` of the `Y n`, and then its completion `Z`
let Z0 := metric.inductive_limit I,
let Z := uniform_space.completion Z0,
let Φ := to_inductive_limit I,
let coeZ := (coe : Z0 → Z),
-- let `X2 n` be the image of `X n` in the space `Z`
let X2 := λn, range (coeZ ∘ (Φ n) ∘ (Y n).embed),
have isom : ∀n, isometry (coeZ ∘ (Φ n) ∘ (Y n).embed),
{ assume n,
apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ (Y n).isom,
apply to_inductive_limit_isometry },
-- The Hausdorff distance of `X2 n` and `X2 (n+1)` is by construction the distance between
-- `u n` and `u (n+1)`, therefore bounded by `1/2^n`
have D2 : ∀n, Hausdorff_dist (X2 n) (X2 n.succ) < (1/2)^n,
{ assume n,
have X2n : X2 n = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injl (X n) (X n.succ))),
{ change X2 n = range (coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ)))
∘ (optimal_GH_injl (X n) (X n.succ))),
simp only [X2, Φ],
rw [← to_inductive_limit_commute I],
simp only [f],
rw ← to_glue_commute },
rw range_comp at X2n,
have X2nsucc : X2 n.succ = range ((coeZ ∘ (Φ n.succ) ∘ (c n)
∘ (to_glue_r (Y n).isom (isometry_optimal_GH_injl (X n) (X n.succ))))
∘ (optimal_GH_injr (X n) (X n.succ))), by refl,
rw range_comp at X2nsucc,
rw [X2n, X2nsucc, Hausdorff_dist_image, Hausdorff_dist_optimal, ← dist_GH_dist],
{ exact hu n n n.succ (le_refl n) (le_succ n) },
{ apply isometry.comp completion.coe_isometry _,
apply isometry.comp _ ((ic n).comp (to_glue_r_isometry _ _)),
apply to_inductive_limit_isometry } },
-- consider `X2 n` as a member `X3 n` of the type of nonempty compact subsets of `Z`, which
-- is a metric space
let X3 : ℕ → nonempty_compacts Z := λn, ⟨X2 n,
⟨range_nonempty _, compact_range (isom n).continuous ⟩⟩,
-- `X3 n` is a Cauchy sequence by construction, as the successive distances are
-- bounded by `(1/2)^n`
have : cauchy_seq X3,
{ refine cauchy_seq_of_le_geometric (1/2) 1 (by norm_num) (λn, _),
rw one_mul,
exact le_of_lt (D2 n) },
-- therefore, it converges to a limit `L`
rcases cauchy_seq_tendsto_of_complete this with ⟨L, hL⟩,
-- the images of `X3 n` in the Gromov-Hausdorff space converge to the image of `L`
have M : tendsto (λn, (X3 n).to_GH_space) at_top (𝓝 L.to_GH_space) :=
tendsto.comp (to_GH_space_continuous.tendsto _) hL,
-- By construction, the image of `X3 n` in the Gromov-Hausdorff space is `u n`.
have : ∀n, (X3 n).to_GH_space = u n,
{ assume n,
rw [nonempty_compacts.to_GH_space, ← (u n).to_GH_space_rep,
to_GH_space_eq_to_GH_space_iff_isometric],
constructor,
convert (isom n).isometric_on_range.symm,
},
-- Finally, we have proved the convergence of `u n`
exact ⟨L.to_GH_space, by simpa [this] using M⟩
end
end complete--section
end Gromov_Hausdorff --namespace
|
7423fae888b16e65d3f2a1719722d9a611d7d5f1 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/category_theory/limits/opposites.lean | d80da9d4b511f61b2c895cf0fb0a95df05f5ab9c | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 25,718 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Floris van Doorn
-/
import category_theory.limits.shapes.finite_products
import category_theory.discrete_category
import tactic.equiv_rw
/-!
# Limits in `C` give colimits in `Cᵒᵖ`.
We also give special cases for (co)products,
(co)equalizers, and pullbacks / pushouts.
-/
universes v₁ v₂ u₁ u₂
noncomputable theory
open category_theory
open category_theory.functor
open opposite
namespace category_theory.limits
variables {C : Type u₁} [category.{v₁} C]
variables {J : Type u₂} [category.{v₂} J]
/-- Turn a colimit for `F : J ⥤ C` into a limit for `F.op : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps] def is_limit_cocone_op (F : J ⥤ C) {c : cocone F} (hc : is_colimit c) :
is_limit c.op :=
{ lift := λ s, (hc.desc s.unop).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F : J ⥤ C` into a colimit for `F.op : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps] def is_colimit_cone_op (F : J ⥤ C) {c : cone F} (hc : is_limit c) :
is_colimit c.op :=
{ desc := λ s, (hc.lift s.unop).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j)
end }
/-- Turn a colimit for `F : J ⥤ Cᵒᵖ` into a limit for `F.left_op : Jᵒᵖ ⥤ C`. -/
@[simps] def is_limit_cone_left_op_of_cocone (F : J ⥤ Cᵒᵖ) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_left_op_of_cocone c) :=
{ lift := λ s, (hc.desc (cocone_of_cone_left_op s)).unop,
fac' := λ s j, quiver.hom.op_inj $ by simpa only [cone_left_op_of_cocone_π_app, op_comp,
quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ι_app],
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac, cocone_of_cone_left_op_ι_app] using w (op j)
end }
/-- Turn a limit of `F : J ⥤ Cᵒᵖ` into a colimit of `F.left_op : Jᵒᵖ ⥤ C`. -/
@[simps] def is_colimit_cocone_left_op_of_cone (F : J ⥤ Cᵒᵖ) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_left_op_of_cone c) :=
{ desc := λ s, (hc.lift (cone_of_cocone_left_op s)).unop,
fac' := λ s j, quiver.hom.op_inj $ by simpa only [cocone_left_op_of_cone_ι_app, op_comp,
quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_π_app],
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac, cone_of_cocone_left_op_π_app] using w (op j)
end }
/-- Turn a colimit for `F : Jᵒᵖ ⥤ C` into a limit for `F.right_op : J ⥤ Cᵒᵖ`. -/
@[simps] def is_limit_cone_right_op_of_cocone (F : Jᵒᵖ ⥤ C) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_right_op_of_cocone c) :=
{ lift := λ s, (hc.desc (cocone_of_cone_right_op s)).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit for `F : Jᵒᵖ ⥤ C` into a colimit for `F.right_op : J ⥤ Cᵒᵖ`. -/
@[simps] def is_colimit_cocone_right_op_of_cone (F : Jᵒᵖ ⥤ C) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_right_op_of_cone c) :=
{ desc := λ s, (hc.lift (cone_of_cocone_right_op s)).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ` into a limit for `F.unop : J ⥤ C`. -/
@[simps] def is_limit_cone_unop_of_cocone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : cocone F} (hc : is_colimit c) :
is_limit (cone_unop_of_cocone c) :=
{ lift := λ s, (hc.desc (cocone_of_cone_unop s)).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit of `F : Jᵒᵖ ⥤ Cᵒᵖ` into a colimit of `F.unop : J ⥤ C`. -/
@[simps] def is_colimit_cocone_unop_of_cone (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : cone F} (hc : is_limit c) :
is_colimit (cocone_unop_of_cone c) :=
{ desc := λ s, (hc.lift (cone_of_cocone_unop s)).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F.op : Jᵒᵖ ⥤ Cᵒᵖ` into a limit for `F : J ⥤ C`. -/
@[simps] def is_limit_cocone_unop (F : J ⥤ C) {c : cocone F.op} (hc : is_colimit c) :
is_limit c.unop :=
{ lift := λ s, (hc.desc s.op).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (unop j)
end }
/-- Turn a limit for `F.op : Jᵒᵖ ⥤ Cᵒᵖ` into a colimit for `F : J ⥤ C`. -/
@[simps] def is_colimit_cone_unop (F : J ⥤ C) {c : cone F.op} (hc : is_limit c) :
is_colimit c.unop :=
{ desc := λ s, (hc.lift s.op).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (unop j)
end }
/-- Turn a colimit for `F.left_op : Jᵒᵖ ⥤ C` into a limit for `F : J ⥤ Cᵒᵖ`. -/
@[simps] def is_limit_cone_of_cocone_left_op (F : J ⥤ Cᵒᵖ) {c : cocone F.left_op}
(hc : is_colimit c) : is_limit (cone_of_cocone_left_op c) :=
{ lift := λ s, (hc.desc (cocone_left_op_of_cone s)).op,
fac' := λ s j, quiver.hom.unop_inj $ by simpa only [cone_of_cocone_left_op_π_app, unop_comp,
quiver.hom.unop_op, is_colimit.fac, cocone_left_op_of_cone_ι_app],
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac, cone_of_cocone_left_op_π_app] using w (unop j)
end }
/-- Turn a limit of `F.left_op : Jᵒᵖ ⥤ C` into a colimit of `F : J ⥤ Cᵒᵖ`. -/
@[simps] def is_colimit_cocone_of_cone_left_op (F : J ⥤ Cᵒᵖ) {c : cone (F.left_op)}
(hc : is_limit c) : is_colimit (cocone_of_cone_left_op c) :=
{ desc := λ s, (hc.lift (cone_left_op_of_cocone s)).op,
fac' := λ s j, quiver.hom.unop_inj $ by simpa only [cocone_of_cone_left_op_ι_app, unop_comp,
quiver.hom.unop_op, is_limit.fac, cone_left_op_of_cocone_π_app],
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac, cocone_of_cone_left_op_ι_app] using w (unop j)
end }
/-- Turn a colimit for `F.right_op : J ⥤ Cᵒᵖ` into a limit for `F : Jᵒᵖ ⥤ C`. -/
@[simps] def is_limit_cone_of_cocone_right_op (F : Jᵒᵖ ⥤ C) {c : cocone F.right_op}
(hc : is_colimit c) : is_limit (cone_of_cocone_right_op c) :=
{ lift := λ s, (hc.desc (cocone_right_op_of_cone s)).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F.right_op : J ⥤ Cᵒᵖ` into a limit for `F : Jᵒᵖ ⥤ C`. -/
@[simps] def is_colimit_cocone_of_cone_right_op (F : Jᵒᵖ ⥤ C) {c : cone F.right_op}
(hc : is_limit c) : is_colimit (cocone_of_cone_right_op c) :=
{ desc := λ s, (hc.lift (cone_right_op_of_cocone s)).unop,
fac' := λ s j, quiver.hom.op_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.op_inj (hc.hom_ext (λ j, quiver.hom.unop_inj _)),
simpa only [quiver.hom.op_unop, is_limit.fac] using w (op j)
end }
/-- Turn a colimit for `F.unop : J ⥤ C` into a limit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps] def is_limit_cone_of_cocone_unop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : cocone F.unop} (hc : is_colimit c) :
is_limit (cone_of_cocone_unop c) :=
{ lift := λ s, (hc.desc (cocone_unop_of_cone s)).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_colimit.fac] using w (op j)
end }
/-- Turn a limit for `F.unop : J ⥤ C` into a colimit for `F : Jᵒᵖ ⥤ Cᵒᵖ`. -/
@[simps] def is_colimit_cone_of_cocone_unop (F : Jᵒᵖ ⥤ Cᵒᵖ) {c : cone F.unop} (hc : is_limit c) :
is_colimit (cocone_of_cone_unop c) :=
{ desc := λ s, (hc.lift (cone_unop_of_cocone s)).op,
fac' := λ s j, quiver.hom.unop_inj (by simpa),
uniq' := λ s m w,
begin
refine quiver.hom.unop_inj (hc.hom_ext (λ j, quiver.hom.op_inj _)),
simpa only [quiver.hom.unop_op, is_limit.fac] using w (op j)
end }
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a colimit, we can construct a limit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_limit_of_has_colimit_left_op (F : J ⥤ Cᵒᵖ) [has_colimit F.left_op] : has_limit F :=
has_limit.mk
{ cone := cone_of_cocone_left_op (colimit.cocone F.left_op),
is_limit := is_limit_cone_of_cocone_left_op _ (colimit.is_colimit _) }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_limits_of_shape_op_of_has_colimits_of_shape [has_colimits_of_shape Jᵒᵖ C] :
has_limits_of_shape J Cᵒᵖ :=
{ has_limit := λ F, has_limit_of_has_colimit_left_op F }
local attribute [instance] has_limits_of_shape_op_of_has_colimits_of_shape
/--
If `C` has colimits, we can construct limits for `Cᵒᵖ`.
-/
lemma has_limits_op_of_has_colimits [has_colimits C] : has_limits Cᵒᵖ := ⟨infer_instance⟩
/--
If `F.left_op : Jᵒᵖ ⥤ C` has a limit, we can construct a colimit for `F : J ⥤ Cᵒᵖ`.
-/
lemma has_colimit_of_has_limit_left_op (F : J ⥤ Cᵒᵖ) [has_limit F.left_op] : has_colimit F :=
has_colimit.mk
{ cocone := cocone_of_cone_left_op (limit.cone F.left_op),
is_colimit := is_colimit_cocone_of_cone_left_op _ (limit.is_limit _) }
/--
If `C` has colimits of shape `Jᵒᵖ`, we can construct limits in `Cᵒᵖ` of shape `J`.
-/
lemma has_colimits_of_shape_op_of_has_limits_of_shape [has_limits_of_shape Jᵒᵖ C] :
has_colimits_of_shape J Cᵒᵖ :=
{ has_colimit := λ F, has_colimit_of_has_limit_left_op F }
local attribute [instance] has_colimits_of_shape_op_of_has_limits_of_shape
/--
If `C` has limits, we can construct colimits for `Cᵒᵖ`.
-/
lemma has_colimits_op_of_has_limits [has_limits C] : has_colimits Cᵒᵖ := ⟨infer_instance⟩
variables (X : Type v₁)
/--
If `C` has products indexed by `X`, then `Cᵒᵖ` has coproducts indexed by `X`.
-/
lemma has_coproducts_opposite [has_products_of_shape X C] :
has_coproducts_of_shape X Cᵒᵖ :=
begin
haveI : has_limits_of_shape (discrete X)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
/--
If `C` has coproducts indexed by `X`, then `Cᵒᵖ` has products indexed by `X`.
-/
lemma has_products_opposite [has_coproducts_of_shape X C] :
has_products_of_shape X Cᵒᵖ :=
begin
haveI : has_colimits_of_shape (discrete X)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite X).symm,
apply_instance
end
lemma has_finite_coproducts_opposite [has_finite_products C] : has_finite_coproducts Cᵒᵖ :=
{ out := λ J 𝒟, begin
resetI,
haveI : has_limits_of_shape (discrete J)ᵒᵖ C :=
has_limits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
lemma has_finite_products_opposite [has_finite_coproducts C] : has_finite_products Cᵒᵖ :=
{ out := λ J 𝒟, begin
resetI,
haveI : has_colimits_of_shape (discrete J)ᵒᵖ C :=
has_colimits_of_shape_of_equivalence (discrete.opposite J).symm,
apply_instance,
end }
lemma has_equalizers_opposite [has_coequalizers C] : has_equalizers Cᵒᵖ :=
begin
haveI : has_colimits_of_shape walking_parallel_pairᵒᵖ C :=
has_colimits_of_shape_of_equivalence walking_parallel_pair_op_equiv,
apply_instance
end
lemma has_coequalizers_opposite [has_equalizers C] : has_coequalizers Cᵒᵖ :=
begin
haveI : has_limits_of_shape walking_parallel_pairᵒᵖ C :=
has_limits_of_shape_of_equivalence walking_parallel_pair_op_equiv,
apply_instance
end
lemma has_finite_colimits_opposite [has_finite_limits C] :
has_finite_colimits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
lemma has_finite_limits_opposite [has_finite_colimits C] :
has_finite_limits Cᵒᵖ :=
{ out := λ J 𝒟 𝒥, by { resetI, apply_instance, }, }
lemma has_pullbacks_opposite [has_pushouts C] : has_pullbacks Cᵒᵖ :=
begin
haveI : has_colimits_of_shape walking_cospanᵒᵖ C :=
has_colimits_of_shape_of_equivalence walking_cospan_op_equiv.symm,
apply has_limits_of_shape_op_of_has_colimits_of_shape,
end
lemma has_pushouts_opposite [has_pullbacks C] : has_pushouts Cᵒᵖ :=
begin
haveI : has_limits_of_shape walking_spanᵒᵖ C :=
has_limits_of_shape_of_equivalence walking_span_op_equiv.symm,
apply has_colimits_of_shape_op_of_has_limits_of_shape,
end
/-- The canonical isomorphism relating `span f.op g.op` and `(cospan f g).op` -/
@[simps]
def span_op {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
span f.op g.op ≅ walking_cospan_op_equiv.inverse ⋙ (cospan f g).op :=
nat_iso.of_components (by { rintro (_|_|_); refl, })
(by { rintros (_|_|_) (_|_|_) f; cases f; tidy, })
/-- The canonical isomorphism relating `(cospan f g).op` and `span f.op g.op` -/
@[simps]
def op_cospan {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z) :
(cospan f g).op ≅ walking_cospan_op_equiv.functor ⋙ span f.op g.op :=
calc (cospan f g).op ≅ 𝟭 _ ⋙ (cospan f g).op : by refl
... ≅ (walking_cospan_op_equiv.functor ⋙ walking_cospan_op_equiv.inverse) ⋙ (cospan f g).op :
iso_whisker_right walking_cospan_op_equiv.unit_iso _
... ≅ walking_cospan_op_equiv.functor ⋙ (walking_cospan_op_equiv.inverse ⋙ (cospan f g).op) :
functor.associator _ _ _
... ≅ walking_cospan_op_equiv.functor ⋙ span f.op g.op : iso_whisker_left _ (span_op f g).symm
/-- The canonical isomorphism relating `cospan f.op g.op` and `(span f g).op` -/
@[simps]
def cospan_op {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
cospan f.op g.op ≅ walking_span_op_equiv.inverse ⋙ (span f g).op :=
nat_iso.of_components (by { rintro (_|_|_); refl, })
(by { rintros (_|_|_) (_|_|_) f; cases f; tidy, })
/-- The canonical isomorphism relating `(span f g).op` and `cospan f.op g.op` -/
@[simps]
def op_span {X Y Z : C} (f : X ⟶ Y) (g : X ⟶ Z) :
(span f g).op ≅ walking_span_op_equiv.functor ⋙ cospan f.op g.op :=
calc (span f g).op ≅ 𝟭 _ ⋙ (span f g).op : by refl
... ≅ (walking_span_op_equiv.functor ⋙ walking_span_op_equiv.inverse) ⋙ (span f g).op :
iso_whisker_right walking_span_op_equiv.unit_iso _
... ≅ walking_span_op_equiv.functor ⋙ (walking_span_op_equiv.inverse ⋙ (span f g).op) :
functor.associator _ _ _
... ≅ walking_span_op_equiv.functor ⋙ cospan f.op g.op :
iso_whisker_left _ (cospan_op f g).symm
namespace pushout_cocone
/-- The obvious map `pushout_cocone f g → pullback_cone f.unop g.unop` -/
@[simps (lemmas_only)]
def unop {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
pullback_cone f.unop g.unop :=
cocone.unop ((cocones.precompose (op_cospan f.unop g.unop).hom).obj
(cocone.whisker walking_cospan_op_equiv.functor c))
@[simp]
lemma unop_fst {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
c.unop.fst = c.inl.unop :=
by { change (_ : limits.cone _).π.app _ = _,
simp only [pushout_cocone.ι_app_left, pushout_cocone.unop_π_app], tidy }
@[simp]
lemma unop_snd {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
c.unop.snd = c.inr.unop :=
by { change (_ : limits.cone _).π.app _ = _,
simp only [pushout_cocone.unop_π_app, pushout_cocone.ι_app_right], tidy, }
/-- The obvious map `pushout_cocone f.op g.op → pullback_cone f g` -/
@[simps (lemmas_only)]
def op {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
pullback_cone f.op g.op :=
(cones.postcompose ((cospan_op f g).symm).hom).obj
(cone.whisker walking_span_op_equiv.inverse (cocone.op c))
@[simp]
lemma op_fst {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
c.op.fst = c.inl.op :=
by { change (_ : limits.cone _).π.app _ = _, apply category.comp_id, }
@[simp]
lemma op_snd {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
c.op.snd = c.inr.op :=
by { change (_ : limits.cone _).π.app _ = _, apply category.comp_id, }
end pushout_cocone
namespace pullback_cone
/-- The obvious map `pullback_cone f g → pushout_cocone f.unop g.unop` -/
@[simps (lemmas_only)]
def unop {X Y Z : Cᵒᵖ} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
pushout_cocone f.unop g.unop :=
cone.unop ((cones.postcompose (op_span f.unop g.unop).symm.hom).obj
(cone.whisker walking_span_op_equiv.functor c))
@[simp]
lemma unop_inl {X Y Z : Cᵒᵖ} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
c.unop.inl = c.fst.unop :=
begin
change ((_ : limits.cocone _).ι.app _) = _,
dsimp only [unop, op_span],
simp, dsimp, simp, dsimp, simp
end
@[simp]
lemma unop_inr {X Y Z : Cᵒᵖ} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
c.unop.inr = c.snd.unop :=
begin
change ((_ : limits.cocone _).ι.app _) = _,
apply quiver.hom.op_inj,
simp [unop_ι_app], dsimp, simp,
apply category.comp_id,
end
/-- The obvious map `pullback_cone f g → pushout_cocone f.op g.op` -/
@[simps (lemmas_only)]
def op {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
pushout_cocone f.op g.op :=
(cocones.precompose (span_op f g).hom).obj
(cocone.whisker walking_cospan_op_equiv.inverse (cone.op c))
@[simp] lemma op_inl {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
c.op.inl = c.fst.op :=
by { change (_ : limits.cocone _).ι.app _ = _, apply category.id_comp, }
@[simp] lemma op_inr {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) :
c.op.inr = c.snd.op :=
by { change (_ : limits.cocone _).ι.app _ = _, apply category.id_comp, }
/-- If `c` is a pullback cone, then `c.op.unop` is isomorphic to `c`. -/
def op_unop {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) : c.op.unop ≅ c :=
pullback_cone.ext (iso.refl _) (by simp) (by simp)
/-- If `c` is a pullback cone in `Cᵒᵖ`, then `c.unop.op` is isomorphic to `c`. -/
def unop_op {X Y Z : Cᵒᵖ} {f : X ⟶ Z} {g : Y ⟶ Z} (c : pullback_cone f g) : c.unop.op ≅ c :=
pullback_cone.ext (iso.refl _) (by simp) (by simp)
end pullback_cone
namespace pushout_cocone
/-- If `c` is a pushout cocone, then `c.op.unop` is isomorphic to `c`. -/
def op_unop {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) : c.op.unop ≅ c :=
pushout_cocone.ext (iso.refl _) (by simp) (by simp)
/-- If `c` is a pushout cocone in `Cᵒᵖ`, then `c.unop.op` is isomorphic to `c`. -/
def unop_op {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) : c.unop.op ≅ c :=
pushout_cocone.ext (iso.refl _) (by simp) (by simp)
/-- A pushout cone is a colimit cocone if and only if the corresponding pullback cone
in the opposite category is a limit cone. -/
def is_colimit_equiv_is_limit_op {X Y Z : C} {f : X ⟶ Y} {g : X ⟶ Z} (c : pushout_cocone f g) :
is_colimit c ≃ is_limit c.op :=
begin
apply equiv_of_subsingleton_of_subsingleton,
{ intro h,
equiv_rw is_limit.postcompose_hom_equiv _ _,
equiv_rw (is_limit.whisker_equivalence_equiv walking_span_op_equiv.symm).symm,
exact is_limit_cocone_op _ h, },
{ intro h,
equiv_rw is_colimit.equiv_iso_colimit c.op_unop.symm,
apply is_colimit_cone_unop,
equiv_rw is_limit.postcompose_hom_equiv _ _,
equiv_rw (is_limit.whisker_equivalence_equiv _).symm,
exact h, }
end
/-- A pushout cone is a colimit cocone in `Cᵒᵖ` if and only if the corresponding pullback cone
in `C` is a limit cone. -/
def is_colimit_equiv_is_limit_unop {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : X ⟶ Z}
(c : pushout_cocone f g) : is_colimit c ≃ is_limit c.unop :=
begin
apply equiv_of_subsingleton_of_subsingleton,
{ intro h,
apply is_limit_cocone_unop,
equiv_rw is_colimit.precompose_hom_equiv _ _,
equiv_rw (is_colimit.whisker_equivalence_equiv _).symm,
exact h, },
{ intro h,
equiv_rw is_colimit.equiv_iso_colimit c.unop_op.symm,
equiv_rw is_colimit.precompose_hom_equiv _ _,
equiv_rw (is_colimit.whisker_equivalence_equiv walking_cospan_op_equiv.symm).symm,
exact is_colimit_cone_op _ h, },
end
end pushout_cocone
namespace pullback_cone
/-- A pullback cone is a limit cone if and only if the corresponding pushout cocone
in the opposite category is a colimit cocone. -/
def is_limit_equiv_is_colimit_op {X Y Z : C} {f : X ⟶ Z} {g : Y ⟶ Z}
(c : pullback_cone f g) : is_limit c ≃ is_colimit c.op :=
(is_limit.equiv_iso_limit c.op_unop).symm.trans c.op.is_colimit_equiv_is_limit_unop.symm
/-- A pullback cone is a limit cone in `Cᵒᵖ` if and only if the corresponding pushout cocone
in `C` is a colimit cocone. -/
def is_limit_equiv_is_colimit_unop {X Y Z : Cᵒᵖ} {f : X ⟶ Z} {g : Y ⟶ Z}
(c : pullback_cone f g) : is_limit c ≃ is_colimit c.unop :=
(is_limit.equiv_iso_limit c.unop_op).symm.trans c.unop.is_colimit_equiv_is_limit_op.symm
end pullback_cone
section pullback
open opposite
/-- The pullback of `f` and `g` in `C` is isomorphic to the pushout of
`f.op` and `g.op` in `Cᵒᵖ`. -/
noncomputable
def pullback_iso_unop_pushout {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
[has_pullback f g] [has_pushout f.op g.op] : pullback f g ≅ unop (pushout f.op g.op) :=
is_limit.cone_point_unique_up_to_iso (limit.is_limit _)
((pushout_cocone.is_colimit_equiv_is_limit_unop _) (colimit.is_colimit (span f.op g.op)))
@[simp, reassoc]
lemma pullback_iso_unop_pushout_inv_fst {X Y Z : C} (f : X ⟶ Z) (g : Y ⟶ Z)
[has_pullback f g] [has_pushout f.op g.op] :
(pullback_iso_unop_pushout f g).inv ≫ pullback.fst =
(pushout.inl : _ ⟶ pushout f.op g.op).unop :=
(is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp)
@[simp, reassoc]
lemma pullback_iso_unop_pushout_inv_snd {X Y Z : C} (f : X ⟶ Z)
(g : Y ⟶ Z) [has_pullback f g] [has_pushout f.op g.op] :
(pullback_iso_unop_pushout f g).inv ≫ pullback.snd =
(pushout.inr : _ ⟶ pushout f.op g.op).unop :=
(is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _).trans (by simp)
@[simp, reassoc]
lemma pullback_iso_unop_pushout_hom_inl {X Y Z : C} (f : X ⟶ Z)
(g : Y ⟶ Z) [has_pullback f g] [has_pushout f.op g.op] :
pushout.inl ≫ (pullback_iso_unop_pushout f g).hom.op = pullback.fst.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [← pullback_iso_unop_pushout_inv_fst, iso.hom_inv_id_assoc],
end
@[simp, reassoc]
lemma pullback_iso_unop_pushout_hom_inr {X Y Z : C} (f : X ⟶ Z)
(g : Y ⟶ Z) [has_pullback f g] [has_pushout f.op g.op] :
pushout.inr ≫ (pullback_iso_unop_pushout f g).hom.op = pullback.snd.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [← pullback_iso_unop_pushout_inv_snd, iso.hom_inv_id_assoc],
end
end pullback
section pushout
/-- The pushout of `f` and `g` in `C` is isomorphic to the pullback of
`f.op` and `g.op` in `Cᵒᵖ`. -/
noncomputable
def pushout_iso_unop_pullback {X Y Z : C} (f : X ⟶ Z) (g : X ⟶ Y)
[has_pushout f g] [has_pullback f.op g.op] : pushout f g ≅ unop (pullback f.op g.op) :=
is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _)
((pullback_cone.is_limit_equiv_is_colimit_unop _) (limit.is_limit (cospan f.op g.op)))
.
@[simp, reassoc]
lemma pushout_iso_unop_pullback_inl_hom {X Y Z : C} (f : X ⟶ Z) (g : X ⟶ Y)
[has_pushout f g] [has_pullback f.op g.op] :
pushout.inl ≫ (pushout_iso_unop_pullback f g).hom =
(pullback.fst : pullback f.op g.op ⟶ _).unop :=
(is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp)
@[simp, reassoc]
lemma pushout_iso_unop_pullback_inr_hom {X Y Z : C} (f : X ⟶ Z) (g : X ⟶ Y)
[has_pushout f g] [has_pullback f.op g.op] :
pushout.inr ≫ (pushout_iso_unop_pullback f g).hom =
(pullback.snd : pullback f.op g.op ⟶ _).unop :=
(is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _).trans (by simp)
@[simp]
lemma pushout_iso_unop_pullback_inv_fst {X Y Z : C} (f : X ⟶ Z) (g : X ⟶ Y)
[has_pushout f g] [has_pullback f.op g.op] :
(pushout_iso_unop_pullback f g).inv.op ≫ pullback.fst = pushout.inl.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [← pushout_iso_unop_pullback_inl_hom, category.assoc, iso.hom_inv_id, category.comp_id],
end
@[simp]
lemma pushout_iso_unop_pullback_inv_snd {X Y Z : C} (f : X ⟶ Z) (g : X ⟶ Y)
[has_pushout f g] [has_pullback f.op g.op] :
(pushout_iso_unop_pullback f g).inv.op ≫ pullback.snd = pushout.inr.op :=
begin
apply quiver.hom.unop_inj,
dsimp,
rw [← pushout_iso_unop_pullback_inr_hom, category.assoc, iso.hom_inv_id, category.comp_id],
end
end pushout
end category_theory.limits
|
333f640917fe08ec85fb465fa8b143ded7f2cea4 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /data/equiv.lean | f75ba67413b883a1dc1641b25cb920c3b671b80a | [
"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 | 28,649 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import data.prod data.nat.pairing logic.function tactic data.set.lattice
import algebra.group
open function
universes u v w
variables {α : Sort u} {β : Sort v} {γ : Sort w}
namespace subtype
/-- Restriction of a function to a function on subtypes. -/
def map {p : α → Prop} {q : β → Prop} (f : α → β) (h : ∀a, p a → q (f a)) :
subtype p → subtype q
| ⟨v, hv⟩ := ⟨f v, h v hv⟩
theorem map_comp {p : α → Prop} {q : β → Prop} {r : γ → Prop} {x : subtype p}
(f : α → β) (h : ∀a, p a → q (f a)) (g : β → γ) (l : ∀a, q a → r (g a)) :
map g l (map f h x) = map (g ∘ f) (assume a ha, l (f a) $ h a ha) x :=
by cases x with v h; refl
theorem map_id {p : α → Prop} {h : ∀a, p a → p (id a)} : map (@id α) h = id :=
funext $ assume ⟨v, h⟩, rfl
end subtype
namespace function
theorem left_inverse.f_g_eq_id {f : α → β} {g : β → α} (h : left_inverse f g) : f ∘ g = id :=
funext $ h
theorem right_inverse.g_f_eq_id {f : α → β} {g : β → α} (h : right_inverse f g) : g ∘ f = id :=
funext $ h
theorem left_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : left_inverse f g) (hh : left_inverse h i) : left_inverse (h ∘ f) (g ∘ i) :=
assume a, show h (f (g (i a))) = a, by rw [hf (i a), hh a]
theorem right_inverse.comp {f : α → β} {g : β → α} {h : β → γ} {i : γ → β}
(hf : right_inverse f g) (hh : right_inverse h i) : right_inverse (h ∘ f) (g ∘ i) :=
left_inverse.comp hh hf
end function
/-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/
structure equiv (α : Sort*) (β : Sort*) :=
(to_fun : α → β)
(inv_fun : β → α)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
/-- `perm α` is the type of bijections from `α` to itself. -/
@[reducible] def perm (α : Sort*) := equiv α α
infix ` ≃ `:50 := equiv
instance : has_coe_to_fun (α ≃ β) :=
⟨_, to_fun⟩
@[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f :=
rfl
theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h :=
have f₁ = f₂, from h,
have g₁ = g₂, from funext $ assume x,
have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm,
have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this,
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this,
by simp *
lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g :=
eq_of_to_fun_eq (funext H)
@[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩
@[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩
@[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun,
e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩
protected theorem bijective : ∀ f : α ≃ β, bijective f
| ⟨f, g, h₁, h₂⟩ :=
⟨injective_of_left_inverse h₁, surjective_of_has_right_inverse ⟨_, h₂⟩⟩
protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α
| ⟨H⟩ := ⟨λ a b, e.bijective.1 (H _ _)⟩
protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α
| a b := decidable_of_iff _ e.bijective.1.eq_iff
protected def cast {α β : Sort*} (h : α = β) : α ≃ β :=
⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩
@[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g :=
rfl
@[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl
@[simp] theorem trans_apply : ∀ (f : α ≃ β) (g : β ≃ γ) (a : α), (f.trans g) a = g (f a)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ a := rfl
@[simp] theorem apply_inverse_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁
@[simp] theorem inverse_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x
| ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁
@[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y
| ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff
@[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl
theorem apply_eq_iff_eq_inverse_apply : ∀ (f : α ≃ β) (x : α) (y : β), f x = y ↔ x = f.symm y
| ⟨f₁, g₁, l₁, r₁⟩ x y := by simp [equiv.symm];
show f₁ x = y ↔ x = g₁ y; from
⟨λ e : f₁ x = y, e ▸ (l₁ x).symm,
λ e : x = g₁ y, e.symm ▸ r₁ y⟩
/- The group of permutations (self-equivalences) of a type `α` -/
instance perm_group {α : Type u} : group (perm α) :=
begin
refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..};
intros; apply equiv.ext; try { apply trans_apply },
apply inverse_apply_apply
end
def equiv_empty (h : α → false) : α ≃ empty :=
⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩
def false_equiv_empty : false ≃ empty :=
equiv_empty _root_.id
def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty :=
⟨assume a, (h ⟨a⟩).elim, assume e, e.rec_on _, assume a, (h ⟨a⟩).elim, assume e, e.rec_on _⟩
protected def ulift {α : Type u} : ulift α ≃ α :=
⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩
protected def plift : plift α ≃ α :=
⟨plift.down, plift.up, plift.up_down, plift.down_up⟩
@[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)),
λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)),
λ h, by funext a; dsimp; rw [l₁, l₂],
λ h, by funext a; dsimp; rw [r₁, r₂]⟩
def punit_equiv_punit : punit.{v} ≃ punit.{w} :=
⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩
section
@[simp] def arrow_unit_equiv_unit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} :=
⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩
@[simp] def unit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α :=
⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩
@[simp] def empty_arrow_equiv_unit (α : Sort*) : (empty → α) ≃ punit.{u} :=
⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩
@[simp] def false_arrow_equiv_unit (α : Sort*) : (false → α) ≃ punit.{u} :=
calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _)
... ≃ punit : empty_arrow_equiv_unit _
def arrow_empty_unit {α : Sort*} : (empty → α) ≃ punit.{u} :=
⟨λf, punit.star, λu e, e.rec_on _, assume f, funext $ assume e, e.rec_on _, assume u, punit_eq _ _⟩
end
@[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ × β₁) ≃ (α₂ × β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ ⟨a, b⟩, (f₁ a, f₂ b), λ ⟨a, b⟩, (g₁ a, g₂ b),
λ ⟨a, b⟩, show (g₁ (f₁ a), g₂ (f₂ b)) = (a, b), by rw [l₁ a, l₂ b],
λ ⟨a, b⟩, show (f₁ (g₁ a), f₂ (g₂ b)) = (a, b), by rw [r₁ a, r₂ b]⟩
@[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) :
prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) :=
by cases e₁; cases e₂; refl
@[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) :=
⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩
@[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) :=
⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩
@[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) :
prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl
section
@[simp] def prod_unit (α : Sort*) : (α × punit.{u+1}) ≃ α :=
⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩
@[simp] theorem prod_unit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_unit α a = a.1 := rfl
@[simp] def unit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α :=
calc (punit × α) ≃ (α × punit) : prod_comm _ _
... ≃ α : prod_unit _
@[simp] theorem unit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : unit_prod α a = a.2 := rfl
@[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty :=
equiv_empty (λ ⟨_, e⟩, e.rec _)
@[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty :=
equiv_empty (λ ⟨e, _⟩, e.rec _)
end
section
open sum
def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) :=
⟨λ s, psum.cases_on s inl inr,
λ s, sum.cases_on s psum.inl psum.inr,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂)
| ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ :=
⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end,
λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end,
λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end,
λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩
@[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) :
sum_congr e₁ e₂ (inl a) = inl (e₁ a) :=
by cases e₁; cases e₂; refl
@[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) :
sum_congr e₁ e₂ (inr b) = inr (e₂ b) :=
by cases e₁; cases e₂; refl
def bool_equiv_unit_sum_unit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) :=
⟨λ b, cond b (inl punit.star) (inr punit.star),
λ s, sum.rec_on s (λ_, tt) (λ_, ff),
λ b, by cases b; refl,
λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩
noncomputable def Prop_equiv_bool : Prop ≃ bool :=
⟨λ p, @to_bool p (classical.prop_decidable _),
λ b, b, λ p, by simp, λ b, by simp⟩
@[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) :=
⟨λ s, match s with inl a := inr a | inr b := inl b end,
λ s, match s with inl b := inr b | inr a := inl a end,
λ s, by cases s; refl,
λ s, by cases s; refl⟩
@[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) :=
⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end,
λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end,
λ s, by rcases s with ⟨_ | _⟩ | _; refl,
λ s, by rcases s with _ | _ | _; refl⟩
@[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl
@[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl
@[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl
@[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α :=
⟨λ s, match s with inl a := a | inr e := empty.rec _ e end,
inl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl,
λ a, rfl⟩
@[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α :=
(sum_comm _ _).trans $ sum_empty _
@[simp] def option_equiv_sum_unit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) :=
⟨λ o, match o with none := inr punit.star | some a := inl a end,
λ s, match s with inr _ := none | inl a := some a end,
λ o, by cases o; refl,
λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩
def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) :=
⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end,
λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end,
λ s, by cases s; refl,
λ s, by rcases s with ⟨_|_, _⟩; refl⟩
def equiv_fib {α β : Type*} (f : α → β) :
α ≃ Σ y : β, {x // f x = y} :=
⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩
end
section
def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) :=
⟨λ H a, F a (H a), λ H a, (F a).symm (H a),
λ H, funext $ by simp, λ H, funext $ by simp⟩
end
section
def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ :=
⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ inverse_apply_apply (F a) b,
λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_inverse_apply (F a) b⟩
def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a)
| ⟨f, g, l, r⟩ :=
⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩,
λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a),
@sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with
| _, rfl := rfl end,
λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with
| _, rfl := rfl end⟩
def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) :=
⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩
def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) :=
(sigma_congr_right F).trans (sigma_equiv_prod α β)
end
section
def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) :=
⟨λ f, (λ c, (f c).1, λ c, (f c).2),
λ p c, (p.1 c, p.2 c),
λ f, funext $ λ c, prod.mk.eta,
λ p, by cases p; refl⟩
def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) :=
⟨λ f, λ p, f p.1 p.2,
λ f, λ a b, f (a, b),
λ f, rfl,
λ f, by funext p; cases p; refl⟩
open sum
def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) :=
⟨λ f, (f ∘ inl, f ∘ inr),
λ p s, sum.rec_on s p.1 p.2,
λ f, by funext s; cases s; refl,
λ p, by cases p; refl⟩
def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) :=
⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end,
λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end,
λ p, by rcases p with ⟨_ | _, _⟩; refl,
λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩
@[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) :
sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl
@[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) :
sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl
def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) :=
calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _
... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _
... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _)
@[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) :
prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl
@[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) :
prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl
def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) :=
calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_unit_sum_unit (equiv.refl _)
... ≃ (α × (unit ⊕ unit)) : prod_comm _ _
... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _
... ≃ (α ⊕ α) : sum_congr (prod_unit _) (prod_unit _)
end
section
open sum nat
def nat_equiv_nat_sum_unit : ℕ ≃ (ℕ ⊕ punit.{u+1}) :=
⟨λ n, match n with zero := inr punit.star | succ a := inl a end,
λ s, match s with inl n := succ n | inr punit.star := zero end,
λ n, begin cases n, repeat { refl } end,
λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩
@[simp] def nat_sum_unit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ :=
nat_equiv_nat_sum_unit.symm
@[simp] def nat_prod_nat_equiv_nat : (ℕ × ℕ) ≃ ℕ :=
⟨λ p, nat.mkpair p.1 p.2,
nat.unpair,
λ p, begin cases p, apply nat.unpair_mkpair end,
nat.mkpair_unpair⟩
@[simp] def nat_sum_bool_equiv_nat : (ℕ ⊕ bool) ≃ ℕ :=
calc (ℕ ⊕ bool) ≃ (ℕ ⊕ (unit ⊕ unit)) : sum_congr (equiv.refl _) bool_equiv_unit_sum_unit
... ≃ ((ℕ ⊕ unit) ⊕ unit) : (sum_assoc ℕ unit unit).symm
... ≃ (ℕ ⊕ unit) : sum_congr nat_sum_unit_equiv_nat (equiv.refl _)
... ≃ ℕ : nat_sum_unit_equiv_nat
@[simp] def bool_prod_nat_equiv_nat : (bool × ℕ) ≃ ℕ :=
⟨λ ⟨b, n⟩, bit b n, bodd_div2,
λ ⟨b, n⟩, by simp [bool_prod_nat_equiv_nat._match_1, bodd_bit, div2_bit],
λ n, by simp [bool_prod_nat_equiv_nat._match_1, bit_decomp]⟩
@[simp] def nat_sum_nat_equiv_nat : (ℕ ⊕ ℕ) ≃ ℕ :=
(bool_prod_equiv_sum ℕ).symm.trans bool_prod_nat_equiv_nat
def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) :=
by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl}
def int_equiv_nat : ℤ ≃ ℕ :=
int_equiv_nat_sum_nat.trans nat_sum_nat_equiv_nat
def prod_equiv_of_equiv_nat {α : Sort*} (e : α ≃ ℕ) : (α × α) ≃ α :=
calc (α × α) ≃ (ℕ × ℕ) : prod_congr e e
... ≃ ℕ : nat_prod_nat_equiv_nat
... ≃ α : e.symm
end
def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β
| ⟨f, g, l, r⟩ :=
by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩;
simp [id_of_left_inverse l, id_of_right_inverse r]
section
open nat list
private def list.to_nat : list ℕ → ℕ
| [] := 0
| (a::l) := succ (mkpair l.to_nat a)
private def list.of_nat : ℕ → list ℕ
| 0 := []
| (succ v) := match unpair v, unpair_le v with
| (v₂, v₁), h :=
have v₂ < succ v, from lt_succ_of_le h,
v₁ :: list.of_nat v₂
end
private theorem list.of_nat_to_nat : ∀ l : list ℕ, list.of_nat (list.to_nat l) = l
| [] := rfl
| (a::l) := by simp [list.to_nat, list.of_nat, unpair_mkpair, *]
private theorem list.to_nat_of_nat : ∀ n : ℕ, list.to_nat (list.of_nat n) = n
| 0 := rfl
| (succ v) := begin
cases e : unpair v with v₁ v₂,
have := lt_succ_of_le (unpair_le v),
have IH := have v₁ < succ v, by rwa e at this, list.to_nat_of_nat v₁,
simp [list.of_nat, e, list.to_nat, IH, mkpair_unpair' e]
end
def list_nat_equiv_nat : list ℕ ≃ ℕ :=
⟨list.to_nat, list.of_nat, list.of_nat_to_nat, list.to_nat_of_nat⟩
def list_equiv_self_of_equiv_nat {α : Type} (e : α ≃ ℕ) : list α ≃ α :=
calc list α ≃ list ℕ : list_equiv_of_equiv e
... ≃ ℕ : list_nat_equiv_nat
... ≃ α : e.symm
end
section
def decidable_eq_of_equiv [h : decidable_eq α] : α ≃ β → decidable_eq β
| ⟨f, g, l, r⟩ b₁ b₂ :=
match h (g b₁) (g b₂) with
| (is_true he) := is_true $ have f (g b₁) = f (g b₂), from congr_arg f he, by rwa [r, r] at this
| (is_false hn) := is_false $ λeq, hn.elim $ by rw [eq]
end
end
def inhabited_of_equiv [inhabited α] : α ≃ β → inhabited β
| ⟨f, g, l, r⟩ := ⟨f (default _)⟩
section
open subtype
def subtype_equiv_of_subtype {p : α → Prop} : Π (e : α ≃ β), {a : α // p a} ≃ {b : β // p (e.symm b)}
| ⟨f, g, l, r⟩ :=
⟨subtype.map f $ assume a ha, show p (g (f a)), by rwa [l],
subtype.map g $ assume a ha, ha,
assume p, by simp [map_comp, l.f_g_eq_id]; rw [map_id]; refl,
assume p, by simp [map_comp, r.f_g_eq_id]; rw [map_id]; refl⟩
def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) :
subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } :=
⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩,
λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩,
assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩
end
namespace set
open set
protected def univ (α) : @univ α ≃ α :=
⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩
protected def empty (α) : (∅ : set α) ≃ empty :=
equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h
protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) :
(s ∪ t : set α) ≃ (s ⊕ t) :=
⟨λ ⟨x, h⟩, if hs : x ∈ s then sum.inl ⟨_, hs⟩ else sum.inr ⟨_, h.resolve_left hs⟩,
λ o, match o with
| (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩
| (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩
end,
λ ⟨x, h'⟩, by by_cases x ∈ s; simp [union._match_1, union._match_2, h]; congr,
λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union._match_1, union._match_2, h];
simp [show x ∉ s, from λ h', eq_empty_iff_forall_not_mem.1 H _ ⟨h', h⟩]⟩
protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} :=
⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩,
λ ⟨x, h⟩, by simp at h; subst x,
λ ⟨⟩, rfl⟩
protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) :
(insert a s : set α) ≃ (s ⊕ punit.{u+1}) :=
by rw ← union_singleton; exact
(set.union $ inter_singleton_eq_empty.2 H).trans
(sum_congr (equiv.refl _) (set.singleton _))
protected def sum_compl {α} (s : set α) [decidable_pred s] :
(s ⊕ (-s : set α)) ≃ α :=
(set.union (inter_compl_self _)).symm.trans
(by rw union_compl_self; exact set.univ _)
protected def prod {α β} (s : set α) (t : set β) :
(s.prod t) ≃ (s × t) :=
⟨λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩,
λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl,
λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩
protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) :
s ≃ (f '' s) :=
⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩,
λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩,
λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2),
λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩
@[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) :
set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl
protected noncomputable def range {α β} (f : α → β) (H : injective f) :
α ≃ range f :=
(set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ)
@[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) :
set.range f H a = ⟨f a, set.mem_range_self _⟩ :=
by dunfold equiv.set.range equiv.set.univ;
simp [set_coe_cast, -image_univ, image_univ.symm]
end set
noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β :=
begin
have hg := bijective_comp equiv.plift.symm.bijective
(bijective_comp hf equiv.plift.bijective),
refine equiv.plift.symm.trans (equiv.trans _ equiv.plift),
exact (set.range _ hg.1).trans
((equiv.cast (by rw set.range_iff_surjective.2 hg.2)).trans (set.univ _))
end
@[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f :=
begin
funext a, dunfold of_bijective equiv.set.univ,
have hg := bijective_comp equiv.plift.symm.bijective
(bijective_comp hf equiv.plift.bijective),
simp [set.set_coe_cast, (∘), set.range_iff_surjective.2 hg.2],
end
section
open set
set_option eqn_compiler.zeta true
noncomputable def set.bUnion_eq_sigma_of_disjoint {α β} {s : set α} {t : α → set β}
(h : pairwise_on s (disjoint on t)) : (⋃i∈s, t i) ≃ (Σi:s, t i.val) :=
let f : (Σi:s, t i.val) → (⋃i∈s, t i) := λ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨b, mem_bUnion ha hb⟩ in
have injective f,
from assume ⟨⟨a₁, ha₁⟩, ⟨b₁, hb₁⟩⟩ ⟨⟨a₂, ha₂⟩, ⟨b₂, hb₂⟩⟩ eq,
have b_eq : b₁ = b₂, from congr_arg subtype.val eq,
have a_eq : a₁ = a₂, from classical.by_contradiction $ assume ne,
have b₁ ∈ t a₁ ∩ t a₂, from ⟨hb₁, b_eq.symm ▸ hb₂⟩,
have t a₁ ∩ t a₂ ≠ ∅, from ne_empty_of_mem this,
this $ h _ ha₁ _ ha₂ ne,
sigma.eq (subtype.eq a_eq) (subtype.eq $ by subst b_eq; subst a_eq),
have surjective f,
from assume ⟨b, hb⟩,
have ∃a∈s, b ∈ t a, by simpa using hb,
let ⟨a, ha, hb⟩ := this in ⟨⟨⟨a, ha⟩, ⟨b, hb⟩⟩, rfl⟩,
(equiv.of_bijective ⟨‹injective f›, ‹surjective f›⟩).symm
end
section swap
variable [decidable_eq α]
open decidable
def swap_core (a b r : α) : α :=
if r = a then b
else if r = b then a
else r
theorem swap_core_self (r a : α) : swap_core a a r = r :=
by by_cases r = a; simp [swap_core, *]
theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r :=
begin
by_cases hb : r = b,
{ by_cases ha : r = a,
{ simp [hb.symm, ha.symm, swap_core_self] },
{ have : b ≠ a, by rwa [hb] at ha,
simp [swap_core, *] } },
{ by_cases ha : r = a,
{ have : b ≠ a, begin rw [ha] at hb, exact ne.symm hb end,
simp [swap_core, *] },
simp [swap_core, *] }
end
theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r :=
begin
by_cases hb : r = b,
{ by_cases ha : r = a,
{ simp [hb.symm, ha.symm, swap_core_self] },
{ have : b ≠ a, by rwa [hb] at ha,
simp [swap_core, *] } },
{ by_cases ha : r = a,
{ have : a ≠ b, by rwa [ha] at hb,
simp [swap_core, *] },
simp [swap_core, *] }
end
/-- `swap a b` is the permutation that swaps `a` and `b` and
leaves other values as is. -/
def swap (a b : α) : perm α :=
⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩
theorem swap_self (a : α) : swap a a = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a
theorem swap_comm (a b : α) : swap a b = swap b a :=
eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _
theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x :=
rfl
theorem swap_apply_left (a b : α) : swap a b a = b :=
if_pos rfl
theorem swap_apply_right (a b : α) : swap a b b = a :=
by by_cases b = a; simp [swap_apply_def, *]
theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x :=
by simp [swap_apply_def] {contextual := tt}
theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ :=
eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _
theorem swap_comp_apply {a b x : α} (π : perm α) :
π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x :=
by cases π; refl
end swap
end equiv
instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton
instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton
instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq
instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq
|
99f500e5ed2fd941a3e3e280f1d79ae3269d28d9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/Lake/Build/Job.lean | 31eca9a5eacb320e173d0e5ddcece20a7a469a2b | [
"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,502 | lean | /-
Copyright (c) 2022 Mac Malone. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mac Malone
-/
import Lake.Util.Async
import Lake.Build.Trace
import Lake.Build.Context
open System
namespace Lake
/-- A Lake job. -/
abbrev Job α := OptionIOTask α
/-- The monad of Lake jobs. -/
abbrev JobM := BuildM
/-- The monad of a finished Lake job. -/
abbrev ResultM := OptionIO
namespace Job
@[inline] def nil : Job Unit :=
pure ()
@[inline] protected def async (act : JobM α) : SchedulerM (Job α) :=
async act
@[inline] protected def await (self : Job α) : ResultM α :=
await self
@[inline] protected def bindSync
(self : Job α) (f : α → JobM β) (prio := Task.Priority.default) : SchedulerM (Job β) :=
bindSync prio self f
@[inline] protected def bindAsync
(self : Job α) (f : α → SchedulerM (Job β)) : SchedulerM (Job β) :=
bindAsync self f
end Job
/-- A Lake build job. -/
abbrev BuildJob α := Job (α × BuildTrace)
namespace BuildJob
@[inline] def mk (job : Job (α × BuildTrace)) : BuildJob α :=
job
@[inline] def ofJob (self : Job BuildTrace) : BuildJob Unit :=
mk <| ((), ·) <$> self
@[inline] def toJob (self : BuildJob α) : Job (α × BuildTrace) :=
self
@[inline] def nil : BuildJob Unit :=
mk <| pure ((), nilTrace)
@[inline] protected def pure (a : α) : BuildJob α :=
mk <| pure (a, nilTrace)
instance : Pure BuildJob := ⟨BuildJob.pure⟩
@[inline] protected def map (f : α → β) (self : BuildJob α) : BuildJob β :=
mk <| (fun (a,t) => (f a,t)) <$> self.toJob
instance : Functor BuildJob where
map := BuildJob.map
@[inline] def mapWithTrace (f : α → BuildTrace → β × BuildTrace) (self : BuildJob α) : BuildJob β :=
mk <| (fun (a,t) => f a t) <$> self.toJob
@[inline] protected def bindSync
(self : BuildJob α) (f : α → BuildTrace → JobM β)
(prio : Task.Priority := .default) : SchedulerM (Job β) :=
self.toJob.bindSync (prio := prio) fun (a, t) => f a t
@[inline] protected def bindAsync
(self : BuildJob α) (f : α → BuildTrace → SchedulerM (Job β)) : SchedulerM (Job β) :=
self.toJob.bindAsync fun (a, t) => f a t
@[inline] protected def await (self : BuildJob α) : ResultM α :=
(·.1) <$> await self.toJob
instance : Await BuildJob ResultM := ⟨BuildJob.await⟩
@[inline] def materialize (self : BuildJob α) : ResultM Unit :=
discard <| await self.toJob
def mix (t1 : BuildJob α) (t2 : BuildJob β) : BaseIO (BuildJob Unit) :=
mk <$> seqWithAsync (fun (_,t) (_,t') => ((), mixTrace t t')) t1.toJob t2.toJob
def mixList (jobs : List (BuildJob α)) : BaseIO (BuildJob Unit) := ofJob <$> do
jobs.foldrM (init := pure nilTrace) fun j a =>
seqWithAsync (fun (_,t') t => mixTrace t t') j.toJob a
def mixArray (jobs : Array (BuildJob α)) : BaseIO (BuildJob Unit) := ofJob <$> do
jobs.foldlM (init := pure nilTrace) fun a j =>
seqWithAsync (fun t (_,t') => mixTrace t t') a j.toJob
protected def seqWithAsync
(f : α → β → γ) (t1 : BuildJob α) (t2 : BuildJob β) : BaseIO (BuildJob γ) :=
mk <$> seqWithAsync (fun (a,t) (b,t') => (f a b, mixTrace t t')) t1.toJob t2.toJob
instance : SeqWithAsync BaseIO BuildJob := ⟨BuildJob.seqWithAsync⟩
def collectList (jobs : List (BuildJob α)) : BaseIO (BuildJob (List α)) :=
jobs.foldrM (seqWithAsync List.cons) (pure [])
def collectArray (jobs : Array (BuildJob α)) : BaseIO (BuildJob (Array α)) :=
jobs.foldlM (seqWithAsync Array.push) (pure #[])
|
df3467c216365f6ffbf2c3efc64417043b8cdb2f | 200b12985a863d01fbbde6abfc9326bb82424a8b | /src/propLogic/Ex015.lean | 65649a61a6845bc00113b3f83b021cb4c901a098 | [] | no_license | SvenWille/LeanLogicExercises | 38eacd36733ac48e5a7aacf863c681c9a9a48271 | 2dbc920feadd63bbc50f87e69646c0081db26eba | refs/heads/master | 1,629,676,667,365 | 1,512,161,459,000 | 1,512,161,459,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 162 | lean |
theorem Ex015 (a b : Prop):(a → b) → a → a ∧ b :=
assume H : (a → b),
assume H1 : a,
have A : b , from H H1,
show a ∧ b, from and.intro H1 A
|
41d516b78d8e192044b6cc916248702152e6bf0e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/number_theory/bertrand.lean | 3c2140e3ad2123fc27c0ecfbd9b621939887a8fe | [
"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 | 11,266 | 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 (zero_lt_two' ℝ) 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 (zero_lt_two' ℕ) 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
|
94f06d85181622a23d4712bbd33ead24229b0c76 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/module/submodule/pointwise.lean | bc4be0638ac439a76cdf181382b61da730f59320 | [
"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,978 | lean | /-
Copyright (c) 2021 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import group_theory.subgroup.pointwise
import linear_algebra.span
/-! # Pointwise instances on `submodule`s
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file provides:
* `submodule.has_pointwise_neg`
and the actions
* `submodule.pointwise_distrib_mul_action`
* `submodule.pointwise_mul_action_with_zero`
which matches the action of `mul_action_set`.
These actions are available in the `pointwise` locale.
## Implementation notes
Most of the lemmas in this file are direct copies of lemmas from
`group_theory/submonoid/pointwise.lean`.
-/
variables {α : Type*} {R : Type*} {M : Type*}
open_locale pointwise
namespace submodule
section neg
section semiring
variables [semiring R] [add_comm_group M] [module R M]
/-- The submodule with every element negated. Note if `R` is a ring and not just a semiring, this
is a no-op, as shown by `submodule.neg_eq_self`.
Recall that When `R` is the semiring corresponding to the nonnegative elements of `R'`,
`submodule R' M` is the type of cones of `M`. This instance reflects such cones about `0`.
This is available as an instance in the `pointwise` locale. -/
protected def has_pointwise_neg : has_neg (submodule R M) :=
{ neg := λ p,
{ carrier := -(p : set M),
smul_mem' := λ r m hm, set.mem_neg.2 $ smul_neg r m ▸ p.smul_mem r $ set.mem_neg.1 hm,
..(- p.to_add_submonoid) } }
localized "attribute [instance] submodule.has_pointwise_neg" in pointwise
open_locale pointwise
@[simp] lemma coe_set_neg (S : submodule R M) : ↑(-S) = -(S : set M) := rfl
@[simp] lemma neg_to_add_submonoid (S : submodule R M) :
(-S).to_add_submonoid = -S.to_add_submonoid := rfl
@[simp] lemma mem_neg {g : M} {S : submodule R M} : g ∈ -S ↔ -g ∈ S := iff.rfl
/-- `submodule.has_pointwise_neg` is involutive.
This is available as an instance in the `pointwise` locale. -/
protected def has_involutive_pointwise_neg : has_involutive_neg (submodule R M) :=
{ neg := has_neg.neg,
neg_neg := λ S, set_like.coe_injective $ neg_neg _ }
localized "attribute [instance] submodule.has_involutive_pointwise_neg" in pointwise
@[simp] lemma neg_le_neg (S T : submodule R M) : -S ≤ -T ↔ S ≤ T :=
set_like.coe_subset_coe.symm.trans set.neg_subset_neg
lemma neg_le (S T : submodule R M) : -S ≤ T ↔ S ≤ -T :=
set_like.coe_subset_coe.symm.trans set.neg_subset
/-- `submodule.has_pointwise_neg` as an order isomorphism. -/
def neg_order_iso : submodule R M ≃o submodule R M :=
{ to_equiv := equiv.neg _,
map_rel_iff' := neg_le_neg }
lemma closure_neg (s : set M) : span R (-s) = -(span R s) :=
begin
apply le_antisymm,
{ rw [span_le, coe_set_neg, ←set.neg_subset, neg_neg],
exact subset_span },
{ rw [neg_le, span_le, coe_set_neg, ←set.neg_subset],
exact subset_span }
end
@[simp]
lemma neg_inf (S T : submodule R M) : -(S ⊓ T) = (-S) ⊓ (-T) :=
set_like.coe_injective set.inter_neg
@[simp]
lemma neg_sup (S T : submodule R M) : -(S ⊔ T) = (-S) ⊔ (-T) :=
(neg_order_iso : submodule R M ≃o submodule R M).map_sup S T
@[simp]
lemma neg_bot : -(⊥ : submodule R M) = ⊥ :=
set_like.coe_injective $ (set.neg_singleton 0).trans $ congr_arg _ neg_zero
@[simp]
lemma neg_top : -(⊤ : submodule R M) = ⊤ :=
set_like.coe_injective $ set.neg_univ
@[simp]
lemma neg_infi {ι : Sort*} (S : ι → submodule R M) : -(⨅ i, S i) = ⨅ i, -S i :=
(neg_order_iso : submodule R M ≃o submodule R M).map_infi _
@[simp]
lemma neg_supr {ι : Sort*} (S : ι → submodule R M) : -(⨆ i, S i) = ⨆ i, -(S i) :=
(neg_order_iso : submodule R M ≃o submodule R M).map_supr _
end semiring
open_locale pointwise
@[simp] lemma neg_eq_self [ring R] [add_comm_group M] [module R M] (p : submodule R M) : -p = p :=
ext $ λ _, p.neg_mem_iff
end neg
variables [semiring R] [add_comm_monoid M] [module R M]
instance pointwise_add_comm_monoid : add_comm_monoid (submodule R M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm }
@[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl
@[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl
instance : canonically_ordered_add_monoid (submodule R M) :=
{ zero := 0,
bot := ⊥,
add := (+),
add_le_add_left := λ a b, sup_le_sup_left,
exists_add_of_le := λ a b h, ⟨b, (sup_eq_right.2 h).symm⟩,
le_self_add := λ a b, le_sup_left,
..submodule.pointwise_add_comm_monoid,
..submodule.complete_lattice }
section
variables [monoid α] [distrib_mul_action α M] [smul_comm_class α R M]
/-- The action on a submodule corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale. -/
protected def pointwise_distrib_mul_action : distrib_mul_action α (submodule R M) :=
{ smul := λ a S, S.map (distrib_mul_action.to_linear_map R M a : M →ₗ[R] M),
one_smul := λ S,
(congr_arg (λ f : module.End R M, S.map f) (linear_map.ext $ by exact one_smul α)).trans
S.map_id,
mul_smul := λ a₁ a₂ S,
(congr_arg (λ f : module.End R M, S.map f) (linear_map.ext $ by exact mul_smul _ _)).trans
(S.map_comp _ _),
smul_zero := λ a, map_bot _,
smul_add := λ a S₁ S₂, map_sup _ _ _ }
localized "attribute [instance] submodule.pointwise_distrib_mul_action" in pointwise
open_locale pointwise
@[simp] lemma coe_pointwise_smul (a : α) (S : submodule R M) : ↑(a • S) = a • (S : set M) := rfl
@[simp] lemma pointwise_smul_to_add_submonoid (a : α) (S : submodule R M) :
(a • S).to_add_submonoid = a • S.to_add_submonoid := rfl
@[simp] lemma pointwise_smul_to_add_subgroup {R M : Type*}
[ring R] [add_comm_group M] [distrib_mul_action α M] [module R M] [smul_comm_class α R M]
(a : α) (S : submodule R M) :
(a • S).to_add_subgroup = a • S.to_add_subgroup := rfl
lemma smul_mem_pointwise_smul (m : M) (a : α) (S : submodule R M) : m ∈ S → a • m ∈ a • S :=
(set.smul_mem_smul_set : _ → _ ∈ a • (S : set M))
/-- See also `submodule.smul_bot`. -/
@[simp] lemma smul_bot' (a : α) : a • (⊥ : submodule R M) = ⊥ := map_bot _
/-- See also `submodule.smul_sup`. -/
lemma smul_sup' (a : α) (S T : submodule R M) : a • (S ⊔ T) = a • S ⊔ a • T := map_sup _ _ _
lemma smul_span (a : α) (s : set M) : a • span R s = span R (a • s) := map_span _ _
lemma span_smul (a : α) (s : set M) : span R (a • s) = a • span R s := eq.symm (span_image _).symm
instance pointwise_central_scalar [distrib_mul_action αᵐᵒᵖ M] [smul_comm_class αᵐᵒᵖ R M]
[is_central_scalar α M] :
is_central_scalar α (submodule R M) :=
⟨λ a S, congr_arg (λ f : module.End R M, S.map f) $ linear_map.ext $ by exact op_smul_eq_smul _⟩
@[simp] lemma smul_le_self_of_tower {α : Type*}
[semiring α] [module α R] [module α M] [smul_comm_class α R M] [is_scalar_tower α R M]
(a : α) (S : submodule R M) : a • S ≤ S :=
begin
rintro y ⟨x, hx, rfl⟩,
exact smul_of_tower_mem _ a hx,
end
end
section
variables [semiring α] [module α M] [smul_comm_class α R M]
/-- The action on a submodule corresponding to applying the action to every element.
This is available as an instance in the `pointwise` locale.
This is a stronger version of `submodule.pointwise_distrib_mul_action`. Note that `add_smul` does
not hold so this cannot be stated as a `module`. -/
protected def pointwise_mul_action_with_zero : mul_action_with_zero α (submodule R M) :=
{ zero_smul := λ S,
(congr_arg (λ f : M →ₗ[R] M, S.map f) (linear_map.ext $ by exact zero_smul α)).trans S.map_zero,
.. submodule.pointwise_distrib_mul_action }
localized "attribute [instance] submodule.pointwise_mul_action_with_zero" in pointwise
end
end submodule
|
eaee1f5ee3168e811b1bff09332b1120fdf2f027 | a047a4718edfa935d17231e9e6ecec8c7b701e05 | /src/tactic/group.lean | 4cd40b3d51651a4f98ed12c13be907b049dd6ae7 | [
"Apache-2.0"
] | permissive | utensil-contrib/mathlib | bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767 | b91909e77e219098a2f8cc031f89d595fe274bd2 | refs/heads/master | 1,668,048,976,965 | 1,592,442,701,000 | 1,592,442,701,000 | 273,197,855 | 0 | 0 | null | 1,592,472,812,000 | 1,592,472,811,000 | null | UTF-8 | Lean | false | false | 3,634 | lean | /-
Copyright (c) 2020. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Patrick Massot
-/
import tactic.ring
import tactic.doc_commands
/-!
# `group`
Normalizes expressions in the language of groups. The basic idea is to use the simplifier
to put everything into a product of group powers (`gpow` which takes a group element and an
integer), then simplify the exponents using the `ring` tactic. The process needs to be repeated
since `ring` can normalize an exponent to zero, leading to a factor that can be removed
before collecting exponents again. The simplifier step also uses some extra lemmas to avoid
some `ring` invocations.
## Tags
group_theory
-/
-- The next four lemmas are not general purpose lemmas, they are intended for use only by
-- the `group` tactic.
lemma tactic.group.gpow_trick {G : Type*} [group G] (a b : G) (n m : ℤ) : a*b^n*b^m = a*b^(n+m) :=
by rw [mul_assoc, ← gpow_add]
lemma tactic.group.gpow_trick_one {G : Type*} [group G] (a b : G) (m : ℤ) : a*b*b^m = a*b^(m+1) :=
by rw [mul_assoc, mul_self_gpow]
lemma tactic.group.gpow_trick_one' {G : Type*} [group G] (a b : G) (n : ℤ) : a*b^n*b = a*b^(n+1) :=
by rw [mul_assoc, mul_gpow_self]
lemma tactic.group.gpow_trick_sub {G : Type*} [group G] (a b : G) (n m : ℤ) : a*b^n*b^(-m) = a*b^(n-m) :=
by rw [mul_assoc, ← gpow_add] ; refl
namespace tactic
open tactic.simp_arg_type tactic.interactive interactive tactic.group.
/-- Auxilliary tactic for the `group` tactic. Calls the simplifier only. -/
meta def aux_group₁ (locat : loc) : tactic unit :=
simp_core {} skip tt [
expr ``(mul_one),
expr ``(one_mul),
expr ``(sub_self),
expr ``(add_neg_self),
expr ``(neg_add_self),
expr ``(neg_neg),
expr ``(nat.sub_self),
expr ``(int.coe_nat_add),
expr ``(int.coe_nat_mul),
expr ``(int.coe_nat_zero),
expr ``(int.coe_nat_one),
expr ``(int.coe_nat_bit0),
expr ``(int.coe_nat_bit1),
expr ``(int.mul_neg_eq_neg_mul_symm),
expr ``(int.neg_mul_eq_neg_mul_symm),
symm_expr ``(gpow_coe_nat),
symm_expr ``(gpow_neg_one),
symm_expr ``(gpow_mul),
symm_expr ``(gpow_add_one),
symm_expr ``(gpow_one_add),
symm_expr ``(gpow_add),
expr ``(mul_gpow_neg_one),
expr ``(gpow_zero),
expr ``(mul_gpow),
symm_expr ``(mul_assoc),
expr ``(gpow_trick),
expr ``(gpow_trick_one),
expr ``(gpow_trick_one'),
expr ``(gpow_trick_sub),
expr ``(tactic.ring.horner)]
[] locat
/-- Auxilliary tactic for the `group` tactic. Calls `ring` to normalize exponents. -/
meta def aux_group₂ (locat : loc) : tactic unit :=
ring none tactic.ring.normalize_mode.raw locat
end tactic
namespace tactic.interactive
setup_tactic_parser
open tactic
/--
Tactic for normalizing expressions in multiplicative groups, without assuming
commutativity, using only the group axioms without any information about which group
is manipulated.
(For additive commutative groups, use the `abel` tactic instead.)
Example:
```lean
example {G : Type} [group G] (a b c d : G) (h : c = (a*b^2)*((b*b)⁻¹*a⁻¹)*d) : a*c*d⁻¹ = a :=
begin
group at h, -- normalizes `h` which becomes `h : c = d`
rw h, -- the goal is now `a*d*d⁻¹ = a`
group, -- which then normalized and closed
end
```
-/
meta def group (locat : parse location) : tactic unit :=
do when locat.include_goal `[rw ← mul_inv_eq_one],
try (aux_group₁ locat),
repeat (aux_group₂ locat ; aux_group₁ locat)
end tactic.interactive
add_tactic_doc
{ name := "group",
category := doc_category.tactic,
decl_names := [`tactic.interactive.group],
tags := ["decision procedure", "simplification"] }
|
36a203d05e6818740774e5a7c9c4865c31dfa63e | 78630e908e9624a892e24ebdd21260720d29cf55 | /src/logic_first_order/fol_17.lean | 5aa556941c26d69d94c2ffd28de73c9db184c82b | [
"CC0-1.0"
] | permissive | tomasz-lisowski/lean-logic-examples | 84e612466776be0a16c23a0439ff8ef6114ddbe1 | 2b2ccd467b49c3989bf6c92ec0358a8d6ee68c5d | refs/heads/master | 1,683,334,199,431 | 1,621,938,305,000 | 1,621,938,305,000 | 365,041,573 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,153 | lean | namespace fol_17
-- Facts useful for calculation proofs:
#check @add_assoc
#check @add_comm
#check @add_zero
#check @zero_add
#check @mul_assoc
#check @mul_comm
#check @mul_one
#check @one_mul
#check @left_distrib
#check @right_distrib
#check @add_left_neg
#check @add_right_neg
#check @sub_eq_add_neg
variables x y z : int
-- Sub-example 1:
theorem t1 : x - x = 0 :=
calc
x - x = x + -x : by rw sub_eq_add_neg
... = 0 : by rw add_right_neg
-- Sub-example 2:
theorem t2 (h : x + y = x + z) : y = z :=
calc
y = 0 + y : by rw zero_add
... = (-x + x) + y : by rw add_left_neg
... = -x + (x + y) : by rw add_assoc
... = -x + (x + z) : by rw h
... = (-x + x) + z : by rw add_assoc
... = 0 + z : by rw add_left_neg
... = z : by rw zero_add
theorem fol_17 (h : x + y = z + y) : x = z :=
calc
x = x + 0 : by rw add_zero
... = x + (y + -y) : by rw add_right_neg
... = (x + y) + -y : by rw add_assoc
... = (z + y) + -y : by rw h
... = z + (y + -y) : by rw add_assoc
... = z + 0 : by rw add_right_neg
... = z : by rw add_zero
end fol_17 |
25ffa85f132cac5551504a0b5cc9c32d9cd8539f | b2363dbdedecce9d05f15cdb1ecba3a7acfebb4a | /test/example.lean | 1442c2e3c88de978b7a1458b5e8feaced81739e9 | [
"Apache-2.0"
] | permissive | xiw/arithcc | dcaf4720829f1e37e28fe32785e7d1efbbdcc78b | f3e0e689d3d5b53b54005303e495e49019e77532 | refs/heads/master | 1,672,711,806,073 | 1,603,320,081,000 | 1,603,320,081,000 | 304,186,195 | 14 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 762 | lean | /-
Copyright (c) 2020 Xi Wang. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Xi Wang.
-/
import arithcc
namespace arithcc
section test
open instruction
/-- The example in the paper for compiling (x + 3) + (x + (y + 2)). -/
example (x y t : register) :
let map := λ v, if v = "x" then x else if v = "y" then y else 0,
p := expr.sum (expr.sum (expr.var "x") (expr.const 3))
(expr.sum (expr.var "x") (expr.sum (expr.var "y") (expr.const 2))) in
compile map p t =
[ load x,
sto t,
li 3,
add t,
sto t,
load x,
sto (t + 1),
load y,
sto (t + 2),
li 2,
add (t + 2),
add (t + 1),
add t ] :=
rfl
end test
end arithcc
|
6590ca63250bbfb1e21a9d57a6c89dbd7a6358ae | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/order/lattice_group.lean | 3ed9bb5da2e2a24a07f4102e44b2fb7cc613f146 | [
"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 | 18,821 | lean | /-
Copyright (c) 2021 Christopher Hoskin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Christopher Hoskin
-/
import algebra.group_power.basic -- Needed for squares
import algebra.order.group
import tactic.nth_rewrite
/-!
# Lattice ordered groups
Lattice ordered groups were introduced by [Birkhoff][birkhoff1942].
They form the algebraic underpinnings of vector lattices, Banach lattices, AL-space, AM-space etc.
This file develops the basic theory, concentrating on the commutative case.
## Main statements
- `pos_div_neg`: Every element `a` of a lattice ordered commutative group has a decomposition
`a⁺-a⁻` into the difference of the positive and negative component.
- `pos_inf_neg_eq_one`: The positive and negative components are coprime.
- `abs_triangle`: The absolute value operation satisfies the triangle inequality.
It is shown that the inf and sup operations are related to the absolute value operation by a
number of equations and inequalities.
## Notations
- `a⁺ = a ⊔ 0`: The *positive component* of an element `a` of a lattice ordered commutative group
- `a⁻ = (-a) ⊔ 0`: The *negative component* of an element `a` of a lattice ordered commutative group
* `|a| = a⊔(-a)`: The *absolute value* of an element `a` of a lattice ordered commutative group
## Implementation notes
A lattice ordered commutative group is a type `α` satisfying:
* `[lattice α]`
* `[comm_group α]`
* `[covariant_class α α (*) (≤)]`
The remainder of the file establishes basic properties of lattice ordered commutative groups. A
number of these results also hold in the non-commutative case ([Birkhoff][birkhoff1942],
[Fuchs][fuchs1963]) but we have not developed that here, since we are primarily interested in vector
lattices.
## References
* [Birkhoff, Lattice-ordered Groups][birkhoff1942]
* [Bourbaki, Algebra II][bourbaki1981]
* [Fuchs, Partially Ordered Algebraic Systems][fuchs1963]
* [Zaanen, Lectures on "Riesz Spaces"][zaanen1966]
* [Banasiak, Banach Lattices in Applications][banasiak]
## Tags
lattice, ordered, group
-/
universe u
-- A linearly ordered additive commutative group is a lattice ordered commutative group
@[priority 100, to_additive] -- see Note [lower instance priority]
instance linear_ordered_comm_group.to_covariant_class (α : Type u)
[linear_ordered_comm_group α] : covariant_class α α (*) (≤) :=
{ elim := λ a b c bc, linear_ordered_comm_group.mul_le_mul_left _ _ bc a }
variables {α : Type u} [lattice α] [comm_group α]
-- Special case of Bourbaki A.VI.9 (1)
-- c + (a ⊔ b) = (c + a) ⊔ (c + b)
@[to_additive]
lemma mul_sup [covariant_class α α (*) (≤)] (a b c : α) : c * (a ⊔ b) = (c * a) ⊔ (c * b) :=
begin
refine le_antisymm _ (by simp),
rw [← mul_le_mul_iff_left (c⁻¹), ← mul_assoc, inv_mul_self, one_mul],
exact sup_le (by simp) (by simp),
end
@[to_additive]
lemma mul_inf [covariant_class α α (*) (≤)] (a b c : α) : c * (a ⊓ b) = (c * a) ⊓ (c * b) :=
begin
refine le_antisymm (by simp) _,
rw [← mul_le_mul_iff_left (c⁻¹), ← mul_assoc, inv_mul_self, one_mul],
exact le_inf (by simp) (by simp),
end
-- Special case of Bourbaki A.VI.9 (2)
-- -(a ⊔ b)=(-a) ⊓ (-b)
@[to_additive]
lemma inv_sup_eq_inv_inf_inv [covariant_class α α (*) (≤)] (a b : α) : (a ⊔ b)⁻¹ = a⁻¹ ⊓ b⁻¹ :=
begin
apply le_antisymm,
{ refine le_inf _ _,
{ rw inv_le_inv_iff, exact le_sup_left, },
{ rw inv_le_inv_iff, exact le_sup_right, } },
{ rw [← inv_le_inv_iff, inv_inv],
refine sup_le _ _,
{ rw ← inv_le_inv_iff, simp, },
{ rw ← inv_le_inv_iff, simp, } }
end
-- -(a ⊓ b) = -a ⊔ -b
@[to_additive]
lemma inv_inf_eq_sup_inv [covariant_class α α (*) (≤)] (a b : α) : (a ⊓ b)⁻¹ = a⁻¹ ⊔ b⁻¹ :=
by rw [← inv_inv (a⁻¹ ⊔ b⁻¹), inv_sup_eq_inv_inf_inv a⁻¹ b⁻¹, inv_inv, inv_inv]
-- Bourbaki A.VI.10 Prop 7
-- a ⊓ b + (a ⊔ b) = a + b
@[to_additive]
lemma inf_mul_sup [covariant_class α α (*) (≤)] (a b : α) : (a ⊓ b) * (a ⊔ b) = a * b :=
calc (a ⊓ b) * (a ⊔ b) = (a ⊓ b) * ((a * b) * (b⁻¹ ⊔ a⁻¹)) :
by { rw mul_sup b⁻¹ a⁻¹ (a * b), simp, }
... = (a ⊓ b) * ((a * b) * (a ⊓ b)⁻¹) : by rw [inv_inf_eq_sup_inv, sup_comm]
... = a * b : by rw [mul_comm, inv_mul_cancel_right]
namespace lattice_ordered_comm_group
/--
Let `α` be a lattice ordered commutative group with identity `1`. For an element `a` of type `α`,
the element `a ⊔ 1` is said to be the *positive component* of `a`, denoted `a⁺`.
-/
@[to_additive /-"
Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `a ⊔ 0` is said to be the *positive component* of `a`, denoted `a⁺`.
"-/,
priority 100] -- see Note [lower instance priority]
instance has_one_lattice_has_pos_part : has_pos_part (α) := ⟨λ a, a ⊔ 1⟩
@[to_additive pos_part_def]
lemma m_pos_part_def (a : α) : a⁺ = a ⊔ 1 := rfl
/--
Let `α` be a lattice ordered commutative group with identity `1`. For an element `a` of type `α`,
the element `(-a) ⊔ 1` is said to be the *negative component* of `a`, denoted `a⁻`.
-/
@[to_additive /-"
Let `α` be a lattice ordered commutative group with identity `0`. For an element `a` of type `α`,
the element `(-a) ⊔ 0` is said to be the *negative component* of `a`, denoted `a⁻`.
"-/,
priority 100] -- see Note [lower instance priority]
instance has_one_lattice_has_neg_part : has_neg_part (α) := ⟨λ a, a⁻¹ ⊔ 1⟩
@[to_additive neg_part_def]
lemma m_neg_part_def (a : α) : a⁻ = a⁻¹ ⊔ 1 := rfl
@[simp, to_additive]
lemma pos_one : (1 : α)⁺ = 1 := sup_idem
@[simp, to_additive]
lemma neg_one : (1 : α)⁻ = 1 := by rw [m_neg_part_def, one_inv, sup_idem]
-- a⁻ = -(a ⊓ 0)
@[to_additive]
lemma neg_eq_inv_inf_one [covariant_class α α (*) (≤)] (a : α) : a⁻ = (a ⊓ 1)⁻¹ :=
by rw [m_neg_part_def, ← inv_inj, inv_sup_eq_inv_inf_inv, inv_inv, inv_inv, one_inv]
@[to_additive le_abs]
lemma le_mabs (a : α) : a ≤ |a| := le_sup_left
@[to_additive]
-- -a ≤ |a|
lemma inv_le_abs (a : α) : a⁻¹ ≤ |a| := le_sup_right
-- 0 ≤ a⁺
@[to_additive pos_nonneg]
lemma one_le_pos (a : α) : 1 ≤ a⁺ := le_sup_right
-- 0 ≤ a⁻
@[to_additive neg_nonneg]
lemma one_le_neg (a : α) : 1 ≤ a⁻ := le_sup_right
@[to_additive] -- pos_nonpos_iff
lemma pos_le_one_iff {a : α} : a⁺ ≤ 1 ↔ a ≤ 1 :=
by { rw [m_pos_part_def, sup_le_iff], simp, }
@[to_additive] -- neg_nonpos_iff
lemma neg_le_one_iff {a : α} : a⁻ ≤ 1 ↔ a⁻¹ ≤ 1 :=
by { rw [m_neg_part_def, sup_le_iff], simp, }
@[to_additive]
lemma pos_eq_one_iff {a : α} : a⁺ = 1 ↔ a ≤ 1 :=
by { rw le_antisymm_iff, simp only [one_le_pos, and_true], exact pos_le_one_iff, }
@[to_additive]
lemma neg_eq_one_iff' {a : α} : a⁻ = 1 ↔ a⁻¹ ≤ 1 :=
by { rw le_antisymm_iff, simp only [one_le_neg, and_true], rw neg_le_one_iff, }
@[to_additive]
lemma neg_eq_one_iff [covariant_class α α has_mul.mul has_le.le] {a : α} : a⁻ = 1 ↔ 1 ≤ a :=
by { rw le_antisymm_iff, simp only [one_le_neg, and_true], rw [neg_le_one_iff, inv_le_one'], }
@[to_additive le_pos]
lemma m_le_pos (a : α) : a ≤ a⁺ := le_sup_left
-- -a ≤ a⁻
@[to_additive]
lemma inv_le_neg (a : α) : a⁻¹ ≤ a⁻ := le_sup_left
-- Bourbaki A.VI.12
-- a⁻ = (-a)⁺
@[to_additive]
lemma neg_eq_pos_inv (a : α) : a⁻ = (a⁻¹)⁺ := rfl
-- a⁺ = (-a)⁻
@[to_additive]
lemma pos_eq_neg_inv (a : α) : a⁺ = (a⁻¹)⁻ := by simp [neg_eq_pos_inv]
-- We use this in Bourbaki A.VI.12 Prop 9 a)
-- c + (a ⊓ b) = (c + a) ⊓ (c + b)
@[to_additive]
lemma mul_inf_eq_mul_inf_mul [covariant_class α α (*) (≤)]
(a b c : α) : c * (a ⊓ b) = (c * a) ⊓ (c * b) :=
begin
refine le_antisymm (by simp) _,
rw [← mul_le_mul_iff_left c⁻¹, ← mul_assoc, inv_mul_self, one_mul, le_inf_iff],
simp,
end
-- Bourbaki A.VI.12 Prop 9 a)
-- a = a⁺ - a⁻
@[simp, to_additive]
lemma pos_div_neg [covariant_class α α (*) (≤)] (a : α) : a⁺ / a⁻ = a :=
begin
symmetry,
rw div_eq_mul_inv,
apply eq_mul_inv_of_mul_eq,
rw [m_neg_part_def, mul_sup, mul_one, mul_right_inv, sup_comm, m_pos_part_def],
end
-- Bourbaki A.VI.12 Prop 9 a)
-- a⁺ ⊓ a⁻ = 0 (`a⁺` and `a⁻` are co-prime, and, since they are positive, disjoint)
@[to_additive]
lemma pos_inf_neg_eq_one [covariant_class α α (*) (≤)] (a : α) : a⁺ ⊓ a⁻ = 1 :=
by rw [←mul_right_inj (a⁻)⁻¹, mul_inf_eq_mul_inf_mul, mul_one, mul_left_inv, mul_comm,
← div_eq_mul_inv, pos_div_neg, neg_eq_inv_inf_one, inv_inv]
-- Bourbaki A.VI.12 (with a and b swapped)
-- a⊔b = b + (a - b)⁺
@[to_additive]
lemma sup_eq_mul_pos_div [covariant_class α α (*) (≤)] (a b : α) : a ⊔ b = b * (a / b)⁺ :=
calc a ⊔ b = (b * (a / b)) ⊔ (b * 1) : by rw [mul_one b, div_eq_mul_inv, mul_comm a,
mul_inv_cancel_left]
... = b * ((a / b) ⊔ 1) : by rw ← mul_sup (a / b) 1 b
-- Bourbaki A.VI.12 (with a and b swapped)
-- a⊓b = a - (a - b)⁺
@[to_additive]
lemma inf_eq_div_pos_div [covariant_class α α (*) (≤)] (a b : α) : a ⊓ b = a / (a / b)⁺ :=
calc a ⊓ b = (a * 1) ⊓ (a * (b / a)) : by { rw [mul_one a, div_eq_mul_inv, mul_comm b,
mul_inv_cancel_left], }
... = a * (1 ⊓ (b / a)) : by rw ← mul_inf_eq_mul_inf_mul 1 (b / a) a
... = a * ((b / a) ⊓ 1) : by rw inf_comm
... = a * ((a / b)⁻¹ ⊓ 1) : by { rw div_eq_mul_inv, nth_rewrite 0 ← inv_inv b,
rw [← mul_inv, mul_comm b⁻¹, ← div_eq_mul_inv], }
... = a * ((a / b)⁻¹ ⊓ 1⁻¹) : by rw one_inv
... = a / ((a / b) ⊔ 1) : by rw [← inv_sup_eq_inv_inf_inv, ← div_eq_mul_inv]
-- Bourbaki A.VI.12 Prop 9 c)
@[to_additive le_iff_pos_le_neg_ge]
lemma m_le_iff_pos_le_neg_ge [covariant_class α α (*) (≤)] (a b : α) : a ≤ b ↔ a⁺ ≤ b⁺ ∧ b⁻ ≤ a⁻ :=
begin
split; intro h,
{ split,
{ exact sup_le (h.trans (m_le_pos b)) (one_le_pos b), },
{ rw ← inv_le_inv_iff at h,
exact sup_le (h.trans (inv_le_neg a)) (one_le_neg a), } },
{ rw [← pos_div_neg a, ← pos_div_neg b],
exact div_le_div'' h.1 h.2, }
end
@[to_additive neg_abs]
lemma m_neg_abs [covariant_class α α (*) (≤)] (a : α) : |a|⁻ = 1 :=
begin
refine le_antisymm _ _,
{ rw ← pos_inf_neg_eq_one a,
apply le_inf,
{ rw pos_eq_neg_inv,
exact ((m_le_iff_pos_le_neg_ge _ _).mp (inv_le_abs a)).right, },
{ exact and.right (iff.elim_left (m_le_iff_pos_le_neg_ge _ _) (le_mabs a)), } },
{ exact one_le_neg _, }
end
@[to_additive pos_abs]
lemma m_pos_abs [covariant_class α α (*) (≤)] (a : α) : |a|⁺ = |a| :=
begin
nth_rewrite 1 ← pos_div_neg (|a|),
rw div_eq_mul_inv,
symmetry,
rw [mul_right_eq_self, inv_eq_one],
exact m_neg_abs a,
end
@[to_additive abs_nonneg]
lemma one_le_abs [covariant_class α α (*) (≤)] (a : α) : 1 ≤ |a| :=
by { rw ← m_pos_abs, exact one_le_pos _, }
-- The proof from Bourbaki A.VI.12 Prop 9 d)
-- |a| = a⁺ - a⁻
@[to_additive]
lemma pos_mul_neg [covariant_class α α (*) (≤)] (a : α) : |a| = a⁺ * a⁻ :=
begin
refine le_antisymm _ _,
{ refine sup_le _ _,
{ nth_rewrite 0 ← mul_one a,
exact mul_le_mul' (m_le_pos a) (one_le_neg a) },
{ nth_rewrite 0 ← one_mul (a⁻¹),
exact mul_le_mul' (one_le_pos a) (inv_le_neg a) } },
{ rw [← inf_mul_sup, pos_inf_neg_eq_one, one_mul, ← m_pos_abs a],
apply sup_le,
{ exact ((m_le_iff_pos_le_neg_ge _ _).mp (le_mabs a)).left, },
{ rw neg_eq_pos_inv,
exact ((m_le_iff_pos_le_neg_ge _ _).mp (inv_le_abs a)).left, }, }
end
-- a ⊔ b - (a ⊓ b) = |b - a|
@[to_additive]
lemma sup_div_inf_eq_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊔ b) / (a ⊓ b) = |b / a| :=
begin
rw [sup_eq_mul_pos_div, inf_comm, inf_eq_div_pos_div, div_eq_mul_inv],
nth_rewrite 1 div_eq_mul_inv,
rw [mul_inv_rev, inv_inv, mul_comm, ← mul_assoc, inv_mul_cancel_right, pos_eq_neg_inv (a / b)],
nth_rewrite 1 div_eq_mul_inv,
rw [mul_inv_rev, ← div_eq_mul_inv, inv_inv, ← pos_mul_neg],
end
-- 2•(a ⊔ b) = a + b + |b - a|
@[to_additive two_sup_eq_add_add_abs_sub]
lemma sup_sq_eq_mul_mul_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊔ b)^2 = a * b * |b / a| :=
by rw [← inf_mul_sup a b, ← sup_div_inf_eq_abs_div, div_eq_mul_inv, ← mul_assoc, mul_comm,
mul_assoc, ← pow_two, inv_mul_cancel_left]
-- 2•(a ⊓ b) = a + b - |b - a|
@[to_additive two_inf_eq_add_sub_abs_sub]
lemma inf_sq_eq_mul_div_abs_div [covariant_class α α (*) (≤)] (a b : α) :
(a ⊓ b)^2 = a * b / |b / a| :=
by rw [← inf_mul_sup a b, ← sup_div_inf_eq_abs_div, div_eq_mul_inv, div_eq_mul_inv,
mul_inv_rev, inv_inv, mul_assoc, mul_inv_cancel_comm_assoc, ← pow_two]
/--
Every lattice ordered commutative group is a distributive lattice
-/
@[to_additive
"Every lattice ordered commutative additive group is a distributive lattice"
]
def lattice_ordered_comm_group_to_distrib_lattice (α : Type u)
[s: lattice α] [comm_group α] [covariant_class α α (*) (≤)] : distrib_lattice α :=
{ le_sup_inf :=
begin
intros,
rw [← mul_le_mul_iff_left (x ⊓ (y ⊓ z)), inf_mul_sup x (y ⊓ z),
← inv_mul_le_iff_le_mul, le_inf_iff],
split,
{ rw [inv_mul_le_iff_le_mul, ← inf_mul_sup x y],
apply mul_le_mul',
{ apply inf_le_inf_left, apply inf_le_left, },
{ apply inf_le_left, } },
{ rw [inv_mul_le_iff_le_mul, ← inf_mul_sup x z],
apply mul_le_mul',
{ apply inf_le_inf_left, apply inf_le_right, },
{ apply inf_le_right, }, }
end,
..s }
-- See, e.g. Zaanen, Lectures on Riesz Spaces
-- 3rd lecture
-- |a ⊔ c - (b ⊔ c)| + |a ⊓ c-b ⊓ c| = |a - b|
@[to_additive]
theorem abs_div_sup_mul_abs_div_inf [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊔ c) / (b ⊔ c)| * |(a ⊓ c) / (b ⊓ c)| = |a / b| :=
begin
letI : distrib_lattice α := lattice_ordered_comm_group_to_distrib_lattice α,
calc |(a ⊔ c) / (b ⊔ c)| * |(a ⊓ c) / (b ⊓ c)| =
((b ⊔ c ⊔ (a ⊔ c)) / ((b ⊔ c) ⊓ (a ⊔ c))) * |(a ⊓ c) / (b ⊓ c)| : by rw sup_div_inf_eq_abs_div
... = (b ⊔ c ⊔ (a ⊔ c)) / ((b ⊔ c) ⊓ (a ⊔ c)) * (((b ⊓ c) ⊔ (a ⊓ c)) / ((b ⊓ c) ⊓ (a ⊓ c))) :
by rw sup_div_inf_eq_abs_div (b ⊓ c) (a ⊓ c)
... = (b ⊔ a ⊔ c) / ((b ⊓ a) ⊔ c) * (((b ⊔ a) ⊓ c) / (b ⊓ a ⊓ c)) : by
{ rw [← sup_inf_right, ← inf_sup_right, sup_assoc],
nth_rewrite 1 sup_comm,
rw [sup_right_idem, sup_assoc, inf_assoc],
nth_rewrite 3 inf_comm,
rw [inf_right_idem, inf_assoc], }
... = (b ⊔ a ⊔ c) * ((b ⊔ a) ⊓ c) /(((b ⊓ a) ⊔ c) * (b ⊓ a ⊓ c)) : by rw div_mul_comm
... = (b ⊔ a) * c / ((b ⊓ a) * c) :
by rw [mul_comm, inf_mul_sup, mul_comm (b ⊓ a ⊔ c), inf_mul_sup]
... = (b ⊔ a) / (b ⊓ a) : by rw [div_eq_mul_inv, mul_inv_rev, mul_assoc, mul_inv_cancel_left,
← div_eq_mul_inv]
... = |a / b| : by rw sup_div_inf_eq_abs_div
end
/--
Let `α` be a lattice ordered commutative group and let `a` be a positive element in `α`. Then `a` is
equal to its positive component `a⁺`.
-/
@[to_additive] -- pos_of_nonneg
lemma pos_of_one_le (a : α) (h : 1 ≤ a) : a⁺ = a :=
by { rw m_pos_part_def, exact sup_of_le_left h, }
-- 0 ≤ a implies a⁺ = a
@[to_additive] -- pos_of_nonpos
lemma pos_of_le_one (a : α) (h : a ≤ 1) : a⁺ = 1 :=
pos_eq_one_iff.mpr h
@[to_additive neg_of_inv_nonneg]
lemma neg_of_one_le_inv (a : α) (h : 1 ≤ a⁻¹) : a⁻ = a⁻¹ :=
by { rw neg_eq_pos_inv, exact pos_of_one_le _ h, }
@[to_additive] -- neg_of_neg_nonpos
lemma neg_of_inv_le_one (a : α) (h : a⁻¹ ≤ 1) : a⁻ = 1 :=
neg_eq_one_iff'.mpr h
@[to_additive] -- neg_of_nonpos
lemma neg_of_le_one [covariant_class α α (*) (≤)] (a : α) (h : a ≤ 1) : a⁻ = a⁻¹ :=
by { refine neg_of_one_le_inv _ _, rw one_le_inv', exact h, }
@[to_additive] -- neg_of_nonneg'
lemma neg_of_one_le [covariant_class α α (*) (≤)] (a : α) (h : 1 ≤ a) : a⁻ = 1 :=
neg_eq_one_iff.mpr h
-- 0 ≤ a implies |a| = a
@[to_additive abs_of_nonneg]
lemma mabs_of_one_le [covariant_class α α (*) (≤)] (a : α) (h : 1 ≤ a) : |a| = a :=
begin
unfold has_abs.abs,
rw [sup_eq_mul_pos_div, div_eq_mul_inv, inv_inv, ← pow_two, inv_mul_eq_iff_eq_mul,
← pow_two, pos_of_one_le],
rw pow_two,
apply one_le_mul h h,
end
/--
The unary operation of taking the absolute value is idempotent.
-/
@[simp, to_additive abs_abs]
lemma m_abs_abs [covariant_class α α (*) (≤)] (a : α) : | |a| | = |a| :=
mabs_of_one_le _ (one_le_abs _)
@[to_additive abs_sup_sub_sup_le_abs]
lemma mabs_sup_div_sup_le_mabs [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊔ c) / (b ⊔ c)| ≤ |a / b| :=
begin
apply le_of_mul_le_of_one_le_left,
{ rw abs_div_sup_mul_abs_div_inf, },
{ exact one_le_abs _, },
end
@[to_additive abs_inf_sub_inf_le_abs]
lemma mabs_inf_div_inf_le_mabs [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊓ c) / (b ⊓ c)| ≤ |a / b| :=
begin
apply le_of_mul_le_of_one_le_right,
{ rw abs_div_sup_mul_abs_div_inf, },
{ exact one_le_abs _, },
end
-- Commutative case, Zaanen, 3rd lecture
-- For the non-commutative case, see Birkhoff Theorem 19 (27)
-- |(a ⊔ c) - (b ⊔ c)| ⊔ |(a ⊓ c) - (b ⊓ c)| ≤ |a - b|
@[to_additive Birkhoff_inequalities]
theorem m_Birkhoff_inequalities [covariant_class α α (*) (≤)] (a b c : α) :
|(a ⊔ c) / (b ⊔ c)| ⊔ |(a ⊓ c) / (b ⊓ c)| ≤ |a / b| :=
sup_le (mabs_sup_div_sup_le_mabs a b c) (mabs_inf_div_inf_le_mabs a b c)
-- Banasiak Proposition 2.12, Zaanen 2nd lecture
/--
The absolute value satisfies the triangle inequality.
-/
@[to_additive abs_add_le]
lemma mabs_mul_le [covariant_class α α (*) (≤)] (a b : α) : |a * b| ≤ |a| * |b| :=
begin
apply sup_le,
{ exact mul_le_mul' (le_mabs a) (le_mabs b), },
{ rw mul_inv,
exact mul_le_mul' (inv_le_abs _) (inv_le_abs _), }
end
-- |a - b| = |b - a|
@[to_additive]
lemma abs_inv_comm (a b : α) : |a/b| = |b/a| :=
begin
unfold has_abs.abs,
rw [inv_div' a b, ← inv_inv (a / b), inv_div', sup_comm],
end
-- | |a| - |b| | ≤ |a - b|
@[to_additive]
lemma abs_abs_div_abs_le [covariant_class α α (*) (≤)] (a b : α) : | |a| / |b| | ≤ |a / b| :=
begin
unfold has_abs.abs,
rw sup_le_iff,
split,
{ apply div_le_iff_le_mul.2,
convert mabs_mul_le (a/b) b,
{ rw div_mul_cancel', },
{ rw div_mul_cancel', },
{ exact covariant_swap_mul_le_of_covariant_mul_le α, } },
{ rw [div_eq_mul_inv, mul_inv_rev, inv_inv, mul_inv_le_iff_le_mul, ← abs_eq_sup_inv (a / b),
abs_inv_comm],
convert mabs_mul_le (b/a) a,
{ rw div_mul_cancel', },
{rw div_mul_cancel', } },
end
end lattice_ordered_comm_group
|
b2c3ecafafec47be27396d888988699b7b531d73 | 367134ba5a65885e863bdc4507601606690974c1 | /src/field_theory/finite/polynomial.lean | 7f634f322450f213615f28918381646e81deba87 | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 7,858 | 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 field_theory.finite.basic
import field_theory.mv_polynomial
import data.mv_polynomial.expand
import linear_algebra.basic
import linear_algebra.finite_dimensional
/-!
## Polynomials over finite fields
-/
namespace mv_polynomial
variables {σ : Type*}
/-- A polynomial over the integers is divisible by `n : ℕ`
if and only if it is zero over `zmod n`. -/
lemma C_dvd_iff_zmod (n : ℕ) (φ : mv_polynomial σ ℤ) :
C (n:ℤ) ∣ φ ↔ map (int.cast_ring_hom (zmod n)) φ = 0 :=
C_dvd_iff_map_hom_eq_zero _ _ (char_p.int_cast_eq_zero_iff (zmod n) n) _
section frobenius
variables {p : ℕ} [fact p.prime]
lemma frobenius_zmod (f : mv_polynomial σ (zmod p)) :
frobenius _ p f = expand p f :=
begin
apply induction_on f,
{ intro a, rw [expand_C, frobenius_def, ← C_pow, zmod.pow_card], },
{ simp only [alg_hom.map_add, ring_hom.map_add], intros _ _ hf hg, rw [hf, hg] },
{ simp only [expand_X, ring_hom.map_mul, alg_hom.map_mul],
intros _ _ hf, rw [hf, frobenius_def], },
end
lemma expand_zmod (f : mv_polynomial σ (zmod p)) :
expand p f = f ^ p :=
(frobenius_zmod _).symm
end frobenius
end mv_polynomial
namespace mv_polynomial
noncomputable theory
open_locale big_operators classical
open set linear_map submodule
variables {K : Type*} {σ : Type*}
variables [field K] [fintype K] [fintype σ]
def indicator (a : σ → K) : mv_polynomial σ K :=
∏ n, (1 - (X n - C (a n))^(fintype.card K - 1))
lemma eval_indicator_apply_eq_one (a : σ → K) :
eval a (indicator a) = 1 :=
have 0 < fintype.card K - 1,
begin
rw [← finite_field.card_units, fintype.card_pos_iff],
exact ⟨1⟩
end,
by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, zero_pow this, sub_zero, finset.prod_const_one]
lemma eval_indicator_apply_eq_zero (a b : σ → K) (h : a ≠ b) :
eval a (indicator b) = 0 :=
have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h,
begin
rcases this with ⟨i, hi⟩,
simp only [indicator, (finset.univ.prod_hom (eval a)).symm, ring_hom.map_sub,
is_ring_hom.map_one (eval a), is_monoid_hom.map_pow (eval a), eval_X, eval_C,
sub_self, finset.prod_eq_zero_iff],
refine ⟨i, finset.mem_univ _, _⟩,
rw [finite_field.pow_card_sub_one_eq_one, sub_self],
rwa [(≠), sub_eq_zero],
end
lemma degrees_indicator (c : σ → K) :
degrees (indicator c) ≤ ∑ s : σ, (fintype.card K - 1) •ℕ {s} :=
begin
rw [indicator],
refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_one, ← bot_eq_zero, bot_sup_eq],
refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _),
refine le_trans (degrees_sub _ _) _,
rw [degrees_C, ← bot_eq_zero, sup_bot_eq],
exact degrees_X' _
end
lemma indicator_mem_restrict_degree (c : σ → K) :
indicator c ∈ restrict_degree σ K (fintype.card K - 1) :=
begin
rw [mem_restrict_degree_iff_sup, indicator],
assume n,
refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _),
rw [← finset.univ.sum_hom (multiset.count n)],
simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton,
nsmul_eq_mul, nat.cast_id],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] },
{ assume h, exact (h $ finset.mem_univ _).elim },
{ rw [multiset.count_cons_self, multiset.count_zero, mul_one] }
end
section
variables (K σ)
def evalₗ : mv_polynomial σ K →ₗ[K] (σ → K) → K :=
⟨ λp e, eval e p,
assume p q, (by { ext x, rw ring_hom.map_add, refl, }),
assume a p, funext $ assume e, by rw [smul_eq_C_mul, ring_hom.map_mul, eval_C]; refl ⟩
end
lemma evalₗ_apply (p : mv_polynomial σ K) (e : σ → K) : evalₗ K σ p e = eval e p :=
rfl
lemma map_restrict_dom_evalₗ : (restrict_degree σ K (fintype.card K - 1)).map (evalₗ K σ) = ⊤ :=
begin
refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _),
refine ⟨∑ n : σ → K, e n • indicator n, _, _⟩,
{ exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) },
{ ext n,
simp only [linear_map.map_sum, @finset.sum_apply (σ → K) (λ_, K) _ _ _ _ _,
pi.smul_apply, linear_map.map_smul],
simp only [evalₗ_apply],
transitivity,
refine finset.sum_eq_single n _ _,
{ assume b _ h,
rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] },
{ assume h, exact (h $ finset.mem_univ n).elim },
{ rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } }
end
end mv_polynomial
namespace mv_polynomial
open_locale classical
open linear_map submodule
universe u
variables (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K]
@[derive [add_comm_group, vector_space K, inhabited]]
def R : Type u := restrict_degree σ K (fintype.card K - 1)
noncomputable instance decidable_restrict_degree (m : ℕ) :
decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) :=
by simp only [set.mem_set_of_eq]; apply_instance
lemma dim_R : vector_space.dim K (R σ K) = fintype.card (σ → K) :=
calc vector_space.dim K (R σ K) =
vector_space.dim K (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} →₀ K) :
linear_equiv.dim_eq
(finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card K - 1 })
... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card K - 1} :
by rw [finsupp.dim_eq, dim_of_field, mul_one]
... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card K } :
begin
refine quotient.sound ⟨equiv.subtype_equiv finsupp.equiv_fun_on_fintype $ assume f, _⟩,
refine forall_congr (assume n, nat.le_sub_right_iff_add_le _),
exact fintype.card_pos_iff.2 ⟨0⟩
end
... = cardinal.mk (σ → {n // n < fintype.card K}) :
quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card K)⟩
... = cardinal.mk (σ → fin (fintype.card K)) :
quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩
... = cardinal.mk (σ → K) :
begin
refine (trunc.induction_on (fintype.equiv_fin K) $ assume (e : K ≃ fin (fintype.card K)), _),
refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩
end
... = fintype.card (σ → K) : cardinal.fintype_card _
instance : finite_dimensional K (R σ K) :=
finite_dimensional.finite_dimensional_iff_dim_lt_omega.mpr
(by simpa only [dim_R] using cardinal.nat_lt_omega (fintype.card (σ → K)))
lemma findim_R : finite_dimensional.findim K (R σ K) = fintype.card (σ → K) :=
finite_dimensional.findim_eq_of_dim_eq (dim_R σ K)
def evalᵢ : R σ K →ₗ[K] (σ → K) → K :=
((evalₗ K σ).comp (restrict_degree σ K (fintype.card K - 1)).subtype)
lemma range_evalᵢ : (evalᵢ σ K).range = ⊤ :=
begin
rw [evalᵢ, linear_map.range_comp, range_subtype],
exact map_restrict_dom_evalₗ
end
lemma ker_evalₗ : (evalᵢ σ K).ker = ⊥ :=
begin
refine (ker_eq_bot_iff_range_eq_top_of_findim_eq_findim _).mpr (range_evalᵢ _ _),
rw [finite_dimensional.findim_fintype_fun_eq_card, findim_R]
end
lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ K)
(h : ∀v:σ → K, eval v p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) :
p = 0 :=
let p' : R σ K := ⟨p, hp⟩ in
have p' ∈ (evalᵢ σ K).ker := by { rw [mem_ker], ext v, exact h v },
show p'.1 = (0 : R σ K).1,
begin
rw [ker_evalₗ, mem_bot] at this,
rw [this]
end
end mv_polynomial
|
ef8db55e7a7840d475516a9cf9a6e7b64d7267d9 | 2fbe653e4bc441efde5e5d250566e65538709888 | /src/topology/metric_space/isometry.lean | 0db7f310ecaab0130fb0af789024d6d3a31849e7 | [
"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 | 12,980 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Isometries of emetric and metric spaces
Authors: Sébastien Gouëzel
-/
import topology.metric_space.basic
topology.bounded_continuous_function analysis.normed_space.basic topology.opens
/-!
# Isometries
We define isometries, i.e., maps between emetric spaces that preserve
the edistance (on metric spaces, these are exactly the maps that preserve distances),
and prove their basic properties. We also introduce isometric bijections.
-/
noncomputable theory
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
open function set
/-- An isometry (also known as isometric embedding) is a map preserving the edistance
between emetric spaces, or equivalently the distance between metric space. -/
def isometry [emetric_space α] [emetric_space β] (f : α → β) : Prop :=
∀x1 x2 : α, edist (f x1) (f x2) = edist x1 x2
/-- On metric spaces, a map is an isometry if and only if it preserves distances. -/
lemma isometry_emetric_iff_metric [metric_space α] [metric_space β] {f : α → β} :
isometry f ↔ (∀x y, dist (f x) (f y) = dist x y) :=
⟨assume H x y, by simp [dist_edist, H x y],
assume H x y, by simp [edist_dist, H x y]⟩
/-- An isometry preserves edistances. -/
theorem isometry.edist_eq [emetric_space α] [emetric_space β] {f : α → β} {x y : α} (hf : isometry f) :
edist (f x) (f y) = edist x y :=
hf x y
/-- An isometry preserves distances. -/
theorem isometry.dist_eq [metric_space α] [metric_space β] {f : α → β} {x y : α} (hf : isometry f) :
dist (f x) (f y) = dist x y :=
by rw [dist_edist, dist_edist, hf]
section emetric_isometry
variables [emetric_space α] [emetric_space β] [emetric_space γ]
variables {f : α → β} {x y z : α} {s : set α}
/-- An isometry is injective -/
lemma isometry.injective (h : isometry f) : injective f :=
λx y hxy, edist_eq_zero.1 $
calc edist x y = edist (f x) (f y) : (h x y).symm
... = 0 : by rw [hxy]; simp
/-- Any map on a subsingleton is an isometry -/
theorem isometry_subsingleton [subsingleton α] : isometry f :=
λx y, by rw subsingleton.elim x y; simp
/-- The identity is an isometry -/
lemma isometry_id : isometry (id : α → α) :=
λx y, rfl
/-- The composition of isometries is an isometry -/
theorem isometry.comp {g : β → γ} {f : α → β} (hg : isometry g) (hf : isometry f) : isometry (g ∘ f) :=
assume x y, calc
edist ((g ∘ f) x) ((g ∘ f) y) = edist (f x) (f y) : hg _ _
... = edist x y : hf _ _
/-- An isometry is an embedding -/
theorem isometry.uniform_embedding (hf : isometry f) : uniform_embedding f :=
begin
refine emetric.uniform_embedding_iff'.2 ⟨_, _⟩,
{ assume ε εpos,
existsi [ε, εpos],
simp [hf.edist_eq] },
{ assume δ δpos,
existsi [δ, δpos],
simp [hf.edist_eq] }
end
/-- An isometry is continuous. -/
lemma isometry.continuous (hf : isometry f) : continuous f :=
hf.uniform_embedding.embedding.continuous
/-- The inverse of an isometry is an isometry. -/
lemma isometry.inv (e : α ≃ β) (h : isometry e.to_fun) : isometry e.inv_fun :=
λx y, by rw [← h, e.right_inv _, e.right_inv _]
/-- Isometries preserve the diameter -/
lemma emetric.isometry.diam_image (hf : isometry f) {s : set α}:
emetric.diam (f '' s) = emetric.diam s :=
eq_of_forall_ge_iff $ λ d,
by simp only [emetric.diam_le_iff_forall_edist_le, ball_image_iff, hf.edist_eq]
/-- The injection from a subtype is an isometry -/
lemma isometry_subtype_val {s : set α} : isometry (subtype.val : s → α) :=
λx y, rfl
end emetric_isometry --section
/-- An isometry preserves the diameter in metric spaces -/
lemma metric.isometry.diam_image [metric_space α] [metric_space β]
{f : α → β} {s : set α} (hf : isometry f) : metric.diam (f '' s) = metric.diam s :=
by rw [metric.diam, metric.diam, emetric.isometry.diam_image hf]
/-- α and β are isometric if there is an isometric bijection between them. -/
structure isometric (α : Type*) (β : Type*) [emetric_space α] [emetric_space β]
extends α ≃ β :=
(isometry_to_fun : isometry to_fun)
(isometry_inv_fun : isometry inv_fun)
infix ` ≃ᵢ `:25 := isometric
namespace isometric
variables [emetric_space α] [emetric_space β] [emetric_space γ]
instance : has_coe_to_fun (α ≃ᵢ β) := ⟨λ_, α → β, λe, e.to_equiv⟩
lemma coe_eq_to_equiv (h : α ≃ᵢ β) (a : α) : h a = h.to_equiv a := rfl
/-- The (bundled) homeomorphism associated to an isometric isomorphism. -/
protected def to_homeomorph (h : α ≃ᵢ β) : α ≃ₜ β :=
{ continuous_to_fun := (isometry_to_fun h).continuous,
continuous_inv_fun := (isometry_inv_fun h).continuous,
.. h.to_equiv }
lemma coe_eq_to_homeomorph (h : α ≃ᵢ β) (a : α) :
h a = h.to_homeomorph a := rfl
lemma to_homeomorph_to_equiv (h : α ≃ᵢ β) :
h.to_homeomorph.to_equiv = h.to_equiv :=
by ext; refl
/-- The identity isometry of a space. -/
protected def refl (α : Type*) [emetric_space α] : α ≃ᵢ α :=
{ isometry_to_fun := isometry_id, isometry_inv_fun := isometry_id, .. equiv.refl α }
/-- The composition of two isometric isomorphisms, as an isometric isomorphism. -/
protected def trans (h₁ : α ≃ᵢ β) (h₂ : β ≃ᵢ γ) : α ≃ᵢ γ :=
{ isometry_to_fun := h₂.isometry_to_fun.comp h₁.isometry_to_fun,
isometry_inv_fun := h₁.isometry_inv_fun.comp h₂.isometry_inv_fun,
.. equiv.trans h₁.to_equiv h₂.to_equiv }
/-- The inverse of an isometric isomorphism, as an isometric isomorphism. -/
protected def symm (h : α ≃ᵢ β) : β ≃ᵢ α :=
{ isometry_to_fun := h.isometry_inv_fun,
isometry_inv_fun := h.isometry_to_fun,
.. h.to_equiv.symm }
protected lemma isometry (h : α ≃ᵢ β) : isometry h := h.isometry_to_fun
lemma symm_comp_self (h : α ≃ᵢ β) : ⇑h.symm ∘ ⇑h = id :=
funext $ assume a, h.to_equiv.left_inv a
lemma self_comp_symm (h : α ≃ᵢ β) : ⇑h ∘ ⇑h.symm = id :=
funext $ assume a, h.to_equiv.right_inv a
lemma range_coe (h : α ≃ᵢ β) : range h = univ :=
eq_univ_of_forall $ assume b, ⟨h.symm b, congr_fun h.self_comp_symm b⟩
lemma image_symm (h : α ≃ᵢ β) : image h.symm = preimage h :=
image_eq_preimage_of_inverse h.symm.to_equiv.left_inv h.symm.to_equiv.right_inv
lemma preimage_symm (h : α ≃ᵢ β) : preimage h.symm = image h :=
(image_eq_preimage_of_inverse h.to_equiv.left_inv h.to_equiv.right_inv).symm
end isometric
/-- An isometry induces an isometric isomorphism between the source space and the
range of the isometry. -/
def isometry.isometric_on_range [emetric_space α] [emetric_space β] {f : α → β} (h : isometry f) :
α ≃ᵢ range f :=
{ isometry_to_fun := λx y,
begin
change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y,
rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective],
exact h x y
end,
isometry_inv_fun :=
begin
apply isometry.inv,
assume x y,
change edist ((equiv.set.range f _) x) ((equiv.set.range f _) y) = edist x y,
rw [equiv.set.range_apply f h.injective, equiv.set.range_apply f h.injective],
exact h x y
end,
.. equiv.set.range f h.injective }
lemma isometry.isometric_on_range_apply [emetric_space α] [emetric_space β]
{f : α → β} (h : isometry f) (x : α) : h.isometric_on_range x = ⟨f x, mem_range_self _⟩ :=
begin
dunfold isometry.isometric_on_range,
rw ← equiv.set.range_apply f h.injective x,
refl
end
/-- In a normed algebra, the inclusion of the base field in the extended field is an isometry. -/
lemma algebra_map_isometry (𝕜 : Type*) (𝕜' : Type*) [normed_field 𝕜] [normed_ring 𝕜']
[h : normed_algebra 𝕜 𝕜'] : isometry (@algebra_map 𝕜 𝕜' _ _ _) :=
begin
refine isometry_emetric_iff_metric.2 (λx y, _),
rw [dist_eq_norm, dist_eq_norm, ← algebra.map_sub, norm_algebra_map_eq],
end
/-- The space of bounded sequences, with its sup norm -/
@[reducible] def ℓ_infty_ℝ : Type := bounded_continuous_function ℕ ℝ
open bounded_continuous_function metric topological_space
namespace Kuratowski_embedding
/-! ### In this section, we show that any separable metric space can be embedded isometrically in ℓ^∞(ℝ) -/
variables {f g : ℓ_infty_ℝ} {n : ℕ} {C : ℝ} [metric_space α] (x : ℕ → α) (a b : α)
/-- A metric space can be embedded in `l^∞(ℝ)` via the distances to points in
a fixed countable set, if this set is dense. This map is given in the next definition,
without density assumptions. -/
def embedding_of_subset : ℓ_infty_ℝ :=
of_normed_group_discrete (λn, dist a (x n) - dist (x 0) (x n)) (dist a (x 0)) (λ_, abs_dist_sub_le _ _ _)
lemma embedding_of_subset_coe : embedding_of_subset x a n = dist a (x n) - dist (x 0) (x n) := rfl
/-- The embedding map is always a semi-contraction. -/
lemma embedding_of_subset_dist_le (a b : α) :
dist (embedding_of_subset x a) (embedding_of_subset x b) ≤ dist a b :=
begin
refine (dist_le dist_nonneg).2 (λn, _),
have A : dist a (x n) + (dist (x 0) (x n) + (-dist b (x n) + -dist (x 0) (x n)))
= dist a (x n) - dist b (x n), by ring,
simp only [embedding_of_subset_coe, real.dist_eq, A, add_comm, neg_add_rev, _root_.neg_neg,
sub_eq_add_neg, add_left_comm],
exact abs_dist_sub_le _ _ _
end
/-- When the reference set is dense, the embedding map is an isometry on its image. -/
lemma embedding_of_subset_isometry (H : closure (range x) = univ) : isometry (embedding_of_subset x) :=
begin
refine isometry_emetric_iff_metric.2 (λa b, _),
refine le_antisymm (embedding_of_subset_dist_le x a b) (real.le_of_forall_epsilon_le (λe epos, _)),
/- First step: find n with dist a (x n) < e -/
have A : a ∈ closure (range x), by { have B := mem_univ a, rwa [← H] at B },
rcases mem_closure_iff'.1 A (e/2) (half_pos epos) with ⟨d, ⟨drange, hd⟩⟩,
cases drange with n dn,
rw [← dn] at hd,
/- Second step: use the norm control at index n to conclude -/
have C : dist b (x n) - dist a (x n) = embedding_of_subset x b n - embedding_of_subset x a n :=
by { simp [embedding_of_subset_coe] },
have := calc
dist a b ≤ dist a (x n) + dist (x n) b : dist_triangle _ _ _
... = 2 * dist a (x n) + (dist b (x n) - dist a (x n)) : by { simp [dist_comm], ring }
... ≤ 2 * dist a (x n) + abs (dist b (x n) - dist a (x n)) :
by apply_rules [add_le_add_left, le_abs_self]
... ≤ 2 * (e/2) + abs (embedding_of_subset x b n - embedding_of_subset x a n) :
begin rw [C], apply_rules [add_le_add, mul_le_mul_of_nonneg_left, le_of_lt hd, le_refl], norm_num end
... ≤ 2 * (e/2) + dist (embedding_of_subset x b) (embedding_of_subset x a) :
begin rw [← coe_diff], apply add_le_add_left, rw [coe_diff, ←real.dist_eq], apply dist_coe_le_dist end
... = dist (embedding_of_subset x b) (embedding_of_subset x a) + e : by ring,
simpa [dist_comm] using this
end
/-- Every separable metric space embeds isometrically in ℓ_infty_ℝ. -/
theorem exists_isometric_embedding (α : Type u) [metric_space α] [separable_space α] :
∃(f : α → ℓ_infty_ℝ), isometry f :=
begin
cases (univ : set α).eq_empty_or_nonempty with h h,
{ use (λ_, 0), assume x, exact absurd h (nonempty.ne_empty ⟨x, mem_univ x⟩) },
{ /- We construct a map x : ℕ → α with dense image -/
rcases h with basepoint,
haveI : inhabited α := ⟨basepoint⟩,
have : ∃s:set α, countable s ∧ closure s = univ := separable_space.exists_countable_closure_eq_univ _,
rcases this with ⟨S, ⟨S_countable, S_dense⟩⟩,
rcases countable_iff_exists_surjective.1 S_countable with ⟨x, x_range⟩,
have : closure (range x) = univ :=
univ_subset_iff.1 (by { rw [← S_dense], apply closure_mono, assumption }),
/- Use embedding_of_subset to construct the desired isometry -/
exact ⟨embedding_of_subset x, embedding_of_subset_isometry x this⟩ }
end
end Kuratowski_embedding
open topological_space Kuratowski_embedding
/-- The Kuratowski embedding is an isometric embedding of a separable metric space in ℓ^∞(ℝ) -/
def Kuratowski_embedding (α : Type u) [metric_space α] [separable_space α] : α → ℓ_infty_ℝ :=
classical.some (Kuratowski_embedding.exists_isometric_embedding α)
/-- The Kuratowski embedding is an isometry -/
protected lemma Kuratowski_embedding.isometry (α : Type u) [metric_space α] [separable_space α] :
isometry (Kuratowski_embedding α) :=
classical.some_spec (exists_isometric_embedding α)
/-- Version of the Kuratowski embedding for nonempty compacts -/
def nonempty_compacts.Kuratowski_embedding (α : Type u) [metric_space α] [compact_space α] [nonempty α] :
nonempty_compacts ℓ_infty_ℝ :=
⟨range (Kuratowski_embedding α), range_nonempty _,
compact_range (Kuratowski_embedding.isometry α).continuous⟩
|
458377a8b3b113c2efdb8597868948c70721ead6 | 037dba89703a79cd4a4aec5e959818147f97635d | /src/2019/questions/sheet1.lean | 24c3f46a57c9bd30182edc0893bcf1acd714f5da | [] | no_license | ImperialCollegeLondon/M40001_lean | 3a6a09298da395ab51bc220a535035d45bbe919b | 62a76fa92654c855af2b2fc2bef8e60acd16ccec | refs/heads/master | 1,666,750,403,259 | 1,665,771,117,000 | 1,665,771,117,000 | 209,141,835 | 115 | 12 | null | 1,640,270,596,000 | 1,568,749,174,000 | Lean | UTF-8 | Lean | false | false | 3,068 | lean | /- Math40001 : Introduction to university mathematics.
Problem Sheet 1, October 2019.
This is a Lean file. It can be read with the Lean theorem prover.
You can work on this file online at
https://tinyurl.com/Lean-M40001-Example-Sheet-1
or you can install Lean and its maths library following the
instructions at
https://github.com/leanprover-community/mathlib#installation
There are advantages to installing Lean on your own computer
(for example it's faster), but it's more hassle than
just using it online.
In the below, delete "sorry" and replace it with some
tactics which prove the result.
-/
/- Question 1.
Let P and Q be Propositions (that is, true/false statements).
Prove that P ∧ Q → Q ∧ P.
-/
lemma question_one (P Q : Prop) : P ∧ Q → Q ∧ P :=
begin
sorry
end
/-
For question 2, comment out one option (or just delete it)
and prove the other one.
-/
-- Part (a): is → symmetric?
lemma question_2a_true : ∀ P Q : Prop, (P → Q) → (Q → P) :=
begin
sorry
end
lemma question_2a_false : ¬ (∀ P Q : Prop, (P → Q) → (Q → P)) :=
begin
sorry
end
-- Part (b) : is ↔ symmetric?
lemma question_2b_true (P Q : Prop) : (P ↔ Q) → (Q ↔ P) :=
begin
sorry
end
lemma question_2b_false : ¬ (∀ P Q : Prop, (P ↔ Q) → (Q ↔ P)) :=
begin
sorry
end
/- Question 3.
Say P, Q and R are propositions, and we know:
1) if Q is true then P is true
2) If Q is false then R is false.
Can we deduce that R implies P? Comment out one
option and prove the other. Hint: if you're stuck,
"apply classical.by_contradiction" sometimes helps.
classical.by_contradiction is the theorem that ¬ ¬ P → P.
-/
lemma question_3_true (P Q R : Prop)
(h1 : Q → P)
(h2 : ¬ Q → ¬ R) :
R → P :=
begin
sorry
end
lemma question_3_false : ¬ (∀ P Q R : Prop,
(Q → P) →
(¬ Q → ¬ R) →
R → P) :=
begin
sorry
end
/- Question 4.
Your friend is thinking of three true-false statements P, Q and R,
and they tell you the following facts:
a) P → (Q ∧ R)
b) Q → (R ∧ ¬ P)
c) R → (P ∧ ¬ Q)
What can you deduce?
In this question you must *change the conclusion* to explain
what you deduced.
-/
lemma question_4 (P Q R : Prop)
(h1 : P → (Q ∧ R))
(h2 : Q → (R ∧ ¬ P))
(h3 : R → (P ∧ ¬ Q)) :
P ∨ Q -- replace this line with your conclusion
:=
begin
sorry
end
/- Question 5.
Say that for every integer n we have a proposition P n.
Say we know P n → P (n + 8) for all n, and
P n → P (n -3) for all n. Prove that the P n are either
all true, or all false.
This question is harder than the others.
-/
lemma question_5 (P : ℤ → Prop) (h8 : ∀ n, P n → P (n + 8)) (h3 : ∀ n, P n → P (n - 3)) :
(∀ n, P n) ∨ (∀ n, ¬ (P n)) :=
begin
sorry
end
/-
The first four of these questions can be solved using only the following
tactics:
intro
apply (or, better, refine)
left, right, cases, split
assumption (or, better, exact)
have,
simp
contradiction (or, better, false.elim)
The fifth question is harder.
-/
|
c9285bb8d68613deea92288b4dec1c1f749a8126 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/coe5.lean | 2ce8804958ff3119f9e95f8fc084194ecac9dcfc | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 310 | lean | open tactic
attribute [instance]
meta def expr_to_app : has_coe_to_fun expr :=
{ F := λ e, expr → expr,
coe := expr.app }
meta constants f a b : expr
check f a
check f a b
check f a b a
set_option pp.coercions false
check f a b a
set_option pp.all true
set_option pp.coercions true
check f a b
|
aa77634cacbb9abd1e53e41a5888e2160f47f38c | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/types/check_types.lean | ebe578192abc3f42162aedc0a7e9bca66c17ab1b | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 75 | lean | def n := 0
def b := tt
def s := "I love logic!"
#check n
#check b
#check s |
cdcf6d842eb9f32846b885668fe0b908e3df693a | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/docStr.lean | 44f710a63edae075d1fc23b6e24ac21c358b4d35 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 2,650 | lean | import Lean
/-- Foo structure is just a test -/
structure Foo where
/-- main name -/ name : String := "hello"
/-- documentation for the second field -/ val : Nat := 0
/-- documenting test axiom -/
axiom myAxiom : Nat
structure Boo (α : Type) where
/-- Boo constructor has a custom name -/
makeBoo ::
/-- Boo.x docString -/ x : Nat
y : Bool
/-- inductive datatype Tree documentation -/
inductive Tree (α : Type) where
/-- Tree.node documentation -/ | node : List (Tree α) → Tree α
/-- Tree.leaf stores the values -/ | leaf : α → Tree α
namespace Bla
/-- documenting definition in namespace -/
def test (x : Nat) : Nat :=
aux x + 1
where
/-- We can document 'where' functions too
... and indentation is stripped, even after an empty line. -/
aux x := x + 2
end Bla
def f (x : Nat) : IO Nat := do
let rec /-- let rec documentation at f -/ foo
| 0 => 1
| x+1 => foo x + 2
return foo x
def g (x : Nat) : Nat :=
let rec /-- let rec documentation at g -/ foo
| 0 => 1
| x+1 => foo x + 2
foo x
open Lean
def printDocString (declName : Name) : MetaM Unit := do
match (← findDocString? (← getEnv) declName) with
| some docStr => IO.println (repr docStr)
| none => IO.println s!"doc string for '{declName}' is not available"
def printDocStringTest : MetaM Unit := do
printDocString `Foo
printDocString `Foo.name
printDocString `Foo.val
printDocString `myAxiom
printDocString `Boo
printDocString `Boo.makeBoo
printDocString `Boo.x
printDocString `Boo.y
printDocString `Tree
printDocString `Tree.node
printDocString `Tree.leaf
printDocString `Bla.test
printDocString `Bla.test.aux
printDocString `f
printDocString `f.foo
printDocString `g
printDocString `g.foo
printDocString `optParam
printDocString `namedPattern
printDocString `Lean.Meta.forallTelescopeReducing
#eval printDocStringTest
def printRanges (declName : Name) : MetaM Unit := do
match (← findDeclarationRanges? declName) with
| some range => IO.println f!"{declName} :={Std.Format.indentD <| repr range}"
| none => IO.println s!"range for '{declName}' is not available"
def printRangesTest : MetaM Unit := do
printRanges `Foo
printRanges `Foo.name
printRanges `Foo.val
printRanges `myAxiom
printRanges `Boo
printRanges `Boo.makeBoo
printRanges `Boo.x
printRanges `Boo.y
printRanges `Tree
printRanges `Tree.rec
printRanges `Tree.casesOn
printRanges `Tree.node
printRanges `Tree.leaf
printRanges `Bla.test
printRanges `Bla.test.aux
printRanges `f
printRanges `f.foo
printRanges `g
printRanges `g.foo
#eval printRangesTest
|
3cd470898728716d7b14842f51c9508bb603bdf6 | ec62863c729b7eedee77b86d974f2c529fa79d25 | /16/b.lean | e0714fcfb25c4f6cd884c3ccda24b5203d637854 | [] | no_license | rwbarton/advent-of-lean-4 | 2ac9b17ba708f66051e3d8cd694b0249bc433b65 | 417c7e2718253ba7148c0279fcb251b6fc291477 | refs/heads/main | 1,675,917,092,057 | 1,609,864,581,000 | 1,609,864,581,000 | 317,700,289 | 24 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,089 | lean | def List.sum (xs : List Int) : Int := xs.foldl (· + ·) 0
@[reducible] def Ticket : Type := List Int
def somewhatValid (flds : List (String × List (Int × Int))) (t : Ticket) : Bool :=
t.all (λ n => flds.any (λ ⟨_, ps⟩ => ps.any (λ ⟨a, b⟩ => a ≤ n ∧ n ≤ b)))
def parseRange (str : String) : Int × Int :=
match str.splitOn "-" with
| [a, b] => (a.toInt!, b.toInt!)
| _ => panic! "invalid range"
def parseType (str : String) : String × List (Int × Int) :=
match str.splitOn ": " with
| [fld, vals] => (fld, (vals.splitOn " or ").map parseRange)
| _ => panic! "invalid type"
def parseTicket (str : String) : Ticket :=
(str.splitOn ",").map String.toInt!
def parse (str : String) : List (String × List (Int × Int)) × Ticket × List Ticket :=
match str.splitOn "\n\n" with
| [ty, your, nearby] =>
((ty.splitOn "\n").map parseType,
parseTicket ((your.splitOn "\n").getD 1 ""),
((nearby.splitOn "\n").drop 1).init.map parseTicket)
| _ => panic! "invalid input"
def matchable (fld : String × List (Int × Int)) (ts : Array Ticket) (i : Nat) : Bool :=
ts.all (λ t => match t.get? i with
| some n => fld.2.any (λ ⟨a, b⟩ => a ≤ n ∧ n ≤ b)
| _ => panic! "impossible")
def main : IO Unit := do
let input := parse (← IO.FS.readFile "a.in")
let goodTickets := (input.2.2.filter (somewhatValid input.1)).toArray
let mut matches := (List.range (goodTickets.get! 0).length).toArray.map (λ i => input.1.toArray.map (λ fld => matchable fld goodTickets i))
let mut assign := Array.mkArray input.1.length 0
let N := input.1.length
for _ in [0:N] do
for r in [0:N] do
let mut count := 0
let mut found := 0
for c in [0:N] do
if (matches.get! r).get! c then
count := count + 1
found := c
if count == 1 then
assign := assign.set! found r
for r' in [0:N] do
matches := matches.modify r' (λ m => m.set! found false)
break
let mut prod := 1
for ⟨i, fld⟩ in input.1.enum do
if "departure ".isPrefixOf fld.1 then
prod := prod * input.2.1.get! (assign.get! i)
IO.print s!"{prod}\n"
|
b37edfea9197d61de353b64c240fd518ac00144a | d29d82a0af640c937e499f6be79fc552eae0aa13 | /src/linear_algebra/matrix/determinant.lean | 5a5b36bef097c88d8eac406535415a3ec8a030ac | [
"Apache-2.0"
] | permissive | AbdulMajeedkhurasani/mathlib | 835f8a5c5cf3075b250b3737172043ab4fa1edf6 | 79bc7323b164aebd000524ebafd198eb0e17f956 | refs/heads/master | 1,688,003,895,660 | 1,627,788,521,000 | 1,627,788,521,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,186 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau, Chris Hughes, Tim Baanen
-/
import data.matrix.pequiv
import data.matrix.block
import data.fintype.card
import group_theory.perm.fin
import group_theory.perm.sign
import algebra.algebra.basic
import tactic.ring
import linear_algebra.alternating
import linear_algebra.pi
/-!
# Determinant of a matrix
This file defines the determinant of a matrix, `matrix.det`, and its essential properties.
## Main definitions
- `matrix.det`: the determinant of a square matrix, as a sum over permutations
- `matrix.det_row_multilinear`: the determinant, as an `alternating_map` in the rows of the matrix
## Main results
- `det_mul`: the determinant of `A ⬝ B` is the product of determinants
- `det_zero_of_row_eq`: the determinant is zero if there is a repeated row
- `det_block_diagonal`: the determinant of a block diagonal matrix is a product
of the blocks' determinants
## Implementation notes
It is possible to configure `simp` to compute determinants. See the file
`test/matrix.lean` for some examples.
-/
universes u v w z
open equiv equiv.perm finset function
namespace matrix
open_locale matrix big_operators
variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m]
variables {R : Type v} [comm_ring R]
local notation `ε` σ:max := ((sign σ : ℤ ) : R)
/-- `det` is an `alternating_map` in the rows of the matrix. -/
def det_row_multilinear : alternating_map R (n → R) R n :=
((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization
/-- The determinant of a matrix given by the Leibniz formula. -/
abbreviation det (M : matrix n n R) : R :=
det_row_multilinear M
lemma det_apply (M : matrix n n R) :
M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i :=
multilinear_map.alternatization_apply _ M
-- This is what the old definition was. We use it to avoid having to change the old proofs below
lemma det_apply' (M : matrix n n R) :
M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i :=
by simp [det_apply, units.smul_def]
@[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i :=
begin
rw det_apply',
refine (finset.sum_eq_single 1 _ _).trans _,
{ intros σ h1 h2,
cases not_forall.1 (mt equiv.ext h2) with x h3,
convert mul_zero _,
apply finset.prod_eq_zero,
{ change x ∈ _, simp },
exact if_neg h3 },
{ simp },
{ simp }
end
@[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_zero
@[simp] lemma det_one : det (1 : matrix n n R) = 1 :=
by rw [← diagonal_one]; simp [-diagonal_one]
@[simp]
lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 :=
by simp [det_apply]
lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 :=
begin
haveI : is_empty n := fintype.card_eq_zero_iff.mp h,
exact det_is_empty,
end
/-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element.
Although `unique` implies `decidable_eq` and `fintype`, the instances might
not be syntactically equal. Thus, we need to fill in the args explicitly. -/
@[simp]
lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) :
det A = A (default n) (default n) :=
by simp [det_apply, univ_unique]
lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) :
det A = A k k :=
begin
casesI fintype.card_eq_one_iff_nonempty_unique.mp h,
convert det_unique A,
end
lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) :
∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 :=
begin
obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j,
{ rw [← fintype.injective_iff_bijective, injective] at H,
push_neg at H,
exact H },
exact sum_involution
(λ σ _, σ * swap i j)
(λ σ _,
have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x),
from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]),
by simp [this, sign_swap hij, prod_mul_distrib])
(λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij)
(λ _ _, mem_univ _)
(λ σ _, mul_swap_involutive i j σ)
end
@[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N :=
calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum,
fintype.pi_finset_univ]; rw [finset.sum_comm]
... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n,
ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) :
eq.symm $ sum_subset (filter_subset _ _)
(λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij)
... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) :
sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _)
(λ _ _, rfl) (λ _ _ _ _ h, by injection h)
(λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩)
... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) :
by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc]
... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) :
sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _
(λ τ,
have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j,
by { rw ← σ⁻¹.prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] },
have h : ε σ * ε (τ * σ⁻¹) = ε τ :=
calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) :
by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] }
... = ε τ : by simp only [inv_mul_cancel_right],
by { simp_rw [equiv.coe_mul_right, h], simp only [this] }))
... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm]
instance : is_monoid_hom (det : matrix n n R → R) :=
{ map_one := det_one,
map_mul := det_mul }
/-- On square matrices, `mul_comm` applies under `det`. -/
lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) :=
by rw [det_mul, det_mul, mul_comm]
/-- On square matrices, `mul_left_comm` applies under `det`. -/
lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) :=
by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul]
/-- On square matrices, `mul_right_comm` applies under `det`. -/
lemma det_mul_right_comm (M N P : matrix m m R) :
det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) :=
by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul]
lemma det_units_conj (M : units (matrix m m R)) (N : matrix m m R) :
det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N :=
by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul]
lemma det_units_conj' (M : units (matrix m m R)) (N : matrix m m R) :
det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N
/-- Transposing a matrix preserves the determinant. -/
@[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det :=
begin
rw [det_apply', det_apply'],
refine fintype.sum_bijective _ inv_involutive.bijective _ _ _,
intros σ,
rw sign_inv,
congr' 1,
apply fintype.prod_equiv σ,
intros,
simp
end
/-- Permuting the columns changes the sign of the determinant. -/
lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det :=
((det_row_multilinear : alternating_map R (n → R) R n).map_perm M σ).trans
(by simp [units.smul_def])
/-- Permuting rows and columns with the same equivalence has no effect. -/
@[simp]
lemma det_minor_equiv_self (e : n ≃ m) (A : matrix m m R) :
det (A.minor e e) = det A :=
begin
rw [det_apply', det_apply'],
apply fintype.sum_equiv (equiv.perm_congr e),
intro σ,
rw equiv.perm.sign_perm_congr e σ,
congr' 1,
apply fintype.prod_equiv e,
intro i,
rw [equiv.perm_congr_apply, equiv.symm_apply_apply, minor_apply],
end
/-- Reindexing both indices along the same equivalence preserves the determinant.
For the `simp` version of this lemma, see `det_minor_equiv_self`; this one is unsuitable because
`matrix.reindex_apply` unfolds `reindex` first.
-/
lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A :=
det_minor_equiv_self e.symm A
/-- The determinant of a permutation matrix equals its sign. -/
@[simp] lemma det_permutation (σ : perm n) :
matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign :=
by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix,
det_permute, det_one, mul_one]
@[simp] lemma det_smul {A : matrix n n R} {c : R} : det (c • A) = c ^ fintype.card n * det A :=
calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul]
... = det (diagonal (λ _, c)) * det A : det_mul _ _
... = c ^ fintype.card n * det A : by simp [card_univ]
/-- Multiplying each row by a fixed `v i` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_row (v : n → R) (A : matrix n n R) :
det (λ i j, v j * A i j) = (∏ i, v i) * det A :=
calc det (λ i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] }
... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm]
/-- Multiplying each column by a fixed `v j` multiplies the determinant by
the product of the `v`s. -/
lemma det_mul_column (v : n → R) (A : matrix n n R) :
det (λ i j, v i * A i j) = (∏ i, v i) * det A :=
multilinear_map.map_smul_univ _ v A
@[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n :=
is_monoid_hom.map_pow det M n
section hom_map
variables {S : Type w} [comm_ring S]
lemma ring_hom.map_det {M : matrix n n R} {f : R →+* S} :
f M.det = matrix.det (f.map_matrix M) :=
by simp [matrix.det_apply', f.map_sum, f.map_prod]
lemma alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T]
{M : matrix n n S} {f : S →ₐ[R] T} :
f M.det = matrix.det ((f : S →+* T).map_matrix M) :=
by rw [← alg_hom.coe_to_ring_hom, ring_hom.map_det]
end hom_map
section det_zero
/-!
### `det_zero` section
Prove that a matrix with a repeated column has determinant equal to zero.
-/
lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_coord_zero i (funext h)
lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 :=
by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, }
variables {M : matrix n n R} {i j : n}
/-- If a matrix has a repeated row, the determinant will be zero. -/
theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 :=
(det_row_multilinear : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j
/-- If a matrix has a repeated column, the determinant will be zero. -/
theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 :=
by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij }
end det_zero
lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) :=
(det_row_multilinear : alternating_map R (n → R) R n).map_add M j u v
lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) :
det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_add],
simp [update_row_transpose, det_transpose]
end
lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_row M j $ s • u) = s * det (update_row M j u) :=
(det_row_multilinear : alternating_map R (n → R) R n).map_smul M j s u
lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) :
det (update_column M j $ s • u) = s * det (update_column M j u) :=
begin
rw [← det_transpose, ← update_row_transpose, det_update_row_smul],
simp [update_row_transpose, det_transpose]
end
section det_eq
/-! ### `det_eq` section
Lemmas showing the determinant is invariant under a variety of operations.
-/
lemma det_eq_of_eq_mul_det_one {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B :=
calc det A = det (B ⬝ C) : congr_arg _ hA
... = det B * det C : det_mul _ _
... = det B : by rw [hC, mul_one]
lemma det_eq_of_eq_det_one_mul {A B : matrix n n R}
(C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B :=
calc det A = det (C ⬝ B) : congr_arg _ hA
... = det C * det B : det_mul _ _
... = det B : by rw [hC, one_mul]
lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_row A i (A i + A j)) = det A :=
by simp [det_update_row_add,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) :
det (update_column A i (λ k, A k i + A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_self Aᵀ hij }
lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_row A i (A i + c • A j)) = det A :=
by simp [det_update_row_add, det_update_row_smul,
det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)]
lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) :
det (update_column A i (λ k, A k i + c • A k j)) = det A :=
by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A],
exact det_update_row_add_smul_self Aᵀ hij c }
lemma det_eq_of_forall_row_eq_smul_add_const_aux
{A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0)
(k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j),
det A = det B :=
begin
revert B,
refine s.induction_on _ _,
{ intros A c hs k hk A_eq,
have : ∀ i, c i = 0,
{ intros i,
specialize hs i,
contrapose! hs,
simp [hs] },
congr,
ext i j,
rw [A_eq, this, zero_mul, add_zero], },
{ intros i s hi ih B c hs k hk A_eq,
have hAi : A i = B i + c i • B k := funext (A_eq i),
rw [@ih (update_row B i (A i)) (function.update c i 0), hAi,
det_update_row_add_smul_self],
{ exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk },
{ intros i' hi',
rw function.update_apply,
split_ifs with hi'i, { refl },
{ exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } },
{ exact λ h, hk (finset.mem_insert_of_mem h) },
{ intros i' j',
rw [update_row_apply, function.update_apply],
split_ifs with hi'i,
{ simp [hi'i] },
rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } }
end
/-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_const
{A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0)
(A_eq : ∀ i j, A i j = B i j + c i * B k j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_const_aux c
(λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr
⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩)
k (finset.not_mem_erase k finset.univ) A_eq
lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) :
∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0)
{M N : matrix (fin n.succ) (fin n.succ) R}
(h0 : ∀ j, M 0 j = N 0 j)
(hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j),
det M = det N :=
begin
refine fin.induction _ (λ k ih, _) k;
intros c hc M N h0 hsucc,
{ congr,
ext i j,
refine fin.cases (h0 j) (λ i, _) i,
rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] },
set M' := update_row M k.succ (N k.succ) with hM',
have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ),
{ ext i j,
by_cases hi : i = k.succ,
{ simp [hi, hM', hsucc, update_row_self] },
rw [update_row_ne hi, hM', update_row_ne hi] },
have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne,
have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm,
rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)],
{ intros i hi,
rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi,
rw function.update_apply,
split_ifs with hik, { refl },
exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) },
{ rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] },
intros i j,
rw function.update_apply,
split_ifs with hik,
{ rw [zero_mul, add_zero, hM', hik, update_row_self] },
rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc],
by_cases hik2 : k < i,
{ simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] },
rw update_row_ne,
apply ne_of_lt,
rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt]
end
/-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/
lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ j, A 0 j = B 0 j)
(A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) :
det A = det B :=
det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c
(λ i hi, absurd hi (not_lt_of_ge (fin.le_last _)))
A_zero A_succ
/-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/
lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ}
{A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R)
(A_zero : ∀ i, A i 0 = B i 0)
(A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) :
det A = det B :=
by { rw [← det_transpose A, ← det_transpose B],
exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) }
end det_eq
@[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) :
(block_diagonal M).det = ∏ k, (M k).det :=
begin
-- Rewrite the determinants as a sum over permutations.
simp_rw [det_apply'],
-- The right hand side is a product of sums, rewrite it as a sum of products.
rw finset.prod_sum,
simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ],
-- We claim that the only permutations contributing to the sum are those that
-- preserve their second component.
let preserving_snd : finset (equiv.perm (n × o)) :=
finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd),
have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)},
σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd :=
λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩,
rw ← finset.sum_subset (finset.subset_univ preserving_snd) _,
-- And that these are in bijection with `o → equiv.perm m`.
rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _,
prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm,
{ intros σ _,
rw mem_preserving_snd,
rintros ⟨k, x⟩,
simp only [prod_congr_left_apply] },
{ intros σ _,
rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product, finset.prod_comm],
simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq,
prod_congr_left_apply] },
{ intros σ σ' _ _ eq,
ext x hx k,
simp only at eq,
have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) =
prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) :=
λ k x, by rw eq,
simp only [prod_congr_left_apply, prod.mk.inj_iff] at this,
exact (this k x).1 },
{ intros σ hσ,
rw mem_preserving_snd at hσ,
have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd,
{ intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } },
have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k),
{ intros k x,
ext,
{ simp only},
{ simp only [hσ] } },
have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k),
{ intros k x,
conv_lhs { rw ← perm.apply_inv_self σ (x, k) },
ext,
{ simp only [apply_inv_self] },
{ simp only [hσ'] } },
refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩,
{ intro x,
simp only [mk_apply_eq, inv_apply_self] },
{ intro x,
simp only [mk_inv_apply_eq, apply_inv_self] },
{ apply finset.mem_univ },
{ ext ⟨k, x⟩,
{ simp only [coe_fn_mk, prod_congr_left_apply] },
{ simp only [prod_congr_left_apply, hσ] } } },
{ intros σ _ hσ,
rw mem_preserving_snd at hσ,
obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ,
rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero],
rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne],
exact hkx }
end
/-- The determinant of a 2x2 block matrix with the lower-left block equal to zero is the product of
the determinants of the diagonal blocks. For the generalization to any number of blocks, see
`matrix.upper_block_triangular_det`. -/
lemma upper_two_block_triangular_det
(A : matrix m m R) (B : matrix m n R) (D : matrix n n R) :
(matrix.from_blocks A B 0 D).det = A.det * D.det :=
begin
classical,
simp_rw det_apply',
convert
(sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm,
rw sum_mul_sum,
simp_rw univ_product_univ,
rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm,
{ intros σ₁₂ h,
simp only [],
erw [set.mem_to_finset, monoid_hom.mem_range],
use σ₁₂,
simp only [sum_congr_hom_apply] },
{ simp only [forall_prop_of_true, prod.forall, mem_univ],
intros σ₁ σ₂,
rw fintype.prod_sum_type,
simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁,
from_blocks_apply₂₂],
have hr : ∀ (a b c d : R), (a * b) * (c * d) = a * c * (b * d), { intros, ac_refl },
rw hr,
congr,
rw [sign_sum_congr, units.coe_mul, int.cast_mul] },
{ intros σ₁ σ₂ h₁ h₂,
dsimp only [],
intro h,
have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x,
{ intro x, exact congr_fun (congr_arg to_fun h) x },
simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2,
ext,
{ exact h2.left x },
{ exact h2.right x }},
{ intros σ hσ,
erw [set.mem_to_finset, monoid_hom.mem_range] at hσ,
obtain ⟨σ₁₂, hσ₁₂⟩ := hσ,
use σ₁₂,
rw ←hσ₁₂,
simp },
{ intros σ hσ hσn,
have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)),
{ by_contradiction,
rw set.mem_to_finset at hσn,
apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn,
rintros x ⟨a, ha⟩,
rw [←ha], exact h a },
obtain ⟨a, ha⟩ := not_forall.mp h1,
cases hx : σ (sum.inl a) with a2 b,
{ have hn := (not_exists.mp ha) a2,
exact absurd hx.symm hn },
{ rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero],
rw [hx, from_blocks_apply₂₁], refl }}
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/
lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 *
det (A.minor i.succ_above fin.succ) :=
begin
rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ],
simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.minor],
refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i),
{ simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum,
equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul,
equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true,
equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero,
mul_smul_comm] },
-- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into
-- `perm (fin n.succ)` than the determinant of the submatrix we want,
-- permute `A` so that we get the correct one.
have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign,
{ simp [fin.sign_cycle_range] },
rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _),
← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum],
-- now we just need to move the corresponding parts to the same place
refine finset.sum_congr rfl (λ σ _, _),
rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)],
calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i'
= ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 *
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range,
equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ]
... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) •
∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) :
by simp only [mul_assoc, mul_comm, neg_mul_eq_neg_mul_symm, one_mul, gsmul_eq_mul, neg_inj,
neg_smul, fin.succ_above_cycle_range],
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/
lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) :
det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j *
det (A.minor fin.succ j.succ_above) :=
by { rw [← det_transpose A, det_succ_column_zero],
refine finset.sum_congr rfl (λ i _, _),
rw [← det_transpose],
simp only [transpose_apply, transpose_minor, transpose_transpose] }
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/
lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) :
det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.minor i.succ_above j.succ_above) :=
begin
simp_rw [pow_add, mul_assoc, ← mul_sum],
have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A,
{ calc det A = ↑((-1 : units ℤ) ^ (i : ℕ) * (-1 : units ℤ) ^ (i : ℕ) : units ℤ) * det A :
by simp
... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A :
by simp [-int.units_mul_self] },
rw [this, mul_assoc],
congr,
rw [← det_permute, det_succ_row_zero],
refine finset.sum_congr rfl (λ j _, _),
rw [mul_assoc, matrix.minor, matrix.minor],
congr,
{ rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] },
{ ext i' j',
rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] },
end
/-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/
lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) :
det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j *
det (A.minor i.succ_above j.succ_above) :=
by { rw [← det_transpose, det_succ_row _ j],
refine finset.sum_congr rfl (λ i _, _),
rw [add_comm, ← det_transpose, transpose_apply, transpose_minor, transpose_transpose] }
end matrix
|
ad962230a6ca6a05cb1b9c8625011b51c2d5ed14 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Elab/Tactic/BuiltinTactic.lean | ea220167091d641426f8eb4083c84b94eff071d1 | [
"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 | 16,362 | 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.Assumption
import Lean.Meta.Tactic.Contradiction
import Lean.Meta.Tactic.Refl
import Lean.Elab.Binders
import Lean.Elab.Open
import Lean.Elab.SetOption
import Lean.Elab.Tactic.Basic
import Lean.Elab.Tactic.ElabTerm
namespace Lean.Elab.Tactic
open Meta
open Parser.Tactic
@[builtin_tactic withAnnotateState] def evalWithAnnotateState : Tactic
| `(tactic| with_annotate_state $stx $t) =>
withTacticInfoContext stx (evalTactic t)
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.«done»] def evalDone : Tactic := fun _ =>
done
@[builtin_tactic seq1] def evalSeq1 : Tactic := fun stx => do
let args := stx[0].getArgs
for i in [:args.size] do
if i % 2 == 0 then
evalTactic args[i]!
else
saveTacticInfoForToken args[i]! -- add `TacticInfo` node for `;`
@[builtin_tactic paren] def evalParen : Tactic := fun stx =>
evalTactic stx[1]
def isCheckpointableTactic (arg : Syntax) : TacticM Bool := do
-- TODO: make it parametric
let kind := arg.getKind
return kind == ``Lean.Parser.Tactic.save
/--
Takes a `sepByIndent tactic "; "`, and inserts `checkpoint` blocks for `save` tactics.
Input:
```
a
b
save
c
d
save
e
```
Output:
```
checkpoint
a
b
save
checkpoint
c
d
save
e
```
-/
-- Note that we need to preserve the separators to show the right goals after semicolons.
def addCheckpoints (stx : Syntax) : TacticM Syntax := do
if !(← stx.getSepArgs.anyM isCheckpointableTactic) then return stx
-- do not checkpoint checkpointable tactic by itself to prevent infinite recursion
-- TODO: rethink approach if we add non-trivial checkpointable tactics
if stx.getNumArgs <= 2 then return stx
let mut currentCheckpointBlock := #[]
let mut output := #[]
-- `+ 1` to account for optional trailing separator
for i in [:(stx.getArgs.size + 1) / 2] do
let tac := stx[2*i]
let sep? := stx.getArgs[2*i+1]?
if (← isCheckpointableTactic tac) then
let checkpoint : Syntax :=
mkNode ``checkpoint #[
mkAtomFrom tac "checkpoint",
mkNode ``tacticSeq #[
mkNode ``tacticSeq1Indented #[
-- HACK: null node is not a valid tactic, but prevents infinite loop
mkNullNode (currentCheckpointBlock.push (mkNullNode #[tac]))
]
]
]
currentCheckpointBlock := #[]
output := output.push checkpoint
if let some sep := sep? then output := output.push sep
else
currentCheckpointBlock := currentCheckpointBlock.push tac
if let some sep := sep? then currentCheckpointBlock := currentCheckpointBlock.push sep
output := output ++ currentCheckpointBlock
return stx.setArgs output
/-- Evaluate `sepByIndent tactic "; " -/
def evalSepByIndentTactic (stx : Syntax) : TacticM Unit := do
let stx ← addCheckpoints stx
for arg in stx.getArgs, i in [:stx.getArgs.size] do
if i % 2 == 0 then
evalTactic arg
else
saveTacticInfoForToken arg
@[builtin_tactic tacticSeq1Indented] def evalTacticSeq1Indented : Tactic := fun stx =>
evalSepByIndentTactic stx[0]
@[builtin_tactic tacticSeqBracketed] def evalTacticSeqBracketed : Tactic := fun stx => do
let initInfo ← mkInitialTacticInfo stx[0]
withRef stx[2] <| closeUsingOrAdmit do
-- save state before/after entering focus on `{`
withInfoContext (pure ()) initInfo
evalSepByIndentTactic stx[1]
@[builtin_tactic cdot] def evalTacticCDot : Tactic := fun stx => do
-- adjusted copy of `evalTacticSeqBracketed`; we used to use the macro
-- ``| `(tactic| $cdot:cdotTk $tacs) => `(tactic| {%$cdot ($tacs) }%$cdot)``
-- but the token antiquotation does not copy trailing whitespace, leading to
-- differences in the goal display (#2153)
let initInfo ← mkInitialTacticInfo stx[0]
withRef stx[0] <| closeUsingOrAdmit do
-- save state before/after entering focus on `·`
withInfoContext (pure ()) initInfo
evalSepByIndentTactic stx[1]
@[builtin_tactic Parser.Tactic.focus] def evalFocus : Tactic := fun stx => do
let mkInfo ← mkInitialTacticInfo stx[0]
focus do
-- show focused state on `focus`
withInfoContext (pure ()) mkInfo
evalTactic stx[1]
private def getOptRotation (stx : Syntax) : Nat :=
if stx.isNone then 1 else stx[0].toNat
@[builtin_tactic Parser.Tactic.rotateLeft] def evalRotateLeft : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateLeft n
@[builtin_tactic Parser.Tactic.rotateRight] def evalRotateRight : Tactic := fun stx => do
let n := getOptRotation stx[1]
setGoals <| (← getGoals).rotateRight n
@[builtin_tactic Parser.Tactic.open] def evalOpen : Tactic := fun stx => do
let `(tactic| open $decl in $tac) := stx | throwUnsupportedSyntax
try
pushScope
let openDecls ← elabOpenDecl decl
withTheReader Core.Context (fun ctx => { ctx with openDecls := openDecls }) do
evalTactic tac
finally
popScope
@[builtin_tactic Parser.Tactic.set_option] def elabSetOption : Tactic := fun stx => do
let options ← Elab.elabSetOption stx[1] stx[2]
withTheReader Core.Context (fun ctx => { ctx with maxRecDepth := maxRecDepth.get options, options := options }) do
evalTactic stx[4]
@[builtin_tactic Parser.Tactic.allGoals] def evalAllGoals : Tactic := fun stx => do
let mvarIds ← getGoals
let mut mvarIdsNew := #[]
for mvarId in mvarIds do
unless (← mvarId.isAssigned) do
setGoals [mvarId]
try
evalTactic stx[1]
mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)
catch ex =>
if (← read).recover then
logException ex
mvarIdsNew := mvarIdsNew.push mvarId
else
throw ex
setGoals mvarIdsNew.toList
@[builtin_tactic Parser.Tactic.anyGoals] def evalAnyGoals : Tactic := fun stx => do
let mvarIds ← getGoals
let mut mvarIdsNew := #[]
let mut succeeded := false
for mvarId in mvarIds do
unless (← mvarId.isAssigned) do
setGoals [mvarId]
try
evalTactic stx[1]
mvarIdsNew := mvarIdsNew ++ (← getUnsolvedGoals)
succeeded := true
catch _ =>
mvarIdsNew := mvarIdsNew.push mvarId
unless succeeded do
throwError "failed on all goals"
setGoals mvarIdsNew.toList
@[builtin_tactic tacticSeq] def evalTacticSeq : Tactic := fun stx =>
evalTactic stx[0]
partial def evalChoiceAux (tactics : Array Syntax) (i : Nat) : TacticM Unit :=
if h : i < tactics.size then
let tactic := tactics.get ⟨i, h⟩
catchInternalId unsupportedSyntaxExceptionId
(evalTactic tactic)
(fun _ => evalChoiceAux tactics (i+1))
else
throwUnsupportedSyntax
@[builtin_tactic choice] def evalChoice : Tactic := fun stx =>
evalChoiceAux stx.getArgs 0
@[builtin_tactic skip] def evalSkip : Tactic := fun _ => pure ()
@[builtin_tactic unknown] def evalUnknown : Tactic := fun stx => do
addCompletionInfo <| CompletionInfo.tactic stx (← getGoals)
@[builtin_tactic failIfSuccess] def evalFailIfSuccess : Tactic := fun stx =>
Term.withoutErrToSorry <| withoutRecover do
let tactic := stx[1]
if (← try evalTactic tactic; pure true catch _ => pure false) then
throwError "tactic succeeded"
@[builtin_tactic traceState] def evalTraceState : Tactic := fun _ => do
let gs ← getUnsolvedGoals
addRawTrace (goalsToMessageData gs)
@[builtin_tactic traceMessage] def evalTraceMessage : Tactic := fun stx => do
match stx[1].isStrLit? with
| none => throwIllFormedSyntax
| some msg => withRef stx[0] <| addRawTrace msg
@[builtin_tactic Lean.Parser.Tactic.assumption] def evalAssumption : Tactic := fun _ =>
liftMetaTactic fun mvarId => do mvarId.assumption; pure []
@[builtin_tactic Lean.Parser.Tactic.contradiction] def evalContradiction : Tactic := fun _ =>
liftMetaTactic fun mvarId => do mvarId.contradiction; pure []
@[builtin_tactic Lean.Parser.Tactic.refl] def evalRefl : Tactic := fun _ =>
liftMetaTactic fun mvarId => do mvarId.refl; pure []
@[builtin_tactic Lean.Parser.Tactic.intro] def evalIntro : Tactic := fun stx => do
match stx with
| `(tactic| intro) => introStep none `_
| `(tactic| intro $h:ident) => introStep h h.getId
| `(tactic| intro _%$tk) => introStep tk `_
/- Type ascription -/
| `(tactic| intro ($h:ident : $type:term)) => introStep h h.getId type
/- We use `@h` at the match-discriminant to disable the implicit lambda feature -/
| `(tactic| intro $pat:term) => evalTactic (← `(tactic| intro h; match @h with | $pat:term => ?_; try clear h))
| `(tactic| intro $h:term $hs:term*) => evalTactic (← `(tactic| intro $h:term; intro $hs:term*))
| _ => throwUnsupportedSyntax
where
introStep (ref : Option Syntax) (n : Name) (typeStx? : Option Syntax := none) : TacticM Unit := do
let fvarId ← liftMetaTacticAux fun mvarId => do
let (fvarId, mvarId) ← mvarId.intro n
pure (fvarId, [mvarId])
if let some typeStx := typeStx? then
withMainContext do
let type ← Term.withSynthesize (mayPostpone := true) <| Term.elabType typeStx
let fvar := mkFVar fvarId
let fvarType ← inferType fvar
unless (← isDefEqGuarded type fvarType) do
throwError "type mismatch at `intro {fvar}`{← mkHasTypeButIsExpectedMsg fvarType type}"
liftMetaTactic fun mvarId => return [← mvarId.replaceLocalDeclDefEq fvarId type]
if let some stx := ref then
withMainContext do
Term.addLocalVarInfo stx (mkFVar fvarId)
@[builtin_tactic Lean.Parser.Tactic.introMatch] def evalIntroMatch : Tactic := fun stx => do
let matchAlts := stx[1]
let stxNew ← liftMacroM <| Term.expandMatchAltsIntoMatchTactic stx matchAlts
withMacroExpansion stx stxNew <| evalTactic stxNew
@[builtin_tactic «intros»] def evalIntros : Tactic := fun stx =>
match stx with
| `(tactic| intros) => liftMetaTactic fun mvarId => do
let (_, mvarId) ← mvarId.intros
return [mvarId]
| `(tactic| intros $ids*) => do
let fvars ← liftMetaTacticAux fun mvarId => do
let (fvars, mvarId) ← mvarId.introN ids.size (ids.map getNameOfIdent').toList
return (fvars, [mvarId])
withMainContext do
for stx in ids, fvar in fvars do
Term.addLocalVarInfo stx (mkFVar fvar)
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.revert] def evalRevert : Tactic := fun stx =>
match stx with
| `(tactic| revert $hs*) => do
let (_, mvarId) ← (← getMainGoal).revert (← getFVarIds hs)
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.clear] def evalClear : Tactic := fun stx =>
match stx with
| `(tactic| clear $hs*) => do
let fvarIds ← getFVarIds hs
let fvarIds ← withMainContext <| sortFVarIds fvarIds
for fvarId in fvarIds.reverse do
withMainContext do
let mvarId ← (← getMainGoal).clear fvarId
replaceMainGoal [mvarId]
| _ => throwUnsupportedSyntax
def forEachVar (hs : Array Syntax) (tac : MVarId → FVarId → MetaM MVarId) : TacticM Unit := do
for h in hs do
withMainContext do
let fvarId ← getFVarId h
let mvarId ← tac (← getMainGoal) fvarId
replaceMainGoal [mvarId]
@[builtin_tactic Lean.Parser.Tactic.subst] def evalSubst : Tactic := fun stx =>
match stx with
| `(tactic| subst $hs*) => forEachVar hs Meta.subst
| _ => throwUnsupportedSyntax
@[builtin_tactic Lean.Parser.Tactic.substVars] def evalSubstVars : Tactic := fun _ =>
liftMetaTactic fun mvarId => return [← substVars mvarId]
/--
Searches for a metavariable `g` s.t. `tag` is its exact name.
If none then searches for a metavariable `g` s.t. `tag` is a suffix of its name.
If none, then it searches for a metavariable `g` s.t. `tag` is a prefix of its name. -/
private def findTag? (mvarIds : List MVarId) (tag : Name) : TacticM (Option MVarId) := do
match (← mvarIds.findM? fun mvarId => return tag == (← mvarId.getDecl).userName) with
| some mvarId => return mvarId
| none =>
match (← mvarIds.findM? fun mvarId => return tag.isSuffixOf (← mvarId.getDecl).userName) with
| some mvarId => return mvarId
| none => mvarIds.findM? fun mvarId => return tag.isPrefixOf (← mvarId.getDecl).userName
def renameInaccessibles (mvarId : MVarId) (hs : TSyntaxArray ``binderIdent) : TacticM MVarId := do
if hs.isEmpty then
return mvarId
else
let mvarDecl ← mvarId.getDecl
let mut lctx := mvarDecl.lctx
let mut hs := hs
let mut info := #[]
let mut found : NameSet := {}
let n := lctx.numIndices
for i in [:n] do
let j := n - i - 1
match lctx.getAt? j with
| none => pure ()
| some localDecl =>
if localDecl.userName.hasMacroScopes || found.contains localDecl.userName then
if let `(binderIdent| $h:ident) := hs.back then
let newName := h.getId
lctx := lctx.setUserName localDecl.fvarId newName
info := info.push (localDecl.fvarId, h)
hs := hs.pop
if hs.isEmpty then
break
found := found.insert localDecl.userName
unless hs.isEmpty do
logError m!"too many variable names provided"
let mvarNew ← mkFreshExprMVarAt lctx mvarDecl.localInstances mvarDecl.type MetavarKind.syntheticOpaque mvarDecl.userName
withSaveInfoContext <| mvarNew.mvarId!.withContext do
for (fvarId, stx) in info do
Term.addLocalVarInfo stx (mkFVar fvarId)
mvarId.assign mvarNew
return mvarNew.mvarId!
private def getCaseGoals (tag : TSyntax ``binderIdent) : TacticM (MVarId × List MVarId) := do
let gs ← getUnsolvedGoals
let g ← if let `(binderIdent| $tag:ident) := tag then
let tag := tag.getId
let some g ← findTag? gs tag | throwError "tag not found"
pure g
else
getMainGoal
return (g, gs.erase g)
@[builtin_tactic «case»] def evalCase : Tactic
| stx@`(tactic| case $[$tag $hs*]|* =>%$arr $tac:tacticSeq) =>
for tag in tag, hs in hs do
let (g, gs) ← getCaseGoals tag
let g ← renameInaccessibles g hs
setGoals [g]
g.setTag Name.anonymous
withCaseRef arr tac do
closeUsingOrAdmit (withTacticInfoContext stx (evalTactic tac))
setGoals gs
| _ => throwUnsupportedSyntax
@[builtin_tactic «case'»] def evalCase' : Tactic
| `(tactic| case' $[$tag $hs*]|* =>%$arr $tac:tacticSeq) => do
let mut acc := #[]
for tag in tag, hs in hs do
let (g, gs) ← getCaseGoals tag
let g ← renameInaccessibles g hs
let mvarTag ← g.getTag
setGoals [g]
withCaseRef arr tac (evalTactic tac)
let gs' ← getUnsolvedGoals
if let [g'] := gs' then
g'.setTag mvarTag
acc := acc ++ gs'
setGoals gs
setGoals (acc.toList ++ (← getGoals))
| _ => throwUnsupportedSyntax
@[builtin_tactic «renameI»] def evalRenameInaccessibles : Tactic
| `(tactic| rename_i $hs*) => do replaceMainGoal [← renameInaccessibles (← getMainGoal) hs]
| _ => throwUnsupportedSyntax
@[builtin_tactic «first»] partial def evalFirst : Tactic := fun stx => do
let tacs := stx[1].getArgs
if tacs.isEmpty then throwUnsupportedSyntax
loop tacs 0
where
loop (tacs : Array Syntax) (i : Nat) :=
if i == tacs.size - 1 then
evalTactic tacs[i]![1]
else
evalTactic tacs[i]![1] <|> loop tacs (i+1)
@[builtin_tactic «fail»] def evalFail : Tactic := fun stx => do
let goals ← getGoals
let goalsMsg := MessageData.joinSep (goals.map MessageData.ofGoal) m!"\n\n"
match stx with
| `(tactic| fail) => throwError "tactic 'fail' failed\n{goalsMsg}"
| `(tactic| fail $msg:str) => throwError "{msg.getString}\n{goalsMsg}"
| _ => throwUnsupportedSyntax
@[builtin_tactic Parser.Tactic.dbgTrace] def evalDbgTrace : Tactic := fun stx => do
match stx[1].isStrLit? with
| none => throwIllFormedSyntax
| some msg => dbg_trace msg
@[builtin_tactic sleep] def evalSleep : Tactic := fun stx => do
match stx[1].isNatLit? with
| none => throwIllFormedSyntax
| some ms => IO.sleep ms.toUInt32
end Lean.Elab.Tactic
|
e37272d114c77bf87af18f52526b00a89bec73e4 | 491068d2ad28831e7dade8d6dff871c3e49d9431 | /tests/lean/errors.lean | 18a8d78e9f6f17ffc2cfb62f538449593a9d25e3 | [
"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 | 530 | lean | namespace foo
definition tst1 : nat → nat → nat :=
a + b -- ERROR
check tst1
definition tst2 : nat → nat → nat :=
begin
intro a,
intro b,
cases add wth (a, b), -- ERROR
exact a,
exact b,
end
section
parameter A : Type
definition tst3 : A → A → A :=
begin
intro a,
apply b, -- ERROR
exact a
end
check tst3
end
end foo
open nat
noncomputable definition bla : nat :=
foo.tst1 0 0 + foo.tst2 0 0 + foo.tst3 nat 1 1
check foo.tst1
check foo.tst2
check foo.tst3
|
bd3bebaeb936a47ff76a920e826cceee891abbcf | 8e6cad62ec62c6c348e5faaa3c3f2079012bdd69 | /src/data/polynomial/erase_lead.lean | d3e51bd50485ad065605042ff0c6d72cc76fffd4 | [
"Apache-2.0"
] | permissive | benjamindavidson/mathlib | 8cc81c865aa8e7cf4462245f58d35ae9a56b150d | fad44b9f670670d87c8e25ff9cdf63af87ad731e | refs/heads/master | 1,679,545,578,362 | 1,615,343,014,000 | 1,615,343,014,000 | 312,926,983 | 0 | 0 | Apache-2.0 | 1,615,360,301,000 | 1,605,399,418,000 | Lean | UTF-8 | Lean | false | false | 6,952 | lean | /-
Copyright (c) 2020 Damiano Testa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Damiano Testa
-/
import data.polynomial.degree
import data.polynomial.degree.trailing_degree
/-!
# Erase the leading term of a univariate polynomial
## Definition
* `erase_lead f`: the polynomial `f - leading term of f`
`erase_lead` serves as reduction step in an induction, shaving off one monomial from a polynomial.
The definition is set up so that it does not mention subtraction in the definition,
and thus works for polynomials over semirings as well as rings.
-/
noncomputable theory
open_locale classical
open polynomial finsupp finset
namespace polynomial
variables {R : Type*} [semiring R] {f : polynomial R}
/-- `erase_lead f` for a polynomial `f` is the polynomial obtained by
subtracting from `f` the leading term of `f`. -/
def erase_lead (f : polynomial R) : polynomial R :=
finsupp.erase f.nat_degree f
section erase_lead
lemma erase_lead_support (f : polynomial R) :
f.erase_lead.support = f.support.erase f.nat_degree :=
-- `rfl` fails because LHS uses `nat.decidable_eq` but RHS is classical.
by convert rfl
lemma erase_lead_coeff (i : ℕ) :
f.erase_lead.coeff i = if i = f.nat_degree then 0 else f.coeff i :=
-- `rfl` fails because LHS uses `nat.decidable_eq` but RHS is classical.
by convert rfl
@[simp] lemma erase_lead_coeff_nat_degree : f.erase_lead.coeff f.nat_degree = 0 :=
finsupp.erase_same
lemma erase_lead_coeff_of_ne (i : ℕ) (hi : i ≠ f.nat_degree) :
f.erase_lead.coeff i = f.coeff i :=
finsupp.erase_ne hi
@[simp] lemma erase_lead_zero : erase_lead (0 : polynomial R) = 0 :=
finsupp.erase_zero _
@[simp] lemma erase_lead_add_monomial_nat_degree_leading_coeff (f : polynomial R) :
f.erase_lead + monomial f.nat_degree f.leading_coeff = f :=
begin
ext i,
simp only [erase_lead_coeff, coeff_monomial, coeff_add, @eq_comm _ _ i],
split_ifs with h,
{ subst i, simp only [leading_coeff, zero_add] },
{ exact add_zero _ }
end
@[simp] lemma erase_lead_add_C_mul_X_pow (f : polynomial R) :
f.erase_lead + (C f.leading_coeff) * X ^ f.nat_degree = f :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_add_monomial_nat_degree_leading_coeff]
@[simp] lemma self_sub_monomial_nat_degree_leading_coeff {R : Type*} [ring R] (f : polynomial R) :
f - monomial f.nat_degree f.leading_coeff = f.erase_lead :=
(eq_sub_iff_add_eq.mpr (erase_lead_add_monomial_nat_degree_leading_coeff f)).symm
@[simp] lemma self_sub_C_mul_X_pow {R : Type*} [ring R] (f : polynomial R) :
f - (C f.leading_coeff) * X ^ f.nat_degree = f.erase_lead :=
by rw [C_mul_X_pow_eq_monomial, self_sub_monomial_nat_degree_leading_coeff]
lemma erase_lead_ne_zero (f0 : 2 ≤ f.support.card) : erase_lead f ≠ 0 :=
begin
rw [ne.def, ← finsupp.card_support_eq_zero, erase_lead_support],
exact (zero_lt_one.trans_le $ (nat.sub_le_sub_right f0 1).trans
finset.pred_card_le_card_erase).ne.symm
end
@[simp] lemma nat_degree_not_mem_erase_lead_support : f.nat_degree ∉ (erase_lead f).support :=
by convert not_mem_erase _ _
lemma ne_nat_degree_of_mem_erase_lead_support {a : ℕ} (h : a ∈ (erase_lead f).support) :
a ≠ f.nat_degree :=
by { rintro rfl, exact nat_degree_not_mem_erase_lead_support h }
lemma erase_lead_support_card_lt (h : f ≠ 0) : (erase_lead f).support.card < f.support.card :=
begin
rw erase_lead_support,
exact card_lt_card (erase_ssubset $ nat_degree_mem_support_of_nonzero h)
end
lemma erase_lead_card_support {c : ℕ} (fc : f.support.card = c) :
f.erase_lead.support.card = c - 1 :=
begin
by_cases f0 : f = 0,
{ rw [← fc, f0, erase_lead_zero, support_zero, card_empty] },
{ rw [erase_lead_support, card_erase_of_mem (nat_degree_mem_support_of_nonzero f0), fc],
exact c.pred_eq_sub_one },
end
lemma erase_lead_card_support' {c : ℕ} (fc : f.support.card = c + 1) :
f.erase_lead.support.card = c :=
erase_lead_card_support fc
@[simp] lemma erase_lead_monomial (i : ℕ) (r : R) :
erase_lead (monomial i r) = 0 :=
begin
by_cases hr : r = 0,
{ subst r, simp only [monomial_zero_right, erase_lead_zero] },
{ rw [erase_lead, nat_degree_monomial _ _ hr], exact erase_single }
end
@[simp] lemma erase_lead_C (r : R) : erase_lead (C r) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X : erase_lead (X : polynomial R) = 0 :=
erase_lead_monomial _ _
@[simp] lemma erase_lead_X_pow (n : ℕ) : erase_lead (X ^ n : polynomial R) = 0 :=
by rw [X_pow_eq_monomial, erase_lead_monomial]
@[simp] lemma erase_lead_C_mul_X_pow (r : R) (n : ℕ) : erase_lead (C r * X ^ n) = 0 :=
by rw [C_mul_X_pow_eq_monomial, erase_lead_monomial]
lemma erase_lead_degree_le : (erase_lead f).degree ≤ f.degree :=
begin
rw degree_le_iff_coeff_zero,
intros i hi,
rw erase_lead_coeff,
split_ifs with h, { refl },
apply coeff_eq_zero_of_degree_lt hi
end
lemma erase_lead_nat_degree_le : (erase_lead f).nat_degree ≤ f.nat_degree :=
nat_degree_le_nat_degree erase_lead_degree_le
lemma erase_lead_nat_degree_lt (f0 : 2 ≤ f.support.card) :
(erase_lead f).nat_degree < f.nat_degree :=
lt_of_le_of_ne erase_lead_nat_degree_le $ ne_nat_degree_of_mem_erase_lead_support $
nat_degree_mem_support_of_nonzero $ erase_lead_ne_zero f0
lemma erase_lead_nat_degree_lt_or_erase_lead_eq_zero (f : polynomial R) :
(erase_lead f).nat_degree < f.nat_degree ∨ f.erase_lead = 0 :=
begin
by_cases h : f.support.card ≤ 1,
{ right,
rw ← C_mul_X_pow_eq_self h,
simp },
{ left,
apply erase_lead_nat_degree_lt (lt_of_not_ge h) }
end
end erase_lead
/-- An induction lemma for polynomials. It takes a natural number `N` as a parameter, that is
required to be at least as big as the `nat_degree` of the polynomial. This is useful to prove
results where you want to change each term in a polynomial to something else depending on the
`nat_degree` of the polynomial itself and not on the specific `nat_degree` of each term. -/
lemma induction_with_nat_degree_le {R : Type*} [semiring R] {P : polynomial R → Prop} (N : ℕ)
(P_0 : P 0)
(P_C_mul_pow : ∀ n : ℕ, ∀ r : R, r ≠ 0 → n ≤ N → P (C r * X ^ n))
(P_C_add : ∀ f g : polynomial R, f.nat_degree ≤ N → g.nat_degree ≤ N → P f → P g → P (f + g)) :
∀ f : polynomial R, f.nat_degree ≤ N → P f :=
begin
intros f df,
generalize' hd : card f.support = c,
revert f,
induction c with c hc,
{ exact λ f df f0, by rwa (finsupp.support_eq_empty.mp (card_eq_zero.mp f0)) },
{ intros f df f0,
rw ← erase_lead_add_C_mul_X_pow f,
refine P_C_add f.erase_lead _ (erase_lead_nat_degree_le.trans df) _ _ _,
{ exact (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree).trans df },
{ exact hc _ (erase_lead_nat_degree_le.trans df) (erase_lead_card_support f0) },
{ refine P_C_mul_pow _ _ _ df,
rw [ne.def, leading_coeff_eq_zero],
rintro rfl,
exact not_le.mpr c.succ_pos f0.ge } }
end
end polynomial
|
4213649054a609d94152277c55bfe172c2c17fc9 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/convex/integral.lean | cf8cfc070257358e1e53e81bd3bf6ca345a67740 | [
"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 | 7,705 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.convex.basic
import measure_theory.set_integral
/-!
# Jensen's inequality for integrals
In this file we prove four theorems:
* `convex.smul_integral_mem`: if `μ` is a non-zero finite measure on `α`, `s` is a convex closed set
in `E`, and `f` is an integrable function sending `μ`-a.e. points to `s`, then the average value
of `f` belongs to `s`: `(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem`
for a finite sum version of this lemma.
* `convex.integral_mem`: if `μ` is a probability measure on `α`, `s` is a convex closed set in `E`,
and `f` is an integrable function sending `μ`-a.e. points to `s`, then the expected value of `f`
belongs to `s`: `∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this
lemma.
* `convex_on.map_smul_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and
continuous on a convex closed set `s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is
a function sending `μ`-a.e. points to `s`, then the value of `g` at the average value of `f` is
less than or equal to the average value of `g ∘ f` provided that both `f` and `g ∘ f` are
integrable. See also `convex.map_center_mass_le` for a finite sum version of this lemma.
* `convex_on.map_integral_le`: Jensen's inequality: if a function `g : E → ℝ` is convex and
continuous on a convex closed set `s`, `μ` is a probability measure on `α`, and `f : α → E` is a
function sending `μ`-a.e. points to `s`, then the value of `g` at the expected value of `f` is
less than or equal to the expected value of `g ∘ f` provided that both `f` and `g ∘ f` are
integrable. See also `convex.map_sum_le` for a finite sum version of this lemma.
## Tags
convex, integral, center mass, Jensen's inequality
-/
open measure_theory set filter
open_locale topological_space big_operators
variables {α E : Type*} [measurable_space α] {μ : measure α}
[normed_group E] [normed_space ℝ E] [complete_space E]
[topological_space.second_countable_topology E] [measurable_space E] [borel_space E]
private lemma convex.smul_integral_mem_of_measurable
[finite_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s)
(hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) (hfm : measurable f) :
(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s :=
begin
unfreezingI { rcases eq_empty_or_nonempty s with rfl|⟨y₀, h₀⟩ },
{ refine (hμ _).elim, simpa using hfs },
rw ← hsc.closure_eq at hfs,
have hc : integrable (λ _, y₀) μ := integrable_const _,
set F : ℕ → simple_func α E := simple_func.approx_on f hfm s y₀ h₀,
have : tendsto (λ n, (F n).integral μ) at_top (𝓝 $ ∫ x, f x ∂μ),
{ simp only [simple_func.integral_eq_integral _
(simple_func.integrable_approx_on hfm hfi h₀ hc _)],
exact tendsto_integral_of_L1 _ hfi
(eventually_of_forall $ simple_func.integrable_approx_on hfm hfi h₀ hc)
(simple_func.tendsto_approx_on_L1_nnnorm hfm h₀ hfs (hfi.sub hc).2) },
refine hsc.mem_of_tendsto (tendsto_const_nhds.smul this) (eventually_of_forall $ λ n, _),
have : ∑ y in (F n).range, (μ ((F n) ⁻¹' {y})).to_real = (μ univ).to_real,
by rw [← (F n).sum_range_measure_preimage_singleton, @ennreal.to_real_sum _ _
(λ y, μ ((F n) ⁻¹' {y})) (λ _ _, (measure_lt_top _ _))],
rw [← this, simple_func.integral],
refine hs.center_mass_mem (λ _ _, ennreal.to_real_nonneg) _ _,
{ rw [this, ennreal.to_real_pos_iff, pos_iff_ne_zero, ne.def, measure.measure_univ_eq_zero],
exact ⟨hμ, measure_ne_top _ _⟩ },
{ simp only [simple_func.mem_range],
rintros _ ⟨x, rfl⟩,
exact simple_func.approx_on_mem hfm h₀ n x }
end
/-- If `μ` is a non-zero finite measure on `α`, `s` is a convex closed set in `E`, and `f` is an
integrable function sending `μ`-a.e. points to `s`, then the average value of `f` belongs to `s`:
`(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s`. See also `convex.center_mass_mem` for a finite sum version
of this lemma. -/
lemma convex.smul_integral_mem
[finite_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s)
(hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) :
(μ univ).to_real⁻¹ • ∫ x, f x ∂μ ∈ s :=
begin
have : ∀ᵐ (x : α) ∂μ, hfi.ae_measurable.mk f x ∈ s,
{ filter_upwards [hfs, hfi.ae_measurable.ae_eq_mk],
assume a ha h,
rwa ← h },
convert convex.smul_integral_mem_of_measurable hs hsc hμ this
(hfi.congr hfi.ae_measurable.ae_eq_mk) (hfi.ae_measurable.measurable_mk) using 2,
apply integral_congr_ae,
exact hfi.ae_measurable.ae_eq_mk
end
/-- If `μ` is a probability measure on `α`, `s` is a convex closed set in `E`, and `f` is an
integrable function sending `μ`-a.e. points to `s`, then the expected value of `f` belongs to `s`:
`∫ x, f x ∂μ ∈ s`. See also `convex.sum_mem` for a finite sum version of this lemma. -/
lemma convex.integral_mem [probability_measure μ] {s : set E} (hs : convex s) (hsc : is_closed s)
{f : α → E} (hf : ∀ᵐ x ∂μ, f x ∈ s) (hfi : integrable f μ) :
∫ x, f x ∂μ ∈ s :=
by simpa [measure_univ] using hs.smul_integral_mem hsc (probability_measure.ne_zero μ) hf hfi
/-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set
`s`, `μ` is a finite non-zero measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points
to `s`, then the value of `g` at the average value of `f` is less than or equal to the average value
of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_center_mass_le`
for a finite sum version of this lemma. -/
lemma convex_on.map_smul_integral_le [finite_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g)
(hgc : continuous_on g s) (hsc : is_closed s) (hμ : μ ≠ 0) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s)
(hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) :
g ((μ univ).to_real⁻¹ • ∫ x, f x ∂μ) ≤ (μ univ).to_real⁻¹ • ∫ x, g (f x) ∂μ :=
begin
set t := {p : E × ℝ | p.1 ∈ s ∧ g p.1 ≤ p.2},
have ht_conv : convex t := hg.convex_epigraph,
have ht_closed : is_closed t :=
(hsc.preimage continuous_fst).is_closed_le (hgc.comp continuous_on_fst (subset.refl _))
continuous_on_snd,
have ht_mem : ∀ᵐ x ∂μ, (f x, g (f x)) ∈ t := hfs.mono (λ x hx, ⟨hx, le_rfl⟩),
simpa [integral_pair hfi hgi]
using (ht_conv.smul_integral_mem ht_closed hμ ht_mem (hfi.prod_mk hgi)).2
end
/-- Jensen's inequality: if a function `g : E → ℝ` is convex and continuous on a convex closed set
`s`, `μ` is a probability measure on `α`, and `f : α → E` is a function sending `μ`-a.e. points to
`s`, then the value of `g` at the expected value of `f` is less than or equal to the expected value
of `g ∘ f` provided that both `f` and `g ∘ f` are integrable. See also `convex.map_sum_le` for a
finite sum version of this lemma. -/
lemma convex_on.map_integral_le [probability_measure μ] {s : set E} {g : E → ℝ} (hg : convex_on s g)
(hgc : continuous_on g s) (hsc : is_closed s) {f : α → E} (hfs : ∀ᵐ x ∂μ, f x ∈ s)
(hfi : integrable f μ) (hgi : integrable (g ∘ f) μ) :
g (∫ x, f x ∂μ) ≤ ∫ x, g (f x) ∂μ :=
by simpa [measure_univ]
using hg.map_smul_integral_le hgc hsc (probability_measure.ne_zero μ) hfs hfi hgi
|
9c9cda59b84274e2dcf08a3a10d3bf1df402411c | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/ring_theory/unique_factorization_domain.lean | 54c05dae5aa6501d88a56fb537b21a16ac4b9429 | [
"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 | 82,123 | 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, Jens Wagemaker, Aaron Anderson
-/
import algebra.big_operators.associated
import algebra.gcd_monoid.basic
import data.finsupp.multiset
import ring_theory.noetherian
import ring_theory.multiplicity
/-!
# Unique factorization
## Main Definitions
* `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is
well-founded.
* `unique_factorization_monoid` holds for `wf_dvd_monoid`s where
`irreducible` is equivalent to `prime`
## To do
* set up the complete lattice structure on `factor_set`.
-/
variables {α : Type*}
local infix ` ~ᵤ ` : 50 := associated
/-- Well-foundedness of the strict version of |, which is equivalent to the descending chain
condition on divisibility and to the ascending chain condition on
principal ideals in an integral domain.
-/
class wf_dvd_monoid (α : Type*) [comm_monoid_with_zero α] : Prop :=
(well_founded_dvd_not_unit : well_founded (@dvd_not_unit α _))
export wf_dvd_monoid (well_founded_dvd_not_unit)
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring.wf_dvd_monoid [comm_ring α] [is_domain α] [is_noetherian_ring α] :
wf_dvd_monoid α :=
⟨by { convert inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _),
ext,
exact ideal.span_singleton_lt_span_singleton.symm }⟩
namespace wf_dvd_monoid
variables [comm_monoid_with_zero α]
open associates nat
theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates α)): wf_dvd_monoid α :=
⟨begin
haveI := h,
refine (surjective.well_founded_iff mk_surjective _).2 well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
variables [wf_dvd_monoid α]
instance wf_dvd_monoid_associates : wf_dvd_monoid (associates α) :=
⟨begin
refine (surjective.well_founded_iff mk_surjective _).1 well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
end⟩
theorem well_founded_associates : well_founded ((<) : associates α → associates α → Prop) :=
subrelation.wf (λ x y, dvd_not_unit_of_lt) well_founded_dvd_not_unit
local attribute [elab_as_eliminator] well_founded.fix
lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) :
∃ i, irreducible i ∧ i ∣ a :=
let ⟨b, hs, hr⟩ := well_founded_dvd_not_unit.has_min {b | b ∣ a ∧ ¬ is_unit b} ⟨a, dvd_rfl, ha⟩ in
⟨b, ⟨hs.2, λ c d he, let h := dvd_trans ⟨d, he⟩ hs.1 in or_iff_not_imp_left.2 $
λ hc, of_not_not $ λ hd, hr c ⟨h, hc⟩ ⟨ne_zero_of_dvd_ne_zero ha0 h, d, hd, he⟩⟩, hs.1⟩
@[elab_as_eliminator] lemma induction_on_irreducible {P : α → Prop} (a : α)
(h0 : P 0) (hu : ∀ u : α, is_unit u → P u)
(hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) :
P a :=
by haveI := classical.dec; exact
well_founded_dvd_not_unit.fix
(λ a ih, if ha0 : a = 0 then ha0.substr h0
else if hau : is_unit a then hu a hau
else let ⟨i, hii, b, hb⟩ := exists_irreducible_factor hau ha0,
hb0 : b ≠ 0 := ne_zero_of_dvd_ne_zero ha0 ⟨i, mul_comm i b ▸ hb⟩ in
hb.symm ▸ hi b i hb0 hii $ ih b ⟨hb0, i, hii.1, mul_comm i b ▸ hb⟩)
a
lemma exists_factors (a : α) : a ≠ 0 →
∃ f : multiset α, (∀ b ∈ f, irreducible b) ∧ associated f.prod a :=
induction_on_irreducible a
(λ h, (h rfl).elim)
(λ u hu _, ⟨0, λ _ h, h.elim, hu.unit, one_mul _⟩)
(λ a i ha0 hi ih _,
let ⟨s, hs⟩ := ih ha0 in
⟨i ::ₘ s, λ b H, (multiset.mem_cons.1 H).elim (λ h, h.symm ▸ hi) (hs.1 b),
by { rw s.prod_cons i, exact hs.2.mul_left i }⟩)
lemma not_unit_iff_exists_factors_eq (a : α) (hn0 : a ≠ 0) :
¬ is_unit a ↔ ∃ f : multiset α, (∀ b ∈ f, irreducible b) ∧ f.prod = a ∧ f ≠ ∅ :=
⟨λ hnu, begin
obtain ⟨f, hi, u, rfl⟩ := exists_factors a hn0,
obtain ⟨b, h⟩ := multiset.exists_mem_of_ne_zero (λ h : f = 0, hnu $ by simp [h]),
classical, refine ⟨(f.erase b).cons (b * u), λ a ha, _, _, multiset.cons_ne_zero⟩,
{ obtain (rfl|ha) := multiset.mem_cons.1 ha,
exacts [associated.irreducible ⟨u,rfl⟩ (hi b h), hi a (multiset.mem_of_mem_erase ha)] },
{ rw [multiset.prod_cons, mul_comm b, mul_assoc, multiset.prod_erase h, mul_comm] },
end,
λ ⟨f, hi, he, hne⟩, let ⟨b, h⟩ := multiset.exists_mem_of_ne_zero hne in
not_is_unit_of_not_is_unit_dvd (hi b h).not_unit $ he ▸ multiset.dvd_prod h⟩
end wf_dvd_monoid
theorem wf_dvd_monoid.of_well_founded_associates [cancel_comm_monoid_with_zero α]
(h : well_founded ((<) : associates α → associates α → Prop)) : wf_dvd_monoid α :=
wf_dvd_monoid.of_wf_dvd_monoid_associates
⟨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }⟩
theorem wf_dvd_monoid.iff_well_founded_associates [cancel_comm_monoid_with_zero α] :
wf_dvd_monoid α ↔ well_founded ((<) : associates α → associates α → Prop) :=
⟨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associates⟩
section prio
set_option default_priority 100 -- see Note [default priority]
/-- unique factorization monoids.
These are defined as `cancel_comm_monoid_with_zero`s with well-founded strict divisibility
relations, but this is equivalent to more familiar definitions:
Each element (except zero) is uniquely represented as a multiset of irreducible factors.
Uniqueness is only up to associated elements.
Each element (except zero) is non-uniquely represented as a multiset
of prime factors.
To define a UFD using the definition in terms of multisets
of irreducible factors, use the definition `of_exists_unique_irreducible_factors`
To define a UFD using the definition in terms of multisets
of prime factors, use the definition `of_exists_prime_factors`
-/
class unique_factorization_monoid (α : Type*) [cancel_comm_monoid_with_zero α]
extends wf_dvd_monoid α : Prop :=
(irreducible_iff_prime : ∀ {a : α}, irreducible a ↔ prime a)
/-- Can't be an instance because it would cause a loop `ufm → wf_dvd_monoid → ufm → ...`. -/
@[reducible] lemma ufm_of_gcd_of_wf_dvd_monoid [cancel_comm_monoid_with_zero α]
[wf_dvd_monoid α] [gcd_monoid α] : unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, gcd_monoid.irreducible_iff_prime
.. ‹wf_dvd_monoid α› }
instance associates.ufm [cancel_comm_monoid_with_zero α]
[unique_factorization_monoid α] : unique_factorization_monoid (associates α) :=
{ irreducible_iff_prime := by { rw ← associates.irreducible_iff_prime_iff,
apply unique_factorization_monoid.irreducible_iff_prime, }
.. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates α)) }
end prio
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
theorem exists_prime_factors (a : α) : a ≠ 0 →
∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a :=
by { simp_rw ← unique_factorization_monoid.irreducible_iff_prime,
apply wf_dvd_monoid.exists_factors a }
@[elab_as_eliminator] lemma induction_on_prime {P : α → Prop}
(a : α) (h₁ : P 0) (h₂ : ∀ x : α, is_unit x → P x)
(h₃ : ∀ a p : α, a ≠ 0 → prime p → P a → P (p * a)) : P a :=
begin
simp_rw ← unique_factorization_monoid.irreducible_iff_prime at h₃,
exact wf_dvd_monoid.induction_on_irreducible a h₁ h₂ h₃,
end
end unique_factorization_monoid
lemma prime_factors_unique [cancel_comm_monoid_with_zero α] : ∀ {f g : multiset α},
(∀ x ∈ f, prime x) → (∀ x ∈ g, prime x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g :=
by haveI := classical.dec_eq α; exact
λ f, multiset.induction_on f
(λ g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem $ λ x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit $ is_unit_iff_dvd_one.2 $
(multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))
(λ p f ih g hf hg hfg,
let ⟨b, hbg, hb⟩ := exists_associated_mem_of_dvd_prod
(hf p (by simp)) (λ q hq, hg _ hq) $
hfg.dvd_iff_dvd_right.1
(show p ∣ (p ::ₘ f).prod, by simp) in
begin
rw ← multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (λ q hq, hf _ (by simp [hq]))
(λ q (hq : q ∈ g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated.of_mul_left
(by rwa [← multiset.prod_cons, ← multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero)),
end)
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
lemma factors_unique {f g : multiset α} (hf : ∀ x ∈ f, irreducible x) (hg : ∀ x ∈ g, irreducible x)
(h : f.prod ~ᵤ g.prod) : multiset.rel associated f g :=
prime_factors_unique
(λ x hx, irreducible_iff_prime.mp (hf x hx))
(λ x hx, irreducible_iff_prime.mp (hg x hx))
h
end unique_factorization_monoid
/-- If an irreducible has a prime factorization,
then it is an associate of one of its prime factors. -/
lemma prime_factors_irreducible [cancel_comm_monoid_with_zero α] {a : α} {f : multiset α}
(ha : irreducible a) (pfa : (∀ b ∈ f, prime b) ∧ f.prod ~ᵤ a) :
∃ p, a ~ᵤ p ∧ f = {p} :=
begin
haveI := classical.dec_eq α,
refine multiset.induction_on f (λ h, (ha.not_unit
(associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1,
rintros p s _ ⟨u, hu⟩ hs,
use p,
have hs0 : s = 0,
{ by_contra hs0,
obtain ⟨q, hq⟩ := multiset.exists_mem_of_ne_zero hs0,
apply (hs q (by simp [hq])).2.1,
refine (ha.is_unit_or_is_unit (_ : _ = ((p * ↑u) * (s.erase q).prod) * _)).resolve_left _,
{ rw [mul_right_comm _ _ q, mul_assoc, ← multiset.prod_cons, multiset.cons_erase hq, ← hu,
mul_comm, mul_comm p _, mul_assoc],
simp, },
apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _),
apply (hs p (multiset.mem_cons_self _ _)).2.1 },
simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *,
exact ⟨associated.symm ⟨u, hu⟩, rfl⟩,
end
section exists_prime_factors
variables [cancel_comm_monoid_with_zero α]
variables (pf : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a)
include pf
lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid α :=
⟨begin
classical,
refine rel_hom_class.well_founded
(rel_hom.mk _ _ : (dvd_not_unit : α → α → Prop) →r ((<) : ℕ∞ → ℕ∞ → Prop))
(with_top.well_founded_lt nat.lt_wf),
{ intro a,
by_cases h : a = 0, { exact ⊤ },
exact (classical.some (pf a h)).card },
rintros a b ⟨ane0, ⟨c, hc, b_eq⟩⟩,
rw dif_neg ane0,
by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] },
rw [dif_neg h, with_top.coe_lt_coe],
have cne0 : c ≠ 0, { refine mt (λ con, _) h, rw [b_eq, con, mul_zero] },
calc multiset.card (classical.some (pf a ane0))
< _ + multiset.card (classical.some (pf c cne0)) :
lt_add_of_pos_right _ (multiset.card_pos.mpr (λ con, hc (associated_one_iff_is_unit.mp _)))
... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) :
(multiset.card_add _ _).symm
... = multiset.card (classical.some (pf b h)) :
multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _),
{ convert (classical.some_spec (pf c cne0)).2.symm,
rw [con, multiset.prod_zero] },
{ intros x hadd,
rw multiset.mem_add at hadd,
cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd },
{ rw multiset.prod_add,
transitivity a * c,
{ apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 },
{ rw ← b_eq,
apply (classical.some_spec (pf _ _)).2.symm, } }
end⟩
lemma irreducible_iff_prime_of_exists_prime_factors {p : α} : irreducible p ↔ prime p :=
begin
by_cases hp0 : p = 0,
{ simp [hp0] },
refine ⟨λ h, _, prime.irreducible⟩,
obtain ⟨f, hf⟩ := pf p hp0,
obtain ⟨q, hq, rfl⟩ := prime_factors_irreducible h hf,
rw hq.prime_iff,
exact hf.1 q (multiset.mem_singleton_self _)
end
theorem unique_factorization_monoid.of_exists_prime_factors :
unique_factorization_monoid α :=
{ irreducible_iff_prime := λ _, irreducible_iff_prime_of_exists_prime_factors pf,
.. wf_dvd_monoid.of_exists_prime_factors pf }
end exists_prime_factors
theorem unique_factorization_monoid.iff_exists_prime_factors [cancel_comm_monoid_with_zero α] :
unique_factorization_monoid α ↔
(∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, prime b) ∧ f.prod ~ᵤ a) :=
⟨λ h, @unique_factorization_monoid.exists_prime_factors _ _ h,
unique_factorization_monoid.of_exists_prime_factors⟩
section
variables {β : Type*} [cancel_comm_monoid_with_zero α] [cancel_comm_monoid_with_zero β]
lemma mul_equiv.unique_factorization_monoid (e : α ≃* β)
(hα : unique_factorization_monoid α) : unique_factorization_monoid β :=
begin
rw unique_factorization_monoid.iff_exists_prime_factors at hα ⊢, intros a ha,
obtain ⟨w,hp,u,h⟩ := hα (e.symm a) (λ h, ha $ by { convert ← map_zero e, simp [← h] }),
exact ⟨ w.map e,
λ b hb, let ⟨c,hc,he⟩ := multiset.mem_map.1 hb in he ▸ e.prime_iff.1 (hp c hc),
units.map e.to_monoid_hom u,
by { erw [multiset.prod_hom, ← e.map_mul, h], simp } ⟩,
end
lemma mul_equiv.unique_factorization_monoid_iff (e : α ≃* β) :
unique_factorization_monoid α ↔ unique_factorization_monoid β :=
⟨ e.unique_factorization_monoid, e.symm.unique_factorization_monoid ⟩
end
theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g)
(p : α) : irreducible p ↔ prime p :=
⟨by letI := classical.dec_eq α; exact λ hpi,
⟨hpi.ne_zero, hpi.1,
λ a b ⟨x, hx⟩,
if hab0 : a * b = 0
then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim
(λ ha0, by simp [ha0])
(λ hb0, by simp [hb0])
else
have hx0 : x ≠ 0, from λ hx0, by simp * at *,
have ha0 : a ≠ 0, from left_ne_zero_of_mul hab0,
have hb0 : b ≠ 0, from right_ne_zero_of_mul hab0,
begin
cases eif x hx0 with fx hfx,
cases eif a ha0 with fa hfa,
cases eif b hb0 with fb hfb,
have h : multiset.rel associated (p ::ₘ fx) (fa + fb),
{ apply uif,
{ exact λ i hi, (multiset.mem_cons.1 hi).elim (λ hip, hip.symm ▸ hpi) (hfx.1 _), },
{ exact λ i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), },
calc multiset.prod (p ::ₘ fx)
~ᵤ a * b : by rw [hx, multiset.prod_cons];
exact hfx.2.mul_left _
... ~ᵤ (fa).prod * (fb).prod :
hfa.2.symm.mul_mul hfb.2.symm
... = _ : by rw multiset.prod_add, },
exact let ⟨q, hqf, hq⟩ := multiset.exists_mem_of_rel_of_mem h
(multiset.mem_cons_self p _) in
(multiset.mem_add.1 hqf).elim
(λ hqa, or.inl $ hq.dvd_iff_dvd_left.2 $
hfa.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqa))
(λ hqb, or.inr $ hq.dvd_iff_dvd_left.2 $
hfb.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqb))
end⟩, prime.irreducible⟩
theorem unique_factorization_monoid.of_exists_unique_irreducible_factors
[cancel_comm_monoid_with_zero α]
(eif : ∀ (a : α), a ≠ 0 → ∃ f : multiset α, (∀b ∈ f, irreducible b) ∧ f.prod ~ᵤ a)
(uif : ∀ (f g : multiset α),
(∀ x ∈ f, irreducible x) → (∀ x ∈ g, irreducible x) → f.prod ~ᵤ g.prod →
multiset.rel associated f g) :
unique_factorization_monoid α :=
unique_factorization_monoid.of_exists_prime_factors (by
{ convert eif,
simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif })
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero α] [decidable_eq α]
variables [unique_factorization_monoid α]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def factors (a : α) : multiset α := if h : a = 0 then 0 else
classical.some (unique_factorization_monoid.exists_prime_factors a h)
theorem factors_prod {a : α} (ane0 : a ≠ 0) : associated (factors a).prod a :=
begin
rw [factors, dif_neg ane0],
exact (classical.some_spec (exists_prime_factors a ane0)).2
end
lemma ne_zero_of_mem_factors {p a : α} (h : p ∈ factors a) : a ≠ 0 :=
begin
intro ha,
rw [factors, dif_pos ha] at h,
exact multiset.not_mem_zero _ h
end
lemma dvd_of_mem_factors {p a : α} (h : p ∈ factors a) : p ∣ a :=
dvd_trans (multiset.dvd_prod h) (associated.dvd (factors_prod (ne_zero_of_mem_factors h)))
theorem prime_of_factor {a : α} (x : α) (hx : x ∈ factors a) : prime x :=
begin
have ane0 := ne_zero_of_mem_factors hx,
rw [factors, dif_neg ane0] at hx,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx,
end
theorem irreducible_of_factor {a : α} : ∀ (x : α), x ∈ factors a → irreducible x :=
λ x h, (prime_of_factor x h).irreducible
@[simp] lemma factors_zero : factors (0 : α) = 0 :=
by simp [factors]
@[simp] lemma factors_one : factors (1 : α) = 0 :=
begin
nontriviality α using [factors],
rw ← multiset.rel_zero_right,
refine factors_unique irreducible_of_factor (λ x hx, (multiset.not_mem_zero x hx).elim) _,
rw multiset.prod_zero,
exact factors_prod one_ne_zero,
end
lemma exists_mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a →
∃ q ∈ factors a, p ~ᵤ q :=
λ ⟨b, hb⟩,
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
have multiset.rel associated (p ::ₘ factors b) (factors a),
from factors_unique
(λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp) (irreducible_of_factor _))
irreducible_of_factor
(associated.symm $ calc multiset.prod (factors a) ~ᵤ a : factors_prod ha0
... = p * b : hb
... ~ᵤ multiset.prod (p ::ₘ factors b) :
by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
lemma exists_mem_factors {x : α} (hx : x ≠ 0) (h : ¬ is_unit x) : ∃ p, p ∈ factors x :=
begin
obtain ⟨p', hp', hp'x⟩ := wf_dvd_monoid.exists_irreducible_factor h hx,
obtain ⟨p, hp, hpx⟩ := exists_mem_factors_of_dvd hx hp' hp'x,
exact ⟨p, hp⟩
end
lemma factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
multiset.rel associated (factors (x * y)) (factors x + factors y) :=
begin
refine factors_unique irreducible_of_factor
(λ a ha, (multiset.mem_add.mp ha).by_cases (irreducible_of_factor _) (irreducible_of_factor _))
((factors_prod (mul_ne_zero hx hy)).trans _),
rw multiset.prod_add,
exact (associated.mul_mul (factors_prod hx) (factors_prod hy)).symm,
end
lemma factors_pow {x : α} (n : ℕ) :
multiset.rel associated (factors (x ^ n)) (n • factors x) :=
begin
induction n with n ih,
{ simp },
by_cases h0 : x = 0,
{ simp [h0, zero_pow n.succ_pos, smul_zero] },
rw [pow_succ, succ_nsmul],
refine multiset.rel.trans _ (factors_mul h0 (pow_ne_zero n h0)) _,
refine multiset.rel.add _ ih,
exact multiset.rel_refl_of_refl_on (λ y hy, associated.refl _),
end
@[simp] lemma factors_pos (x : α) (hx : x ≠ 0) : 0 < factors x ↔ ¬ is_unit x :=
begin
split,
{ intros h hx,
obtain ⟨p, hp⟩ := multiset.exists_mem_of_ne_zero h.ne',
exact (prime_of_factor _ hp).not_unit (is_unit_of_dvd_unit (dvd_of_mem_factors hp) hx) },
{ intros h,
obtain ⟨p, hp⟩ := exists_mem_factors hx h,
exact bot_lt_iff_ne_bot.mpr (mt multiset.eq_zero_iff_forall_not_mem.mp
(not_forall.mpr ⟨p, not_not.mpr hp⟩)) },
end
end unique_factorization_monoid
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero α] [decidable_eq α] [normalization_monoid α]
variables [unique_factorization_monoid α]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def normalized_factors (a : α) : multiset α :=
multiset.map normalize $ factors a
/-- An arbitrary choice of factors of `x : M` is exactly the (unique) normalized set of factors,
if `M` has a trivial group of units. -/
@[simp] lemma factors_eq_normalized_factors {M : Type*} [cancel_comm_monoid_with_zero M]
[decidable_eq M] [unique_factorization_monoid M] [unique (Mˣ)] (x : M) :
factors x = normalized_factors x :=
begin
unfold normalized_factors,
convert (multiset.map_id (factors x)).symm,
ext p,
exact normalize_eq p
end
theorem normalized_factors_prod {a : α} (ane0 : a ≠ 0) : associated (normalized_factors a).prod a :=
begin
rw [normalized_factors, factors, dif_neg ane0],
refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2,
rw [← associates.mk_eq_mk_iff_associated, ← associates.prod_mk, ← associates.prod_mk,
multiset.map_map],
congr' 2,
ext,
rw [function.comp_apply, associates.mk_normalize],
end
theorem prime_of_normalized_factor {a : α} : ∀ (x : α), x ∈ normalized_factors a → prime x :=
begin
rw [normalized_factors, factors],
split_ifs with ane0, { simp },
intros x hx, rcases multiset.mem_map.1 hx with ⟨y, ⟨hy, rfl⟩⟩,
rw (normalize_associated _).prime_iff,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy,
end
theorem irreducible_of_normalized_factor {a : α} :
∀ (x : α), x ∈ normalized_factors a → irreducible x :=
λ x h, (prime_of_normalized_factor x h).irreducible
theorem normalize_normalized_factor {a : α} :
∀ (x : α), x ∈ normalized_factors a → normalize x = x :=
begin
rw [normalized_factors, factors],
split_ifs with h, { simp },
intros x hx,
obtain ⟨y, hy, rfl⟩ := multiset.mem_map.1 hx,
apply normalize_idem
end
lemma normalized_factors_irreducible {a : α} (ha : irreducible a) :
normalized_factors a = {normalize a} :=
begin
obtain ⟨p, a_assoc, hp⟩ := prime_factors_irreducible ha
⟨prime_of_normalized_factor, normalized_factors_prod ha.ne_zero⟩,
have p_mem : p ∈ normalized_factors a,
{ rw hp, exact multiset.mem_singleton_self _ },
convert hp,
rwa [← normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated]
end
lemma normalized_factors_eq_of_dvd (a : α) : ∀ (p q ∈ normalized_factors a), p ∣ q → p = q :=
begin
intros p hp q hq hdvd,
convert normalize_eq_normalize hdvd
(((prime_of_normalized_factor _ hp).irreducible).dvd_symm
((prime_of_normalized_factor _ hq).irreducible) hdvd);
apply (normalize_normalized_factor _ _).symm; assumption
end
lemma exists_mem_normalized_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) : p ∣ a →
∃ q ∈ normalized_factors a, p ~ᵤ q :=
λ ⟨b, hb⟩,
have hb0 : b ≠ 0, from λ hb0, by simp * at *,
have multiset.rel associated (p ::ₘ normalized_factors b) (normalized_factors a),
from factors_unique
(λ x hx, (multiset.mem_cons.1 hx).elim (λ h, h.symm ▸ hp)
(irreducible_of_normalized_factor _))
irreducible_of_normalized_factor
(associated.symm $ calc multiset.prod (normalized_factors a) ~ᵤ a : normalized_factors_prod ha0
... = p * b : hb
... ~ᵤ multiset.prod (p ::ₘ normalized_factors b) :
by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
lemma exists_mem_normalized_factors {x : α} (hx : x ≠ 0) (h : ¬ is_unit x) :
∃ p, p ∈ normalized_factors x :=
begin
obtain ⟨p', hp', hp'x⟩ := wf_dvd_monoid.exists_irreducible_factor h hx,
obtain ⟨p, hp, hpx⟩ := exists_mem_normalized_factors_of_dvd hx hp' hp'x,
exact ⟨p, hp⟩
end
@[simp] lemma normalized_factors_zero : normalized_factors (0 : α) = 0 :=
by simp [normalized_factors, factors]
@[simp] lemma normalized_factors_one : normalized_factors (1 : α) = 0 :=
begin
nontriviality α using [normalized_factors, factors],
rw ← multiset.rel_zero_right,
apply factors_unique irreducible_of_normalized_factor,
{ intros x hx,
exfalso,
apply multiset.not_mem_zero x hx },
{ simp [normalized_factors_prod one_ne_zero] },
apply_instance
end
@[simp] lemma normalized_factors_mul {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
normalized_factors (x * y) = normalized_factors x + normalized_factors y :=
begin
have h : (normalize : α → α) = associates.out ∘ associates.mk,
{ ext, rw [function.comp_apply, associates.out_mk], },
rw [← multiset.map_id' (normalized_factors (x * y)), ← multiset.map_id' (normalized_factors x),
← multiset.map_id' (normalized_factors y), ← multiset.map_congr rfl normalize_normalized_factor,
← multiset.map_congr rfl normalize_normalized_factor,
← multiset.map_congr rfl normalize_normalized_factor,
← multiset.map_add, h, ← multiset.map_map associates.out, eq_comm,
← multiset.map_map associates.out],
refine congr rfl _,
apply multiset.map_mk_eq_map_mk_of_rel,
apply factors_unique,
{ intros x hx,
rcases multiset.mem_add.1 hx with hx | hx;
exact irreducible_of_normalized_factor x hx },
{ exact irreducible_of_normalized_factor },
{ rw multiset.prod_add,
exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans
(normalized_factors_prod (mul_ne_zero hx hy)).symm }
end
@[simp] lemma normalized_factors_pow {x : α} (n : ℕ) :
normalized_factors (x ^ n) = n • normalized_factors x :=
begin
induction n with n ih,
{ simp },
by_cases h0 : x = 0,
{ simp [h0, zero_pow n.succ_pos, smul_zero] },
rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih],
end
theorem _root_.irreducible.normalized_factors_pow {p : α} (hp : irreducible p) (k : ℕ) :
normalized_factors (p ^ k) = multiset.repeat (normalize p) k :=
by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton]
theorem normalized_factors_prod_eq (s : multiset α) (hs : ∀ a ∈ s, irreducible a) :
normalized_factors s.prod = s.map normalize :=
begin
induction s using multiset.induction with a s ih,
{ rw [multiset.prod_zero, normalized_factors_one, multiset.map_zero] },
{ have ia := hs a (multiset.mem_cons_self a _),
have ib := λ b h, hs b (multiset.mem_cons_of_mem h),
obtain rfl | ⟨b, hb⟩ := s.empty_or_exists_mem,
{ rw [multiset.cons_zero, multiset.prod_singleton,
multiset.map_singleton, normalized_factors_irreducible ia] },
haveI := nontrivial_of_ne b 0 (ib b hb).ne_zero,
rw [multiset.prod_cons, multiset.map_cons, normalized_factors_mul ia.ne_zero,
normalized_factors_irreducible ia, ih],
exacts [rfl, ib, multiset.prod_ne_zero (λ h, (ib 0 h).ne_zero rfl)] },
end
lemma dvd_iff_normalized_factors_le_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
x ∣ y ↔ normalized_factors x ≤ normalized_factors y :=
begin
split,
{ rintro ⟨c, rfl⟩,
simp [hx, right_ne_zero_of_mul hy] },
{ rw [← (normalized_factors_prod hx).dvd_iff_dvd_left,
← (normalized_factors_prod hy).dvd_iff_dvd_right],
apply multiset.prod_dvd_prod_of_le }
end
lemma associated_iff_normalized_factors_eq_normalized_factors {x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
x ~ᵤ y ↔ normalized_factors x = normalized_factors y :=
begin
refine ⟨λ h, _,
λ h, (normalized_factors_prod hx).symm.trans (trans (by rw h) (normalized_factors_prod hy))⟩,
apply le_antisymm; rw [← dvd_iff_normalized_factors_le_normalized_factors],
all_goals { simp [*, h.dvd, h.symm.dvd], },
end
theorem normalized_factors_of_irreducible_pow {p : α} (hp : irreducible p) (k : ℕ) :
normalized_factors (p ^ k) = multiset.repeat (normalize p) k :=
by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton]
lemma zero_not_mem_normalized_factors (x : α) : (0 : α) ∉ normalized_factors x :=
λ h, prime.ne_zero (prime_of_normalized_factor _ h) rfl
lemma dvd_of_mem_normalized_factors {a p : α} (H : p ∈ normalized_factors a) : p ∣ a :=
begin
by_cases hcases : a = 0,
{ rw hcases,
exact dvd_zero p },
{ exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) },
end
lemma exists_associated_prime_pow_of_unique_normalized_factor {p r : α}
(h : ∀ {m}, m ∈ normalized_factors r → m = p) (hr : r ≠ 0) : ∃ (i : ℕ), associated (p ^ i) r :=
begin
use (normalized_factors r).card,
have := unique_factorization_monoid.normalized_factors_prod hr,
rwa [multiset.eq_repeat_of_mem (λ b, h), multiset.prod_repeat] at this
end
lemma normalized_factors_prod_of_prime [nontrivial α] [unique αˣ] {m : multiset α}
(h : ∀ p ∈ m, prime p) : (normalized_factors m.prod) = m :=
by simpa only [←multiset.rel_eq, ←associated_eq_eq] using prime_factors_unique
(prime_of_normalized_factor) h (normalized_factors_prod (m.prod_ne_zero_of_prime h))
lemma mem_normalized_factors_eq_of_associated {a b c : α} (ha : a ∈ normalized_factors c)
(hb : b ∈ normalized_factors c) (h : associated a b) : a = b :=
begin
rw [← normalize_normalized_factor a ha, ← normalize_normalized_factor b hb,
normalize_eq_normalize_iff],
apply associated.dvd_dvd h,
end
@[simp] lemma normalized_factors_pos (x : α) (hx : x ≠ 0) :
0 < normalized_factors x ↔ ¬ is_unit x :=
begin
split,
{ intros h hx,
obtain ⟨p, hp⟩ := multiset.exists_mem_of_ne_zero h.ne',
exact (prime_of_normalized_factor _ hp).not_unit
(is_unit_of_dvd_unit (dvd_of_mem_normalized_factors hp) hx) },
{ intros h,
obtain ⟨p, hp⟩ := exists_mem_normalized_factors hx h,
exact bot_lt_iff_ne_bot.mpr (mt multiset.eq_zero_iff_forall_not_mem.mp
(not_forall.mpr ⟨p, not_not.mpr hp⟩)) },
end
lemma dvd_not_unit_iff_normalized_factors_lt_normalized_factors
{x y : α} (hx : x ≠ 0) (hy : y ≠ 0) :
dvd_not_unit x y ↔ normalized_factors x < normalized_factors y :=
begin
split,
{ rintro ⟨_, c, hc, rfl⟩,
simp only [hx, right_ne_zero_of_mul hy, normalized_factors_mul, ne.def, not_false_iff,
lt_add_iff_pos_right, normalized_factors_pos, hc] },
{ intro h,
exact dvd_not_unit_of_dvd_of_not_dvd
((dvd_iff_normalized_factors_le_normalized_factors hx hy).mpr h.le)
(mt (dvd_iff_normalized_factors_le_normalized_factors hy hx).mp h.not_le) }
end
end unique_factorization_monoid
namespace unique_factorization_monoid
open_locale classical
open multiset associates
noncomputable theory
variables [cancel_comm_monoid_with_zero α] [nontrivial α] [unique_factorization_monoid α]
/-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/
protected def normalization_monoid : normalization_monoid α :=
normalization_monoid_of_monoid_hom_right_inverse
{ to_fun := λ a : associates α, if a = 0 then 0 else ((normalized_factors a).map
(classical.some mk_surjective.has_right_inverse : associates α → α)).prod,
map_one' := by simp,
map_mul' := λ x y, by
{ by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
simp [hx, hy] } } begin
intro x,
dsimp,
by_cases hx : x = 0, { simp [hx] },
have h : associates.mk_monoid_hom ∘ (classical.some mk_surjective.has_right_inverse) =
(id : associates α → associates α),
{ ext x,
rw [function.comp_apply, mk_monoid_hom_apply,
classical.some_spec mk_surjective.has_right_inverse x],
refl },
rw [if_neg hx, ← mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id,
← associated_iff_eq],
apply normalized_factors_prod hx
end
instance : inhabited (normalization_monoid α) := ⟨unique_factorization_monoid.normalization_monoid⟩
end unique_factorization_monoid
namespace unique_factorization_monoid
variables {R : Type*} [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R]
lemma no_factors_of_no_prime_factors {a b : R} (ha : a ≠ 0)
(h : (∀ {d}, d ∣ a → d ∣ b → ¬ prime d)) : ∀ {d}, d ∣ a → d ∣ b → is_unit d :=
λ d, induction_on_prime d
(by { simp only [zero_dvd_iff], intros, contradiction })
(λ x hx _ _, hx)
(λ d q hp hq ih dvd_a dvd_b,
absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b)))
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `c` have no common prime factors, `a ∣ b`.
Compare `is_coprime.dvd_of_dvd_mul_left`. -/
lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a ≠ 0) :
(∀ {d}, d ∣ a → d ∣ c → ¬ prime d) → a ∣ b * c → a ∣ b :=
begin
refine induction_on_prime c _ _ _,
{ intro no_factors,
simp only [dvd_zero, mul_zero, forall_prop_of_true],
haveI := classical.prop_decidable,
exact is_unit_iff_forall_dvd.mp
(no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ },
{ rintros _ ⟨x, rfl⟩ _ a_dvd_bx,
apply units.dvd_mul_right.mp a_dvd_bx },
{ intros c p hc hp ih no_factors a_dvd_bpc,
apply ih (λ q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq),
rw mul_left_comm at a_dvd_bpc,
refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (λ h, _),
exact no_factors h (dvd_mul_right p c) hp }
end
/-- Euclid's lemma: if `a ∣ b * c` and `a` and `b` have no common prime factors, `a ∣ c`.
Compare `is_coprime.dvd_of_dvd_mul_right`. -/
lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a ≠ 0)
(no_factors : ∀ {d}, d ∣ a → d ∣ b → ¬ prime d) : a ∣ b * c → a ∣ c :=
by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors
/-- If `a ≠ 0, b` are elements of a unique factorization domain, then dividing
out their common factor `c'` gives `a'` and `b'` with no factors in common. -/
lemma exists_reduced_factors : ∀ (a ≠ (0 : R)) b,
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
begin
haveI := classical.prop_decidable,
intros a,
refine induction_on_prime a _ _ _,
{ intros, contradiction },
{ intros a a_unit a_ne_zero b,
use [a, b, 1],
split,
{ intros p p_dvd_a _,
exact is_unit_of_dvd_unit p_dvd_a a_unit },
{ simp } },
{ intros a p a_ne_zero p_prime ih_a pa_ne_zero b,
by_cases p ∣ b,
{ rcases h with ⟨b, rfl⟩,
obtain ⟨a', b', c', no_factor, ha', hb'⟩ := ih_a a_ne_zero b,
refine ⟨a', b', p * c', @no_factor, _, _⟩,
{ rw [mul_assoc, ha'] },
{ rw [mul_assoc, hb'] } },
{ obtain ⟨a', b', c', coprime, rfl, rfl⟩ := ih_a a_ne_zero b,
refine ⟨p * a', b', c', _, mul_left_comm _ _ _, rfl⟩,
intros q q_dvd_pa' q_dvd_b',
cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a',
{ have : p ∣ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _,
contradiction },
exact coprime q_dvd_a' q_dvd_b' } }
end
lemma exists_reduced_factors' (a b : R) (hb : b ≠ 0) :
∃ a' b' c', (∀ {d}, d ∣ a' → d ∣ b' → is_unit d) ∧ c' * a' = a ∧ c' * b' = b :=
let ⟨b', a', c', no_factor, hb, ha⟩ := exists_reduced_factors b hb a
in ⟨a', b', c', λ _ hpb hpa, no_factor hpa hpb, ha, hb⟩
lemma pow_right_injective {a : R} (ha0 : a ≠ 0) (ha1 : ¬ is_unit a) :
function.injective ((^) a : ℕ → R) :=
begin
letI := classical.dec_eq R,
intros i j hij,
letI : nontrivial R := ⟨⟨a, 0, ha0⟩⟩,
letI : normalization_monoid R := unique_factorization_monoid.normalization_monoid,
obtain ⟨p', hp', dvd'⟩ := wf_dvd_monoid.exists_irreducible_factor ha1 ha0,
obtain ⟨p, mem, _⟩ := exists_mem_normalized_factors_of_dvd ha0 hp' dvd',
have := congr_arg (λ x, multiset.count p (normalized_factors x)) hij,
simp only [normalized_factors_pow, multiset.count_nsmul] at this,
exact mul_right_cancel₀ (multiset.count_ne_zero.mpr mem) this
end
lemma pow_eq_pow_iff {a : R} (ha0 : a ≠ 0) (ha1 : ¬ is_unit a) {i j : ℕ} :
a ^ i = a ^ j ↔ i = j :=
(pow_right_injective ha0 ha1).eq_iff
section multiplicity
variables [nontrivial R] [normalization_monoid R] [decidable_eq R]
variables [dec_dvd : decidable_rel (has_dvd.dvd : R → R → Prop)]
open multiplicity multiset
include dec_dvd
lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : ℕ}
(ha : irreducible a) (hb : b ≠ 0) :
↑n ≤ multiplicity a b ↔ repeat (normalize a) n ≤ normalized_factors b :=
begin
rw ← pow_dvd_iff_le_multiplicity,
revert b,
induction n with n ih, { simp },
intros b hb,
split,
{ rintro ⟨c, rfl⟩,
rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb,
rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ,
normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, ← ih hb.2],
apply dvd.intro _ rfl },
{ rw [multiset.le_iff_exists_add],
rintro ⟨u, hu⟩,
rw [← (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat],
exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) }
end
/-- The multiplicity of an irreducible factor of a nonzero element is exactly the number of times
the normalized factor occurs in the `normalized_factors`.
See also `count_normalized_factors_eq` which expands the definition of `multiplicity`
to produce a specification for `count (normalized_factors _) _`..
-/
lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b ≠ 0) :
multiplicity a b = (normalized_factors b).count (normalize a) :=
begin
apply le_antisymm,
{ apply part_enat.le_of_lt_add_one,
rw [← nat.cast_one, ← nat.cast_add, lt_iff_not_ge, ge_iff_le,
le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le],
simp },
rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, ← le_count_iff_repeat_le],
end
omit dec_dvd
/-- The number of times an irreducible factor `p` appears in `normalized_factors x` is defined by
the number of times it divides `x`.
See also `multiplicity_eq_count_normalized_factors` if `n` is given by `multiplicity p x`.
-/
lemma count_normalized_factors_eq {p x : R} (hp : irreducible p) (hnorm : normalize p = p) {n : ℕ}
(hle : p^n ∣ x) (hlt : ¬ (p^(n+1) ∣ x)) :
(normalized_factors x).count p = n :=
begin
letI : decidable_rel ((∣) : R → R → Prop) := λ _ _, classical.prop_decidable _,
by_cases hx0 : x = 0,
{ simp [hx0] at hlt, contradiction },
rw [← part_enat.coe_inj],
convert (multiplicity_eq_count_normalized_factors hp hx0).symm,
{ exact hnorm.symm },
exact (multiplicity.eq_coe_iff.mpr ⟨hle, hlt⟩).symm
end
/-- The number of times an irreducible factor `p` appears in `normalized_factors x` is defined by
the number of times it divides `x`. This is a slightly more general version of
`unique_factorization_monoid.count_normalized_factors_eq` that allows `p = 0`.
See also `multiplicity_eq_count_normalized_factors` if `n` is given by `multiplicity p x`.
-/
lemma count_normalized_factors_eq' {p x : R} (hp : p = 0 ∨ irreducible p) (hnorm : normalize p = p)
{n : ℕ} (hle : p^n ∣ x) (hlt : ¬ (p^(n+1) ∣ x)) :
(normalized_factors x).count p = n :=
begin
rcases hp with rfl|hp,
{ cases n,
{ exact count_eq_zero.2 (zero_not_mem_normalized_factors _) },
{ rw [zero_pow (nat.succ_pos _)] at hle hlt,
exact absurd hle hlt } },
{ exact count_normalized_factors_eq hp hnorm hle hlt }
end
end multiplicity
section multiplicative
variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
variables {β : Type*} [cancel_comm_monoid_with_zero β]
open_locale big_operators
lemma prime_pow_coprime_prod_of_coprime_insert [decidable_eq α] {s : finset α} (i : α → ℕ) (p : α)
(hps : p ∉ s) (is_prime : ∀ q ∈ insert p s, prime q)
(is_coprime : ∀ (q q' ∈ insert p s), q ∣ q' → q = q') :
∀ (q : α), q ∣ p ^ i p → q ∣ ∏ p' in s, p' ^ i p' → is_unit q :=
begin
have hp := is_prime _ (finset.mem_insert_self _ _),
refine λ _, no_factors_of_no_prime_factors (pow_ne_zero _ hp.ne_zero) _,
intros d hdp hdprod hd,
apply hps,
replace hdp := hd.dvd_of_dvd_pow hdp,
obtain ⟨q, q_mem', hdq⟩ := hd.exists_mem_multiset_dvd hdprod,
obtain ⟨q, q_mem, rfl⟩ := multiset.mem_map.mp q_mem',
replace hdq := hd.dvd_of_dvd_pow hdq,
have : p ∣ q := dvd_trans
(hd.irreducible.dvd_symm hp.irreducible hdp)
hdq,
convert q_mem,
exact is_coprime _ (finset.mem_insert_self p s) _ (finset.mem_insert_of_mem q_mem) this,
end
/-- If `P` holds for units and powers of primes,
and `P x ∧ P y` for coprime `x, y` implies `P (x * y)`,
then `P` holds on a product of powers of distinct primes. -/
@[elab_as_eliminator]
theorem induction_on_prime_power
{P : α → Prop} (s : finset α) (i : α → ℕ)
(is_prime : ∀ p ∈ s, prime p) (is_coprime : ∀ p q ∈ s, p ∣ q → p = q)
(h1 : ∀ {x}, is_unit x → P x) (hpr : ∀ {p} (i : ℕ), prime p → P (p ^ i))
(hcp : ∀ {x y}, (∀ p, p ∣ x → p ∣ y → is_unit p) → P x → P y → P (x * y)) :
P (∏ p in s, p ^ (i p)) :=
begin
letI := classical.dec_eq α,
induction s using finset.induction_on with p f' hpf' ih,
{ simpa using h1 is_unit_one },
rw finset.prod_insert hpf',
exact hcp
(prime_pow_coprime_prod_of_coprime_insert i p hpf' is_prime is_coprime)
(hpr (i p) (is_prime _ (finset.mem_insert_self _ _)))
(ih (λ q hq, is_prime _ (finset.mem_insert_of_mem hq))
(λ q hq q' hq', is_coprime _ (finset.mem_insert_of_mem hq) _ (finset.mem_insert_of_mem hq')))
end
/-- If `P` holds for `0`, units and powers of primes,
and `P x ∧ P y` for coprime `x, y` implies `P (x * y)`,
then `P` holds on all `a : α`. -/
@[elab_as_eliminator]
theorem induction_on_coprime
{P : α → Prop} (a : α) (h0 : P 0) (h1 : ∀ {x}, is_unit x → P x)
(hpr : ∀ {p} (i : ℕ), prime p → P (p ^ i))
(hcp : ∀ {x y}, (∀ p, p ∣ x → p ∣ y → is_unit p) → P x → P y → P (x * y)) :
P a :=
begin
letI := classical.dec_eq α,
have P_of_associated : ∀ {x y}, associated x y → P x → P y,
{ rintros x y ⟨u, rfl⟩ hx,
exact hcp (λ p _ hpx, is_unit_of_dvd_unit hpx u.is_unit) hx (h1 u.is_unit) },
by_cases ha0 : a = 0, { rwa ha0 },
haveI : nontrivial α := ⟨⟨_, _, ha0⟩⟩,
letI : normalization_monoid α := unique_factorization_monoid.normalization_monoid,
refine P_of_associated (normalized_factors_prod ha0) _,
rw [← (normalized_factors a).map_id, finset.prod_multiset_map_count],
refine induction_on_prime_power _ _ _ _ @h1 @hpr @hcp;
simp only [multiset.mem_to_finset],
{ apply prime_of_normalized_factor },
{ apply normalized_factors_eq_of_dvd },
end
/-- If `f` maps `p ^ i` to `(f p) ^ i` for primes `p`, and `f`
is multiplicative on coprime elements, then `f` is multiplicative on all products of primes. -/
@[elab_as_eliminator]
theorem multiplicative_prime_power
{f : α → β} (s : finset α) (i j : α → ℕ)
(is_prime : ∀ p ∈ s, prime p) (is_coprime : ∀ p q ∈ s, p ∣ q → p = q)
(h1 : ∀ {x y}, is_unit y → f (x * y) = f x * f y)
(hpr : ∀ {p} (i : ℕ), prime p → f (p ^ i) = (f p) ^ i)
(hcp : ∀ {x y}, (∀ p, p ∣ x → p ∣ y → is_unit p) → f (x * y) = f x * f y) :
f (∏ p in s, p ^ (i p + j p)) = f (∏ p in s, p ^ i p) * f (∏ p in s, p ^ j p) :=
begin
letI := classical.dec_eq α,
induction s using finset.induction_on with p s hps ih,
{ simpa using h1 is_unit_one },
have hpr_p := is_prime _ (finset.mem_insert_self _ _),
have hpr_s : ∀ p ∈ s, prime p := λ p hp, is_prime _ (finset.mem_insert_of_mem hp),
have hcp_p := λ i, (prime_pow_coprime_prod_of_coprime_insert i p hps is_prime is_coprime),
have hcp_s : ∀ (p q ∈ s), p ∣ q → p = q := λ p hp q hq, is_coprime p
(finset.mem_insert_of_mem hp) q
(finset.mem_insert_of_mem hq),
rw [finset.prod_insert hps, finset.prod_insert hps, finset.prod_insert hps,
hcp (hcp_p _), hpr _ hpr_p, hcp (hcp_p _), hpr _ hpr_p, hcp (hcp_p _), hpr _ hpr_p,
ih hpr_s hcp_s,
pow_add, mul_assoc, mul_left_comm (f p ^ j p), mul_assoc],
end
/-- If `f` maps `p ^ i` to `(f p) ^ i` for primes `p`, and `f`
is multiplicative on coprime elements, then `f` is multiplicative everywhere. -/
theorem multiplicative_of_coprime
(f : α → β) (a b : α) (h0 : f 0 = 0) (h1 : ∀ {x y}, is_unit y → f (x * y) = f x * f y)
(hpr : ∀ {p} (i : ℕ), prime p → f (p ^ i) = (f p) ^ i)
(hcp : ∀ {x y}, (∀ p, p ∣ x → p ∣ y → is_unit p) → f (x * y) = f x * f y) :
f (a * b) = f a * f b :=
begin
letI := classical.dec_eq α,
by_cases ha0 : a = 0, { rw [ha0, zero_mul, h0, zero_mul] },
by_cases hb0 : b = 0, { rw [hb0, mul_zero, h0, mul_zero] },
by_cases hf1 : f 1 = 0,
{ calc f (a * b) = f ((a * b) * 1) : by rw mul_one
... = 0 : by simp only [h1 is_unit_one, hf1, mul_zero]
... = f a * f (b * 1) : by simp only [h1 is_unit_one, hf1, mul_zero]
... = f a * f b : by rw mul_one },
have h1' : f 1 = 1 := (mul_left_inj' hf1).mp (by rw [← h1 is_unit_one, one_mul, one_mul]),
haveI : nontrivial α := ⟨⟨_, _, ha0⟩⟩,
letI : normalization_monoid α := unique_factorization_monoid.normalization_monoid,
suffices : f (∏ p in (normalized_factors a).to_finset ∪ (normalized_factors b).to_finset,
p ^ ((normalized_factors a).count p + (normalized_factors b).count p))
= f (∏ p in (normalized_factors a).to_finset ∪ (normalized_factors b).to_finset,
p ^ (normalized_factors a).count p) *
f (∏ (p : α) in (normalized_factors a).to_finset ∪ (normalized_factors b).to_finset,
p ^ (normalized_factors b).count p),
{ obtain ⟨ua, a_eq⟩ := normalized_factors_prod ha0,
obtain ⟨ub, b_eq⟩ := normalized_factors_prod hb0,
rw [← a_eq, ← b_eq, mul_right_comm _ ↑ua, h1 ua.is_unit, h1 ub.is_unit, h1 ua.is_unit,
← mul_assoc, h1 ub.is_unit, mul_right_comm _ (f ua), ← mul_assoc],
congr,
rw [← (normalized_factors a).map_id, ← (normalized_factors b).map_id,
finset.prod_multiset_map_count, finset.prod_multiset_map_count,
finset.prod_subset (finset.subset_union_left _ (normalized_factors b).to_finset),
finset.prod_subset (finset.subset_union_right _ (normalized_factors b).to_finset),
← finset.prod_mul_distrib],
simp_rw [id.def, ← pow_add, this],
all_goals { simp only [multiset.mem_to_finset] },
{ intros p hpab hpb, simp [hpb] },
{ intros p hpab hpa, simp [hpa] } },
refine multiplicative_prime_power _ _ _ _ _ @h1 @hpr @hcp,
all_goals { simp only [multiset.mem_to_finset, finset.mem_union] },
{ rintros p (hpa | hpb); apply prime_of_normalized_factor; assumption },
{ rintro p (hp | hp) q (hq | hq) hdvd;
rw [← normalize_normalized_factor _ hp, ← normalize_normalized_factor _ hq];
exact normalize_eq_normalize hdvd
((prime_of_normalized_factor _ hp).irreducible.dvd_symm
(prime_of_normalized_factor _ hq).irreducible
hdvd) },
end
end multiplicative
end unique_factorization_monoid
namespace associates
open unique_factorization_monoid associated multiset
variables [cancel_comm_monoid_with_zero α]
/-- `factor_set α` representation elements of unique factorization domain as multisets.
`multiset α` produced by `normalized_factors` are only unique up to associated elements, while the
multisets in `factor_set α` are unique by equality and restricted to irreducible elements. This
gives us a representation of each element as a unique multisets (or the added ⊤ for 0), which has a
complete lattice struture. Infimum is the greatest common divisor and supremum is the least common
multiple.
-/
@[reducible] def {u} factor_set (α : Type u) [cancel_comm_monoid_with_zero α] :
Type u :=
with_top (multiset { a : associates α // irreducible a })
local attribute [instance] associated.setoid
theorem factor_set.coe_add {a b : multiset { a : associates α // irreducible a }} :
(↑(a + b) : factor_set α) = a + b :=
by norm_cast
lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates α)] :
∀(a b : factor_set α), a ⊔ b + a ⊓ b = a + b
| none b := show ⊤ ⊔ b + ⊤ ⊓ b = ⊤ + b, by simp
| a none := show a ⊔ ⊤ + a ⊓ ⊤ = a + ⊤, by simp
| (some a) (some b) := show (a : factor_set α) ⊔ b + a ⊓ b = a + b, from
begin
rw [← with_top.coe_sup, ← with_top.coe_inf, ← with_top.coe_add, ← with_top.coe_add,
with_top.coe_eq_coe],
exact multiset.union_add_inter _ _
end
/-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset,
or `0` if there is none. -/
def factor_set.prod : factor_set α → associates α
| none := 0
| (some s) := (s.map coe).prod
@[simp] theorem prod_top : (⊤ : factor_set α).prod = 0 := rfl
@[simp] theorem prod_coe {s : multiset { a : associates α // irreducible a }} :
(s : factor_set α).prod = (s.map coe).prod :=
rfl
@[simp] theorem prod_add : ∀(a b : factor_set α), (a + b).prod = a.prod * b.prod
| none b := show (⊤ + b).prod = (⊤:factor_set α).prod * b.prod, by simp
| a none := show (a + ⊤).prod = a.prod * (⊤:factor_set α).prod, by simp
| (some a) (some b) :=
show (↑a + ↑b:factor_set α).prod = (↑a:factor_set α).prod * (↑b:factor_set α).prod,
by rw [← factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add]
theorem prod_mono : ∀{a b : factor_set α}, a ≤ b → a.prod ≤ b.prod
| none b h := have b = ⊤, from top_unique h, by rw [this, prod_top]; exact le_rfl
| a none h := show a.prod ≤ (⊤ : factor_set α).prod, by simp; exact le_top
| (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h
theorem factor_set.prod_eq_zero_iff [nontrivial α] (p : factor_set α) :
p.prod = 0 ↔ p = ⊤ :=
begin
induction p using with_top.rec_top_coe,
{ simp only [iff_self, eq_self_iff_true, associates.prod_top] },
simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map],
rintro ⟨⟨a, ha⟩, -, eq⟩,
rw [subtype.coe_mk] at eq,
exact ha.ne_zero eq,
end
/-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/
def bcount [decidable_eq (associates α)] (p : {a : associates α // irreducible a}) :
factor_set α → ℕ
| none := 0
| (some s) := s.count p
variables [dec_irr : Π (p : associates α), decidable (irreducible p)]
include dec_irr
/-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`.
If `p` is not irreducible, `count p s` is defined to be `0`. -/
def count [decidable_eq (associates α)] (p : associates α) :
factor_set α → ℕ :=
if hp : irreducible p then bcount ⟨p, hp⟩ else 0
@[simp] lemma count_some [decidable_eq (associates α)] {p : associates α} (hp : irreducible p)
(s : multiset _) : count p (some s) = s.count ⟨p, hp⟩:=
by { dunfold count, split_ifs, refl }
@[simp] lemma count_zero [decidable_eq (associates α)] {p : associates α} (hp : irreducible p) :
count p (0 : factor_set α) = 0 :=
by { dunfold count, split_ifs, refl }
lemma count_reducible [decidable_eq (associates α)] {p : associates α} (hp : ¬ irreducible p) :
count p = 0 := dif_neg hp
omit dec_irr
/-- membership in a factor_set (bundled version) -/
def bfactor_set_mem : {a : associates α // irreducible a} → (factor_set α) → Prop
| _ ⊤ := true
| p (some l) := p ∈ l
include dec_irr
/-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of
`s : factor_set α`.
If `p` is not irreducible, `p` is not a member of any `factor_set`. -/
def factor_set_mem (p : associates α) (s : factor_set α) : Prop :=
if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false
instance : has_mem (associates α) (factor_set α) := ⟨factor_set_mem⟩
@[simp] lemma factor_set_mem_eq_mem (p : associates α) (s : factor_set α) :
factor_set_mem p s = (p ∈ s) := rfl
lemma mem_factor_set_top {p : associates α} {hp : irreducible p} :
p ∈ (⊤ : factor_set α) :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial
end
lemma mem_factor_set_some {p : associates α} {hp : irreducible p}
{l : multiset {a : associates α // irreducible a }} :
p ∈ (l : factor_set α) ↔ subtype.mk p hp ∈ l :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl
end
lemma reducible_not_mem_factor_set {p : associates α} (hp : ¬ irreducible p)
(s : factor_set α) : ¬ p ∈ s :=
λ (h : if hp : irreducible p then bfactor_set_mem ⟨p, hp⟩ s else false),
by rwa [dif_neg hp] at h
omit dec_irr
variable [unique_factorization_monoid α]
theorem unique' {p q : multiset (associates α)} :
(∀a∈p, irreducible a) → (∀a∈q, irreducible a) → p.prod = q.prod → p = q :=
begin
apply multiset.induction_on_multiset_quot p,
apply multiset.induction_on_multiset_quot q,
assume s t hs ht eq,
refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _),
{ exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) },
{ exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) },
simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq
end
theorem factor_set.unique [nontrivial α] {p q : factor_set α} (h : p.prod = q.prod) : p = q :=
begin
induction p using with_top.rec_top_coe;
induction q using with_top.rec_top_coe,
{ refl },
{ rw [eq_comm, ←factor_set.prod_eq_zero_iff, ←h, associates.prod_top] },
{ rw [←factor_set.prod_eq_zero_iff, h, associates.prod_top] },
{ congr' 1,
rw ←multiset.map_eq_map subtype.coe_injective,
apply unique' _ _ h;
{ intros a ha,
obtain ⟨⟨a', irred⟩, -, rfl⟩ := multiset.mem_map.mp ha,
rwa [subtype.coe_mk] } },
end
theorem prod_le_prod_iff_le [nontrivial α] {p q : multiset (associates α)}
(hp : ∀a∈p, irreducible a) (hq : ∀a∈q, irreducible a) :
p.prod ≤ q.prod ↔ p ≤ q :=
iff.intro
begin
classical,
rintros ⟨c, eqc⟩,
refine multiset.le_iff_exists_add.2 ⟨factors c, unique' hq (λ x hx, _) _⟩,
{ obtain h|h := multiset.mem_add.1 hx,
{ exact hp x h },
{ exact irreducible_of_factor _ h } },
{ rw [eqc, multiset.prod_add],
congr,
refine associated_iff_eq.mp (factors_prod (λ hc, _)).symm,
refine not_irreducible_zero (hq _ _),
rw [←prod_eq_zero_iff, eqc, hc, mul_zero] }
end
prod_le_prod
variables [dec : decidable_eq α] [dec' : decidable_eq (associates α)]
include dec
/-- This returns the multiset of irreducible factors as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors' (a : α) :
multiset { a : associates α // irreducible a } :=
(factors a).pmap (λa ha, ⟨associates.mk a, (irreducible_mk _).2 ha⟩)
(irreducible_of_factor)
@[simp] theorem map_subtype_coe_factors' {a : α} :
(factors' a).map coe = (factors a).map associates.mk :=
by simp [factors', multiset.map_pmap, multiset.pmap_eq_map]
theorem factors'_cong {a b : α} (h : a ~ᵤ b) :
factors' a = factors' b :=
begin
obtain rfl|hb := eq_or_ne b 0,
{ rw associated_zero_iff_eq_zero at h, rw h },
have ha : a ≠ 0,
{ contrapose! hb with ha,
rw [←associated_zero_iff_eq_zero, ←ha],
exact h.symm },
rw [←multiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors',
map_subtype_coe_factors', ←rel_associated_iff_map_eq_map],
exact factors_unique irreducible_of_factor irreducible_of_factor
((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm),
end
include dec'
/-- This returns the multiset of irreducible factors of an associate as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors (a : associates α) :
factor_set α :=
begin
refine (if h : a = 0 then ⊤ else
quotient.hrec_on a (λx h, some $ factors' x) _ h),
assume a b hab,
apply function.hfunext,
{ have : a ~ᵤ 0 ↔ b ~ᵤ 0, from
iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0),
simp only [associated_zero_iff_eq_zero] at this,
simp only [quotient_mk_eq_mk, this, mk_eq_zero] },
exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab)
end
@[simp] theorem factors_0 : (0 : associates α).factors = ⊤ :=
dif_pos rfl
@[simp] theorem factors_mk (a : α) (h : a ≠ 0) :
(associates.mk a).factors = factors' a :=
by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) }
@[simp]
theorem factors_prod (a : associates α) : a.factors.prod = a :=
quotient.induction_on a $ assume a, decidable.by_cases
(assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this])
(assume : associates.mk a ≠ 0,
have a ≠ 0, by simp * at *,
by simp [this, quotient_mk_eq_mk, prod_mk,
mk_eq_mk_iff_associated.2 (factors_prod this)])
theorem prod_factors [nontrivial α] (s : factor_set α) : s.prod.factors = s :=
factor_set.unique $ factors_prod _
@[nontriviality] lemma factors_subsingleton [subsingleton α] {a : associates α} :
a.factors = option.none :=
by { convert factors_0; apply_instance }
lemma factors_eq_none_iff_zero {a : associates α} :
a.factors = option.none ↔ a = 0 :=
begin
nontriviality α,
exact ⟨λ h, by rwa [← factors_prod a, factor_set.prod_eq_zero_iff], λ h, h.symm ▸ factors_0⟩
end
lemma factors_eq_some_iff_ne_zero {a : associates α} :
(∃ (s : multiset {p : associates α // irreducible p}), a.factors = some s) ↔ a ≠ 0 :=
by rw [← option.is_some_iff_exists, ← option.ne_none_iff_is_some, ne.def, ne.def,
factors_eq_none_iff_zero]
theorem eq_of_factors_eq_factors {a b : associates α} (h : a.factors = b.factors) : a = b :=
have a.factors.prod = b.factors.prod, by rw h,
by rwa [factors_prod, factors_prod] at this
omit dec dec'
theorem eq_of_prod_eq_prod [nontrivial α] {a b : factor_set α} (h : a.prod = b.prod) : a = b :=
begin
classical,
have : a.prod.factors = b.prod.factors, by rw h,
rwa [prod_factors, prod_factors] at this
end
include dec dec' dec_irr
theorem eq_factors_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
(h : ∀ (p : associates α) (hp : irreducible p), p.count a.factors = p.count b.factors) :
a.factors = b.factors :=
begin
obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha,
obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb,
rw [h_sa, h_sb] at h ⊢,
rw option.some_inj,
have h_count : ∀ (p : associates α) (hp : irreducible p), sa.count ⟨p, hp⟩ = sb.count ⟨p, hp⟩,
{ intros p hp, rw [← count_some, ← count_some, h p hp] },
apply multiset.to_finsupp.injective,
ext ⟨p, hp⟩,
rw [multiset.to_finsupp_apply, multiset.to_finsupp_apply, h_count p hp]
end
theorem eq_of_eq_counts {a b : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
(h : ∀ (p : associates α), irreducible p → p.count a.factors = p.count b.factors) : a = b :=
eq_of_factors_eq_factors (eq_factors_of_eq_counts ha hb h)
lemma count_le_count_of_factors_le {a b p : associates α} (hb : b ≠ 0)
(hp : irreducible p) (h : a.factors ≤ b.factors) : p.count a.factors ≤ p.count b.factors :=
begin
by_cases ha : a = 0,
{ simp [*] at *, },
obtain ⟨sa, h_sa⟩ := factors_eq_some_iff_ne_zero.mpr ha,
obtain ⟨sb, h_sb⟩ := factors_eq_some_iff_ne_zero.mpr hb,
rw [h_sa, h_sb] at h ⊢,
rw [count_some hp, count_some hp], rw with_top.some_le_some at h,
exact multiset.count_le_of_le _ h
end
omit dec_irr
@[simp] theorem factors_mul (a b : associates α) :
(a * b).factors = a.factors + b.factors :=
begin
casesI subsingleton_or_nontrivial α,
{ simp [subsingleton.elim a 0], },
refine (eq_of_prod_eq_prod (eq_of_factors_eq_factors _)),
rw [prod_add, factors_prod, factors_prod, factors_prod],
end
theorem factors_mono : ∀{a b : associates α}, a ≤ b → a.factors ≤ b.factors
| s t ⟨d, rfl⟩ := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le
theorem factors_le {a b : associates α} : a.factors ≤ b.factors ↔ a ≤ b :=
iff.intro
(assume h, have a.factors.prod ≤ b.factors.prod, from prod_mono h,
by rwa [factors_prod, factors_prod] at this)
factors_mono
include dec_irr
lemma count_le_count_of_le {a b p : associates α} (hb : b ≠ 0)
(hp : irreducible p) (h : a ≤ b) : p.count a.factors ≤ p.count b.factors :=
count_le_count_of_factors_le hb hp $ factors_mono h
omit dec dec' dec_irr
theorem prod_le [nontrivial α] {a b : factor_set α} : a.prod ≤ b.prod ↔ a ≤ b :=
begin
classical,
exact iff.intro
(assume h, have a.prod.factors ≤ b.prod.factors, from factors_mono h,
by rwa [prod_factors, prod_factors] at this)
prod_mono
end
include dec dec'
noncomputable instance : has_sup (associates α) := ⟨λa b, (a.factors ⊔ b.factors).prod⟩
noncomputable instance : has_inf (associates α) := ⟨λa b, (a.factors ⊓ b.factors).prod⟩
noncomputable instance : lattice (associates α) :=
{ sup := (⊔),
inf := (⊓),
sup_le :=
assume a b c hac hbc, factors_prod c ▸ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)),
le_sup_left := assume a b,
le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left,
le_sup_right := assume a b,
le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right,
le_inf :=
assume a b c hac hbc, factors_prod a ▸ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)),
inf_le_left := assume a b,
le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)),
inf_le_right := assume a b,
le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)),
.. associates.partial_order }
lemma sup_mul_inf (a b : associates α) : (a ⊔ b) * (a ⊓ b) = a * b :=
show (a.factors ⊔ b.factors).prod * (a.factors ⊓ b.factors).prod = a * b,
begin
nontriviality α,
refine eq_of_factors_eq_factors _,
rw [← prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add]
end
include dec_irr
lemma dvd_of_mem_factors {a p : associates α} {hp : irreducible p}
(hm : p ∈ factors a) : p ∣ a :=
begin
by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p },
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha0,
rw [← associates.factors_prod a],
rw [← ha', factors_mk a0 nza] at hm ⊢,
erw prod_coe,
apply multiset.dvd_prod, apply multiset.mem_map.mpr,
exact ⟨⟨p, hp⟩, mem_factor_set_some.mp hm, rfl⟩
end
omit dec'
lemma dvd_of_mem_factors' {a : α} {p : associates α} {hp : irreducible p} {hz : a ≠ 0}
(h_mem : subtype.mk p hp ∈ factors' a) : p ∣ associates.mk a :=
by { haveI := classical.dec_eq (associates α),
apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp,
rw factors_mk _ hz,
apply mem_factor_set_some.2 h_mem }
omit dec_irr
lemma mem_factors'_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a :=
begin
obtain ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd ha0 hp hd,
apply multiset.mem_pmap.mpr, use q, use hq,
exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq))
end
include dec_irr
lemma mem_factors'_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) ∈ factors' a ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 },
{ apply mem_factors'_of_dvd ha0 }
end
include dec'
lemma mem_factors_of_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) (hd : p ∣ a) :
(associates.mk p) ∈ factors (associates.mk a) :=
begin
rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd)
end
lemma mem_factors_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
(associates.mk p) ∈ factors (associates.mk a) ↔ p ∣ a :=
begin
split,
{ rw ← mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp },
{ apply mem_factors_of_dvd ha0 hp }
end
lemma exists_prime_dvd_of_not_inf_one {a b : α}
(ha : a ≠ 0) (hb : b ≠ 0) (h : (associates.mk a) ⊓ (associates.mk b) ≠ 1) :
∃ (p : α), prime p ∧ p ∣ a ∧ p ∣ b :=
begin
have hz : (factors (associates.mk a)) ⊓ (factors (associates.mk b)) ≠ 0,
{ contrapose! h with hf,
change ((factors (associates.mk a)) ⊓ (factors (associates.mk b))).prod = 1,
rw hf,
exact multiset.prod_zero },
rw [factors_mk a ha, factors_mk b hb, ← with_top.coe_inf] at hz,
obtain ⟨⟨p0, p0_irr⟩, p0_mem⟩ := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz),
rw multiset.inf_eq_inter at p0_mem,
obtain ⟨p, rfl⟩ : ∃ p, associates.mk p = p0 := quot.exists_rep p0,
refine ⟨p, _, _, _⟩,
{ rw [← irreducible_iff_prime, ← irreducible_mk],
exact p0_irr },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left,
apply ha, },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right,
apply hb }
end
theorem coprime_iff_inf_one {a b : α} (ha0 : a ≠ 0) (hb0 : b ≠ 0) :
(associates.mk a) ⊓ (associates.mk b) = 1 ↔ ∀ {d : α}, d ∣ a → d ∣ b → ¬ prime d :=
begin
split,
{ intros hg p ha hb hp,
refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _),
rw ← hg,
exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) },
{ contrapose,
intros hg hc,
obtain ⟨p, hp, hpa, hpb⟩ := exists_prime_dvd_of_not_inf_one ha0 hb0 hg,
exact hc hpa hpb hp }
end
omit dec_irr
theorem factors_self [nontrivial α] {p : associates α} (hp : irreducible p) :
p.factors = some ({⟨p, hp⟩}) :=
eq_of_prod_eq_prod (by rw [factors_prod, factor_set.prod, map_singleton, prod_singleton,
subtype.coe_mk])
theorem factors_prime_pow [nontrivial α] {p : associates α} (hp : irreducible p)
(k : ℕ) : factors (p ^ k) = some (multiset.repeat ⟨p, hp⟩ k) :=
eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat,
multiset.prod_repeat, subtype.coe_mk])
include dec_irr
theorem prime_pow_dvd_iff_le [nontrivial α] {m p : associates α} (h₁ : m ≠ 0)
(h₂ : irreducible p) {k : ℕ} : p ^ k ≤ m ↔ k ≤ count p m.factors :=
begin
obtain ⟨a, nz, rfl⟩ := associates.exists_non_zero_rep h₁,
rw [factors_mk _ nz, ← with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le,
← factors_le, factors_prime_pow h₂, factors_mk _ nz],
exact with_top.coe_le_coe
end
theorem le_of_count_ne_zero {m p : associates α} (h0 : m ≠ 0)
(hp : irreducible p) : count p m.factors ≠ 0 → p ≤ m :=
begin
nontriviality α,
rw [← pos_iff_ne_zero],
intro h,
rw [← pow_one p],
apply (prime_pow_dvd_iff_le h0 hp).2,
simpa only
end
theorem count_ne_zero_iff_dvd {a p : α} (ha0 : a ≠ 0) (hp : irreducible p) :
(associates.mk p).count (associates.mk a).factors ≠ 0 ↔ p ∣ a :=
begin
nontriviality α,
rw ← associates.mk_le_mk_iff_dvd_iff,
refine ⟨λ h, associates.le_of_count_ne_zero (associates.mk_ne_zero.mpr ha0)
((associates.irreducible_mk p).mpr hp) h, λ h, _⟩,
{ rw [← pow_one (associates.mk p), associates.prime_pow_dvd_iff_le
(associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp)] at h,
exact (zero_lt_one.trans_le h).ne' }
end
theorem count_self [nontrivial α] {p : associates α} (hp : irreducible p) :
p.count p.factors = 1 :=
by simp [factors_self hp, associates.count_some hp]
lemma count_eq_zero_of_ne {p q : associates α} (hp : irreducible p) (hq : irreducible q)
(h : p ≠ q) : p.count q.factors = 0 :=
not_ne_iff.mp $ λ h', h $ associated_iff_eq.mp $ hp.associated_of_dvd hq $
by { nontriviality α, exact le_of_count_ne_zero hq.ne_zero hp h' }
theorem count_mul {a : associates α} (ha : a ≠ 0) {b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) :
count p (factors (a * b)) = count p a.factors + count p b.factors :=
begin
obtain ⟨a0, nza, ha'⟩ := exists_non_zero_rep ha,
obtain ⟨b0, nzb, hb'⟩ := exists_non_zero_rep hb,
rw [factors_mul, ← ha', ← hb', factors_mk a0 nza, factors_mk b0 nzb, ← factor_set.coe_add,
← with_top.some_eq_coe, ← with_top.some_eq_coe, ← with_top.some_eq_coe, count_some hp,
multiset.count_add, count_some hp, count_some hp]
end
theorem count_of_coprime {a : associates α} (ha : a ≠ 0) {b : associates α}
(hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {p : associates α} (hp : irreducible p) :
count p a.factors = 0 ∨ count p b.factors = 0 :=
begin
rw [or_iff_not_imp_left, ← ne.def],
intro hca,
contrapose! hab with hcb,
exact ⟨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb,
(irreducible_iff_prime.mp hp)⟩,
end
theorem count_mul_of_coprime {a : associates α} {b : associates α}
(hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p a.factors = 0 ∨ count p a.factors = count p (a * b).factors :=
begin
by_cases ha : a = 0,
{ simp [ha], },
cases count_of_coprime ha hb hab hp with hz hb0, { tauto },
apply or.intro_right,
rw [count_mul ha hb hp, hb0, add_zero]
end
theorem count_mul_of_coprime' {a b : associates α}
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) :
count p (a * b).factors = count p a.factors
∨ count p (a * b).factors = count p b.factors :=
begin
by_cases ha : a = 0, { simp [ha], },
by_cases hb : b = 0, { simp [hb], },
rw [count_mul ha hb hp],
cases count_of_coprime ha hb hab hp with ha0 hb0,
{ apply or.intro_right, rw [ha0, zero_add] },
{ apply or.intro_left, rw [hb0, add_zero] }
end
theorem dvd_count_of_dvd_count_mul {a b : associates α} (hb : b ≠ 0)
{p : associates α} (hp : irreducible p) (hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d)
{k : ℕ} (habk : k ∣ count p (a * b).factors) : k ∣ count p a.factors :=
begin
by_cases ha : a = 0, { simpa [*] using habk, },
cases count_of_coprime ha hb hab hp with hz h,
{ rw hz, exact dvd_zero k },
{ rw [count_mul ha hb hp, h] at habk, exact habk }
end
omit dec_irr
@[simp] lemma factors_one [nontrivial α] : factors (1 : associates α) = 0 :=
begin
apply eq_of_prod_eq_prod,
rw associates.factors_prod,
exact multiset.prod_zero,
end
@[simp] theorem pow_factors [nontrivial α] {a : associates α} {k : ℕ} :
(a ^ k).factors = k • a.factors :=
begin
induction k with n h,
{ rw [zero_nsmul, pow_zero], exact factors_one },
{ rw [pow_succ, succ_nsmul, factors_mul, h] }
end
include dec_irr
lemma count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α}
(hp : irreducible p)
(k : ℕ) : count p (a ^ k).factors = k * count p a.factors :=
begin
induction k with n h,
{ rw [pow_zero, factors_one, zero_mul, count_zero hp] },
{ rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring }
end
theorem dvd_count_pow [nontrivial α] {a : associates α} (ha : a ≠ 0) {p : associates α}
(hp : irreducible p)
(k : ℕ) : k ∣ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right }
theorem is_pow_of_dvd_count [nontrivial α] {a : associates α} (ha : a ≠ 0) {k : ℕ}
(hk : ∀ (p : associates α) (hp : irreducible p), k ∣ count p a.factors) :
∃ (b : associates α), a = b ^ k :=
begin
obtain ⟨a0, hz, rfl⟩ := exists_non_zero_rep ha,
rw [factors_mk a0 hz] at hk,
have hk' : ∀ p, p ∈ (factors' a0) → k ∣ (factors' a0).count p,
{ rintros p -,
have pp : p = ⟨p.val, p.2⟩, { simp only [subtype.coe_eta, subtype.val_eq_coe] },
rw [pp, ← count_some p.2], exact hk p.val p.2 },
obtain ⟨u, hu⟩ := multiset.exists_smul_of_dvd_count _ hk',
use (u : factor_set α).prod,
apply eq_of_factors_eq_factors,
rw [pow_factors, prod_factors, factors_mk a0 hz, ← with_top.some_eq_coe, hu],
exact with_bot.coe_nsmul u k
end
/-- The only divisors of prime powers are prime powers. See `eq_pow_find_of_dvd_irreducible_pow`
for an explicit expression as a p-power (without using `count`). -/
theorem eq_pow_count_factors_of_dvd_pow {p a : associates α} (hp : irreducible p)
{n : ℕ} (h : a ∣ p ^ n) : a = p ^ p.count a.factors :=
begin
nontriviality α,
have hph := pow_ne_zero n hp.ne_zero,
have ha := ne_zero_of_dvd_ne_zero hph h,
apply eq_of_eq_counts ha (pow_ne_zero _ hp.ne_zero),
have eq_zero_of_ne : ∀ (q : associates α), irreducible q → q ≠ p → _ = 0 :=
λ q hq h', nat.eq_zero_of_le_zero $ by
{ convert count_le_count_of_le hph hq h, symmetry,
rw [count_pow hp.ne_zero hq, count_eq_zero_of_ne hq hp h', mul_zero] },
intros q hq,
rw count_pow hp.ne_zero hq,
by_cases h : q = p,
{ rw [h, count_self hp, mul_one] },
{ rw [count_eq_zero_of_ne hq hp h, mul_zero, eq_zero_of_ne q hq h] }
end
lemma count_factors_eq_find_of_dvd_pow {a p : associates α} (hp : irreducible p)
[∀ n : ℕ, decidable (a ∣ p ^ n)] {n : ℕ} (h : a ∣ p ^ n) : nat.find ⟨n, h⟩ = p.count a.factors :=
begin
apply le_antisymm,
{ refine nat.find_le ⟨1, _⟩, rw mul_one, symmetry, exact eq_pow_count_factors_of_dvd_pow hp h },
{ have hph := pow_ne_zero (nat.find ⟨n, h⟩) hp.ne_zero,
casesI (subsingleton_or_nontrivial α) with hα hα,
{ simpa using hph, },
convert count_le_count_of_le hph hp (nat.find_spec ⟨n, h⟩),
rw [count_pow hp.ne_zero hp, count_self hp, mul_one] }
end
omit dec
omit dec_irr
omit dec'
theorem eq_pow_of_mul_eq_pow [nontrivial α] {a b c : associates α} (ha : a ≠ 0) (hb : b ≠ 0)
(hab : ∀ d, d ∣ a → d ∣ b → ¬ prime d) {k : ℕ} (h : a * b = c ^ k) :
∃ (d : associates α), a = d ^ k :=
begin
classical,
by_cases hk0 : k = 0,
{ use 1,
rw [hk0, pow_zero] at h ⊢,
apply (mul_eq_one_iff.1 h).1 },
{ refine is_pow_of_dvd_count ha _,
intros p hp,
apply dvd_count_of_dvd_count_mul hb hp hab,
rw h,
apply dvd_count_pow _ hp,
rintros rfl,
rw zero_pow' _ hk0 at h,
cases mul_eq_zero.mp h; contradiction }
end
/-- The only divisors of prime powers are prime powers. -/
theorem eq_pow_find_of_dvd_irreducible_pow {a p : associates α} (hp : irreducible p)
[∀ n : ℕ, decidable (a ∣ p ^ n)] {n : ℕ} (h : a ∣ p ^ n) : a = p ^ nat.find ⟨n, h⟩ :=
by { classical, rw [count_factors_eq_find_of_dvd_pow hp, ← eq_pow_count_factors_of_dvd_pow hp h] }
end associates
section
open associates unique_factorization_monoid
lemma associates.quot_out {α : Type*} [comm_monoid α] (a : associates α):
associates.mk (quot.out (a)) = a :=
by rw [←quot_mk_eq_mk, quot.out_eq]
/-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_gcd_monoid
(α : Type*) [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
[decidable_eq (associates α)] [decidable_eq α] : gcd_monoid α :=
{ gcd := λa b, quot.out (associates.mk a ⊓ associates.mk b : associates α),
lcm := λa b, quot.out (associates.mk a ⊔ associates.mk b : associates α),
gcd_dvd_left := λ a b, by
{ rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le],
exact inf_le_left },
gcd_dvd_right := λ a b, by
{ rw [←mk_dvd_mk, (associates.mk a ⊓ associates.mk b).quot_out, dvd_eq_le],
exact inf_le_right },
dvd_gcd := λ a b c hac hab, by
{ rw [←mk_dvd_mk, (associates.mk c ⊓ associates.mk b).quot_out, dvd_eq_le,
le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff],
exact ⟨hac, hab⟩ },
lcm_zero_left := λ a, by
{ have : associates.mk (0 : α) = ⊤ := rfl,
rw [this, top_sup_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated,
←associated_iff_eq, associates.quot_out] },
lcm_zero_right := λ a, by
{ have : associates.mk (0 : α) = ⊤ := rfl,
rw [this, sup_top_eq, ←this, ←associated_zero_iff_eq_zero, ←mk_eq_mk_iff_associated,
←associated_iff_eq, associates.quot_out] },
gcd_mul_lcm := λ a b, by
{ rw [←mk_eq_mk_iff_associated, ←associates.mk_mul_mk, ←associated_iff_eq, associates.quot_out,
associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } }
/-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a
unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid
(α : Type*) [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
[normalization_monoid α] [decidable_eq (associates α)] [decidable_eq α] :
normalized_gcd_monoid α :=
{ gcd := λa b, (associates.mk a ⊓ associates.mk b).out,
lcm := λa b, (associates.mk a ⊔ associates.mk b).out,
gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a ⊓ associates.mk b)).2 $ inf_le_left,
gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a ⊓ associates.mk b)).2 $ inf_le_right,
dvd_gcd := assume a b c hac hab, show a ∣ (associates.mk c ⊓ associates.mk b).out,
by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact ⟨hac, hab⟩,
lcm_zero_left := assume a, show (⊤ ⊔ associates.mk a).out = 0, by simp,
lcm_zero_right := assume a, show (associates.mk a ⊔ ⊤).out = 0, by simp,
gcd_mul_lcm := assume a b, by
{ rw [← out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk],
exact normalize_associated (a * b) },
normalize_gcd := assume a b, by convert normalize_out _,
normalize_lcm := assume a b, by convert normalize_out _,
.. ‹normalization_monoid α› }
end
namespace unique_factorization_monoid
/-- If `y` is a nonzero element of a unique factorization monoid with finitely
many units (e.g. `ℤ`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/
noncomputable def fintype_subtype_dvd {M : Type*} [cancel_comm_monoid_with_zero M]
[unique_factorization_monoid M] [fintype Mˣ]
(y : M) (hy : y ≠ 0) :
fintype {x // x ∣ y} :=
begin
haveI : nontrivial M := ⟨⟨y, 0, hy⟩⟩,
haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid,
haveI := classical.dec_eq M,
haveI := classical.dec_eq (associates M),
-- We'll show `λ (u : Mˣ) (f ⊆ factors y) → u * Π f` is injective
-- and has image exactly the divisors of `y`.
refine fintype.of_finset
(((normalized_factors y).powerset.to_finset.product (finset.univ : finset Mˣ)).image
(λ s, (s.snd : M) * s.fst.prod))
(λ x, _),
simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true,
multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map],
split,
{ rintros ⟨s, hs, rfl⟩,
have prod_s_ne : s.fst.prod ≠ 0,
{ intro hz,
apply hy (eq_zero_of_zero_dvd _),
have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz,
rw ← (normalized_factors_prod hy).dvd_iff_dvd_right,
exact multiset.dvd_prod (multiset.mem_of_le hs hz) },
show (s.snd : M) * s.fst.prod ∣ y,
rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul,
← (normalized_factors_prod hy).dvd_iff_dvd_right],
exact multiset.prod_dvd_prod_of_le hs },
{ rintro (h : x ∣ y),
have hx : x ≠ 0, { refine mt (λ hx, _) hy, rwa [hx, zero_dvd_iff] at h },
obtain ⟨u, hu⟩ := normalized_factors_prod hx,
refine ⟨⟨normalized_factors x, u⟩, _, (mul_comm _ _).trans hu⟩,
exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h }
end
end unique_factorization_monoid
section finsupp
variables [cancel_comm_monoid_with_zero α] [unique_factorization_monoid α]
variables [normalization_monoid α] [decidable_eq α]
open unique_factorization_monoid
/-- This returns the multiset of irreducible factors as a `finsupp` -/
noncomputable def factorization (n : α) : α →₀ ℕ := (normalized_factors n).to_finsupp
lemma factorization_eq_count {n p : α} :
factorization n p = multiset.count p (normalized_factors n) :=
by simp [factorization]
@[simp] lemma factorization_zero : factorization (0 : α) = 0 := by simp [factorization]
@[simp] lemma factorization_one : factorization (1 : α) = 0 := by simp [factorization]
/-- The support of `factorization n` is exactly the finset of normalized factors -/
@[simp] lemma support_factorization {n : α} :
(factorization n).support = (normalized_factors n).to_finset :=
by simp [factorization, multiset.to_finsupp_support]
/-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/
@[simp] lemma factorization_mul {a b : α} (ha : a ≠ 0) (hb : b ≠ 0) :
factorization (a * b) = factorization a + factorization b :=
by simp [factorization, normalized_factors_mul ha hb]
/-- For any `p`, the power of `p` in `x^n` is `n` times the power in `x` -/
lemma factorization_pow {x : α} {n : ℕ} :
factorization (x^n) = n • factorization x :=
by { ext, simp [factorization] }
lemma associated_of_factorization_eq (a b: α) (ha: a ≠ 0) (hb: b ≠ 0)
(h: factorization a = factorization b) : associated a b :=
begin
simp_rw [factorization, add_equiv.apply_eq_iff_eq] at h,
rwa [associated_iff_normalized_factors_eq_normalized_factors ha hb],
end
end finsupp
|
8ec8c52544915e4b2942c2370a4965b93a22ca38 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/coelambda.lean | c5fa08032af98d2d7bfbfaf5a462323f2d6d1102 | [
"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 | 208 | lean |
#eval #[2, 3, 1, 0].qsort fun a b => a < b
#eval #[2, 3, 1, 0].qsort fun a b => let x := a; x < b
#eval #[2, 3, 1, 0].qsort (· < ·)
#eval #[2, 3, 1, 0].filter (· > 1)
#eval #[2, 3, 1, 0].filter (2 > ·)
|
7de176130cea309df2fe6cdde360dac06dce51bb | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/set/enumerate.lean | bbc27a712468f39910a5a5bd8df80787f2248c0f | [
"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 | 2,399 | 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
Enumerate elements of a set with a select function.
-/
import data.set.lattice
import tactic.wlog
noncomputable theory
open function set
namespace set
section enumerate
parameters {α : Type*} (sel : set α → option α)
def enumerate : set α → ℕ → option α
| s 0 := sel s
| s (n + 1) := do a ← sel s, enumerate (s \ {a}) n
lemma enumerate_eq_none_of_sel {s : set α} (h : sel s = none) : ∀{n}, enumerate s n = none
| 0 := by simp [h, enumerate]; refl
| (n + 1) := by simp [h, enumerate]; refl
lemma enumerate_eq_none : ∀{s n₁ n₂}, enumerate s n₁ = none → n₁ ≤ n₂ → enumerate s n₂ = none
| s 0 m := assume : sel s = none, by simp [enumerate_eq_none_of_sel, this]
| s (n + 1) m := assume h hm,
begin
cases hs : sel s,
{ by simp [enumerate_eq_none_of_sel, hs] },
{ cases m,
case nat.zero {
have : n + 1 = 0, from nat.eq_zero_of_le_zero hm,
contradiction },
case nat.succ : m' {
simp [hs, enumerate] at h ⊢,
have hm : n ≤ m', from nat.le_of_succ_le_succ hm,
exact enumerate_eq_none h hm } }
end
lemma enumerate_mem (h_sel : ∀s a, sel s = some a → a ∈ s) :
∀{s n a}, enumerate s n = some a → a ∈ s
| s 0 a := h_sel s a
| s (n+1) a :=
begin
cases h : sel s,
case none { simp [enumerate_eq_none_of_sel, h] },
case some : a' {
simp [enumerate, h],
exact assume h' : enumerate _ (s \ {a'}) n = some a,
have a ∈ s \ {a'}, from enumerate_mem h',
this.left }
end
lemma enumerate_inj {n₁ n₂ : ℕ} {a : α} {s : set α} (h_sel : ∀s a, sel s = some a → a ∈ s)
(h₁ : enumerate s n₁ = some a) (h₂ : enumerate s n₂ = some a) : n₁ = n₂ :=
begin
wlog hn : n₁ ≤ n₂,
{ rcases nat.le.dest hn with ⟨m, rfl⟩, clear hn,
induction n₁ generalizing s,
case nat.zero {
cases m,
case nat.zero { refl },
case nat.succ : m {
have : enumerate sel (s \ {a}) m = some a, { simp [enumerate, *] at * },
have : a ∈ s \ {a}, from enumerate_mem _ h_sel this,
by simpa } },
case nat.succ { cases h : sel s; simp [enumerate, nat.add_succ, add_comm, *] at *; tauto } }
end
end enumerate
end set
|
45e87cda8e899caed068d1c8b55b6b86de42b307 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /stage0/src/Lean/Meta/Tactic/Util.lean | a5c9bc2bbb2acb9bf2dbef36fab2b031bc618c45 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,098 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.Basic
import Lean.Meta.AppBuilder
import Lean.Meta.LevelDefEq
namespace Lean
namespace Meta
/-- Aka user name -/
def getMVarTag (mvarId : MVarId) : MetaM Name := do
mvarDecl ← getMVarDecl mvarId;
pure mvarDecl.userName
def setMVarTag (mvarId : MVarId) (tag : Name) : MetaM Unit := do
modify $ fun s => { s with mctx := s.mctx.setMVarUserName mvarId tag }
def appendTagSuffix (mvarId : MVarId) (suffix : Name) : MetaM Unit := do
tag ← getMVarTag mvarId;
setMVarTag mvarId (tag ++ suffix)
def mkFreshExprSyntheticOpaqueMVar (type : Expr) (userName : Name := Name.anonymous) : MetaM Expr :=
mkFreshExprMVar type MetavarKind.syntheticOpaque userName
def throwTacticEx {α} (tacticName : Name) (mvarId : MVarId) (msg : MessageData) (ref := Syntax.missing) : MetaM α :=
throwError $ "tactic '" ++ tacticName ++ "' failed, " ++ msg ++ Format.line ++ MessageData.ofGoal mvarId
def checkNotAssigned (mvarId : MVarId) (tacticName : Name) : MetaM Unit :=
whenM (isExprMVarAssigned mvarId) $ throwTacticEx tacticName mvarId "metavariable has already been assigned"
def getMVarType (mvarId : MVarId) : MetaM Expr := do
mvarDecl ← getMVarDecl mvarId;
pure mvarDecl.type
def ppGoal (mvarId : MVarId) : MetaM Format := do
env ← getEnv;
mctx ← getMCtx;
opts ← getOptions;
pure $ ppGoal env mctx opts mvarId
@[inline] protected def orelse {α} (x y : MetaM α) : MetaM α := do
env ← getEnv;
s ← get;
catch x (fun _ => do restore env s.mctx s.postponed; y)
instance Meta.hasOrelse {α} : HasOrelse (MetaM α) := ⟨Meta.orelse⟩
@[init] private def regTraceClasses : IO Unit :=
registerTraceClass `Meta.Tactic
/-- Assign `mvarId` to `sorryAx` -/
def admit (mvarId : MVarId) (synthetic := true) : MetaM Unit :=
withMVarContext mvarId $ do
checkNotAssigned mvarId `admit;
mvarType ← getMVarType mvarId;
val ← mkSorry mvarType synthetic;
assignExprMVar mvarId val;
pure ()
end Meta
end Lean
|
d0e776a18d91584753bc3bd52861f048fce5e3f9 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/2173.lean | d67431611a6cf76256607cb9f86ca76ebc2a9c24 | [
"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 | 562 | lean | set_option pp.raw true
example (n : Nat) : 0 = 0 := by
match n with
| _ => simp (config := {decide := false}) -- this is the default, so masks the problem?
example : True := by
have : True := ⟨⟩
simp (config := {decide := false}) -- unsolved goals
example : True := by
let _x : True := ⟨⟩
simp (config := {decide := false}) -- unsolved goals
example : True := by
suffices True by simp (config := {decide := false}) -- unsolved goals
constructor
example : True := by
show True
simp (config := {decide := false}) -- unsolved goals
|
ea51a453e01ccef30fff50e18f375794ff475253 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/algebra/category/Group/biproducts.lean | c11671aab003c4c2a2dfd18828f3b606d1921cf8 | [
"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,714 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import algebra.group.pi
import algebra.category.Group.preadditive
import category_theory.preadditive.biproducts
import algebra.category.Group.limits
/-!
# The category of abelian groups has finite biproducts
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
open category_theory
open category_theory.limits
open_locale big_operators
universes w u
namespace AddCommGroup
-- As `AddCommGroup` is preadditive, and has all limits, it automatically has biproducts.
instance : has_binary_biproducts AddCommGroup :=
has_binary_biproducts.of_has_binary_products
instance : has_finite_biproducts AddCommGroup :=
has_finite_biproducts.of_has_finite_products
-- We now construct explicit limit data,
-- so we can compare the biproducts to the usual unbundled constructions.
/--
Construct limit data for a binary product in `AddCommGroup`, using `AddCommGroup.of (G × H)`.
-/
@[simps cone_X is_limit_lift]
def binary_product_limit_cone (G H : AddCommGroup.{u}) : limits.limit_cone (pair G H) :=
{ cone :=
{ X := AddCommGroup.of (G × H),
π := { app := λ j, discrete.cases_on j
(λ j, walking_pair.cases_on j (add_monoid_hom.fst G H) (add_monoid_hom.snd G H)),
naturality' := by rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟨⟩⟩⟩; refl, }},
is_limit :=
{ lift := λ s, add_monoid_hom.prod (s.π.app ⟨walking_pair.left⟩) (s.π.app ⟨walking_pair.right⟩),
fac' := by { rintros s (⟨⟩|⟨⟩); { ext x, simp, } },
uniq' := λ s m w, begin
ext; [rw ← w ⟨walking_pair.left⟩, rw ← w ⟨walking_pair.right⟩]; refl,
end, } }
@[simp] lemma binary_product_limit_cone_cone_π_app_left (G H : AddCommGroup.{u}) :
(binary_product_limit_cone G H).cone.π.app ⟨walking_pair.left⟩ = add_monoid_hom.fst G H := rfl
@[simp] lemma binary_product_limit_cone_cone_π_app_right (G H : AddCommGroup.{u}) :
(binary_product_limit_cone G H).cone.π.app ⟨walking_pair.right⟩ = add_monoid_hom.snd G H := rfl
/--
We verify that the biproduct in AddCommGroup is isomorphic to
the cartesian product of the underlying types:
-/
@[simps hom_apply] noncomputable
def biprod_iso_prod (G H : AddCommGroup.{u}) : (G ⊞ H : AddCommGroup) ≅ AddCommGroup.of (G × H) :=
is_limit.cone_point_unique_up_to_iso
(binary_biproduct.is_limit G H)
(binary_product_limit_cone G H).is_limit
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_fst (G H : AddCommGroup.{u}) :
(biprod_iso_prod G H).inv ≫ biprod.fst = add_monoid_hom.fst G H :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.left)
@[simp, elementwise] lemma biprod_iso_prod_inv_comp_snd (G H : AddCommGroup.{u}) :
(biprod_iso_prod G H).inv ≫ biprod.snd = add_monoid_hom.snd G H :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk walking_pair.right)
namespace has_limit
variables {J : Type w} (f : J → AddCommGroup.{max w u})
/--
The map from an arbitrary cone over a indexed family of abelian groups
to the cartesian product of those groups.
-/
@[simps]
def lift (s : fan f) :
s.X ⟶ AddCommGroup.of (Π j,f j) :=
{ to_fun := λ x j, s.π.app ⟨j⟩ x,
map_zero' := by { ext, simp },
map_add' := λ x y, by { ext, simp }, }
/--
Construct limit data for a product in `AddCommGroup`, using `AddCommGroup.of (Π j, F.obj j)`.
-/
@[simps] def product_limit_cone : limits.limit_cone (discrete.functor f) :=
{ cone :=
{ X := AddCommGroup.of (Π j, f j),
π := discrete.nat_trans (λ j, pi.eval_add_monoid_hom (λ j, f j) j.as), },
is_limit :=
{ lift := lift f,
fac' := λ s j, by { cases j, ext, simp, },
uniq' := λ s m w,
begin
ext x j,
dsimp only [has_limit.lift],
simp only [add_monoid_hom.coe_mk],
exact congr_arg (λ g : s.X ⟶ f j, (g : s.X → f j) x) (w ⟨j⟩),
end, }, }
end has_limit
open has_limit
variables {J : Type} [fintype J]
/--
We verify that the biproduct we've just defined is isomorphic to the AddCommGroup structure
on the dependent function type
-/
@[simps hom_apply] noncomputable
def biproduct_iso_pi (f : J → AddCommGroup.{u}) :
(⨁ f : AddCommGroup) ≅ AddCommGroup.of (Π j, f j) :=
is_limit.cone_point_unique_up_to_iso
(biproduct.is_limit f)
(product_limit_cone f).is_limit
@[simp, elementwise] lemma biproduct_iso_pi_inv_comp_π (f : J → AddCommGroup.{u}) (j : J) :
(biproduct_iso_pi f).inv ≫ biproduct.π f j = pi.eval_add_monoid_hom (λ j, f j) j :=
is_limit.cone_point_unique_up_to_iso_inv_comp _ _ (discrete.mk j)
end AddCommGroup
|
69040a181bb6ce745ae2bf805ab808dcd0845814 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/meta/rb_map.lean | 9ec91de1244642dc42ff3c0672364d017590da03 | [] | 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 | 673 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.option.defs
import Mathlib.data.list.defs
import Mathlib.PostPort
namespace Mathlib
/-!
# rb_map
This file defines additional operations on native rb_maps and rb_sets.
These structures are defined in core in `init.meta.rb_map`. They are meta objects,
and are generally the most efficient dictionary structures to use for pure metaprogramming right now.
-/
namespace native
/-! ### Declarations about `rb_set` -/
namespace rb_set
|
0d26422a6eedf31fa56ee6d502bef4b6c447daac | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/KyleAlg.lean | 2163a80c55794cfe7f2adc8a89224b1762209144 | [
"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 | 8,446 | lean | import Lean
/- from core:
class OfNat (α : Type u) (n : Nat) where
ofNat : α
class Mul (α : Type u) where
mul : α → α → α
class Add (α : Type u) where
add : α → α → α
-/
class Inv (α : Type u) where
inv : α → α
postfix:max "⁻¹" => Inv.inv
class One (α : Type u) where
one : α
export One (one)
instance [One α] : OfNat α (nat_lit 1) where
ofNat := one
class Zero (α : Type u) where
zero : α
export Zero (zero)
instance [Zero α] : OfNat α (nat_lit 0) where
ofNat := zero
class MulComm (α : Type u) [Mul α] : Prop where
mulComm : {a b : α} → a * b = b * a
export MulComm (mulComm)
class MulAssoc (α : Type u) [Mul α] : Prop where
mulAssoc : {a b c : α} → a * b * c = a * (b * c)
export MulAssoc (mulAssoc)
class OneUnit (α : Type u) [Mul α] [One α] : Prop where
oneMul : {a : α} → 1 * a = a
mulOne : {a : α} → a * 1 = a
export OneUnit (oneMul mulOne)
class AddComm (α : Type u) [Add α] : Prop where
addComm : {a b : α} → a + b = b + a
export AddComm (addComm)
class AddAssoc (α : Type u) [Add α] : Prop where
addAssoc : {a b c : α} → a + b + c = a + (b + c)
export AddAssoc (addAssoc)
class ZeroUnit (α : Type u) [Add α] [Zero α] : Prop where
zeroAdd : {a : α} → 0 + a = a
addZero : {a : α} → a + 0 = a
export ZeroUnit (zeroAdd addZero)
class InvMul (α : Type u) [Mul α] [One α] [Inv α] : Prop where
invMul : {a : α} → a⁻¹ * a = 1
export InvMul (invMul)
class NegAdd (α : Type u) [Add α] [Zero α] [Neg α] : Prop where
negAdd : {a : α} → -a + a = 0
export NegAdd (negAdd)
class ZeroMul (α : Type u) [Mul α] [Zero α] : Prop where
zeroMul : {a : α} → 0 * a = 0
export ZeroMul (zeroMul)
class Distrib (α : Type u) [Add α] [Mul α] : Prop where
leftDistrib : {a b c : α} → a * (b + c) = a * b + a * c
rightDistrib : {a b c : α} → (a + b) * c = a * c + b * c
export Distrib (leftDistrib rightDistrib)
class Domain (α : Type u) [Mul α] [Zero α] : Prop where
eqZeroOrEqZeroOfMulEqZero : {a b : α} → a * b = 0 → a = 0 ∨ b = 0
export Domain (eqZeroOrEqZeroOfMulEqZero)
class Semigroup (α : Type u) extends Mul α, MulAssoc α
attribute [instance] Semigroup.mk
class AddSemigroup (α : Type u) extends Add α, AddAssoc α
attribute [instance] AddSemigroup.mk
class Monoid (α : Type u) extends Semigroup α, One α, OneUnit α
attribute [instance] Monoid.mk
class AddMonoid (α : Type u) extends AddSemigroup α, Zero α, ZeroUnit α
attribute [instance] AddMonoid.mk
class CommSemigroup (α : Type u) extends Semigroup α, MulComm α
attribute [instance] CommSemigroup.mk
class CommMonoid (α : Type u) extends Monoid α, MulComm α
attribute [instance] CommMonoid.mk
class Group (α : Type u) extends Monoid α, Inv α, InvMul α
attribute [instance] Group.mk
class AddGroup (α : Type u) extends AddMonoid α, Neg α, NegAdd α
attribute [instance] AddGroup.mk
class Semiring (α : Type u) extends AddMonoid α, Monoid α, AddComm α, ZeroMul α, Distrib α
attribute [instance] Semiring.mk
class Ring (α : Type u) extends AddGroup α, Monoid α, AddComm α, Distrib α
attribute [instance] Ring.mk
class CommRing (α : Type u) extends Ring α, MulComm α
attribute [instance] CommRing.mk
class IntegralDomain (α : Type u) extends CommRing α, Domain α
attribute [instance] IntegralDomain.mk
section test1
variable (α : Type u) [h : CommMonoid α]
example : Semigroup α := inferInstance
example : Monoid α := inferInstance
example : CommSemigroup α := inferInstance
end test1
section test2
variable (β : Type u) [CommSemigroup β] [One β] [OneUnit β]
example : Monoid β := inferInstance
example : CommMonoid β := inferInstance
example : Semigroup β := inferInstance
end test2
section test3
variable (β : Type u) [Mul β] [One β] [MulAssoc β] [OneUnit β]
example : Monoid β := inferInstance
example : Semigroup β := inferInstance
end test3
theorem negZero [AddGroup α] : -(0 : α) = 0 := by
rw [←addZero (a := -(0 : α)), negAdd]
theorem subZero [AddGroup α] {a : α} : a + -(0 : α) = a := by
rw [←addZero (a := a), addAssoc, negZero, addZero]
theorem negNeg [AddGroup α] {a : α} : -(-a) = a := by {
rw [←addZero (a := - -a)];
rw [←negAdd (a := a)];
rw [←addAssoc];
rw [negAdd];
rw [zeroAdd];
}
theorem addNeg [AddGroup α] {a : α} : a + -a = 0 := by {
have h : - -a + -a = 0 := by { rw [negAdd] };
rw [negNeg] at h;
exact h
}
theorem addIdemIffZero [AddGroup α] {a : α} : a + a = a ↔ a = 0 := by
apply Iff.intro
focus
intro h
have h' := congrArg (λ x => x + -a) h
simp at h'
rw [addAssoc, addNeg, addZero] at h'
exact h'
focus
intro h
subst a
rw [addZero]
instance [Ring α] : ZeroMul α := by {
apply ZeroMul.mk;
intro a;
have h : 0 * a + 0 * a = 0 * a := by { rw [←rightDistrib, addZero] };
rw [addIdemIffZero (a := 0 * a)] at h;
rw [h];
}
example [Ring α] : Semiring α := inferInstance
section prod
instance [Mul α] [Mul β] : Mul (α × β) where
mul p p' := (p.1 * p'.1, p.2 * p'.2)
instance [Inv α] [Inv β] : Inv (α × β) where
inv p := (p.1⁻¹, p.2⁻¹)
instance [One α] [One β] : One (α × β) where
one := (1, 1)
theorem Product.ext : {p q : α × β} → p.1 = q.1 → p.2 = q.2 → p = q
| (a, b), (c, d) => by simp_all
instance [Semigroup α] [Semigroup β] : Semigroup (α × β) where
mulAssoc := by
intros
apply Product.ext
apply mulAssoc
apply mulAssoc
instance [Monoid α] [Monoid β] : Monoid (α × β) where
oneMul := by
intros
apply Product.ext
apply oneMul
apply oneMul
mulOne := by
intros
apply Product.ext
apply mulOne
apply mulOne
instance [Group α] [Group β] : Group (α × β) where
invMul := by
intros
apply Product.ext
apply invMul
apply invMul
end prod
def test1 {G : Type _} [Group G]: Group (G) := inferInstance
def test2 {G : Type _} [Group G]: Group (G × G) := inferInstance
def test3 {G : Type _} [Group G]: Group (G × G × G) := inferInstance
def test4 {G : Type _} [Group G]: Group (G × G × G × G) := inferInstance
def test5 {G : Type _} [Group G]: Group (G × G × G × G × G) := inferInstance
def test6 {G : Type _} [Group G]: Group (G × G × G × G × G × G) := inferInstance
def test7 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G) := inferInstance
def test8 {G : Type _} [Group G]: Group (G × G × G × G × G × G × G × G) := inferInstance
namespace Lean
unsafe def Expr.dagSizeUnsafe (e : Expr) : IO Nat := do
let (_, s) ← visit e |>.run ({}, 0)
return s.2
where
visit (e : Expr) : StateRefT (Std.HashSet USize × Nat) IO Unit := do
let addr := ptrAddrUnsafe e
unless (← get).1.contains addr do
modify fun (s, c) => (s.insert addr, c+1)
match e with
| Expr.proj _ _ s => visit s
| Expr.forallE _ d b _ => visit d; visit b
| Expr.lam _ d b _ => visit d; visit b
| Expr.letE _ t v b _ => visit t; visit v; visit b
| Expr.app f a => visit f; visit a
| Expr.mdata _ b => visit b
| _ => return ()
@[implementedBy Expr.dagSizeUnsafe]
opaque Expr.dagSize (e : Expr) : IO Nat
def getDeclTypeValueDagSize (declName : Name) : CoreM Nat := do
let info ← getConstInfo declName
let n ← info.type.dagSize
match info.value? with
| none => return n
| some v => return n + (← v.dagSize)
#eval getDeclTypeValueDagSize `test2
#eval getDeclTypeValueDagSize `test3
#eval getDeclTypeValueDagSize `test4
#eval getDeclTypeValueDagSize `test5
#eval getDeclTypeValueDagSize `test6
#eval getDeclTypeValueDagSize `test7
#eval getDeclTypeValueDagSize `test8
def reduceAndGetDagSize (declName : Name) : MetaM Nat := do
let c := mkConst declName [levelOne]
let e ← Meta.reduce c
trace[Meta.debug] "{e}"
e.dagSize
#eval reduceAndGetDagSize `test1
#eval reduceAndGetDagSize `test2
#eval reduceAndGetDagSize `test3
#eval reduceAndGetDagSize `test4
#eval reduceAndGetDagSize `test5
#eval reduceAndGetDagSize `test6
#eval reduceAndGetDagSize `test7
-- Use `set_option` to trace the reduced term
set_option pp.all true in
set_option trace.Meta.debug true in
#eval reduceAndGetDagSize `test8
|
457d52771a83239f1539d1550b235cb214c93558 | 675b8263050a5d74b89ceab381ac81ce70535688 | /src/analysis/specific_limits.lean | 78f26306538acfa388bfac04db9ec526b8a40490 | [
"Apache-2.0"
] | permissive | vozor/mathlib | 5921f55235ff60c05f4a48a90d616ea167068adf | f7e728ad8a6ebf90291df2a4d2f9255a6576b529 | refs/heads/master | 1,675,607,702,231 | 1,609,023,279,000 | 1,609,023,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 28,837 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import algebra.geom_sum
import order.filter.archimedean
import order.iterate
import topology.instances.ennreal
import tactic.ring_exp
import analysis.asymptotics
/-!
# A collection of specific limit computations
-/
noncomputable theory
open classical set function filter finset metric asymptotics
open_locale classical topological_space nat big_operators uniformity nnreal
variables {α : Type*} {β : Type*} {ι : Type*}
lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top :=
tendsto_abs_at_top_at_top
lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} :
(∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f
| ⟨r, hr⟩ :=
begin
refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩,
exact assume i, norm_nonneg _,
simpa only using hr
end
lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) :=
tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top
lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat
lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) :=
by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp }
lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) :
tendsto (λ n : ℕ, C / n) at_top (𝓝 0) :=
by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat
lemma tendsto_one_div_add_at_top_nhds_0_nat :
tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) :=
suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa,
(tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1)
/-! ### Powers -/
lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α}
(h : 0 < r) :
tendsto (λ n:ℕ, (r + 1)^n) at_top at_top :=
tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $
not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h
lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α]
{r : α} (h : 1 < r) :
tendsto (λn:ℕ, r ^ n) at_top at_top :=
sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h)
lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) :
tendsto (λn:ℕ, m ^ n) at_top at_top :=
nat.sub_add_cancel (le_of_lt h) ▸
tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h)
lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] :
tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) :=
tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx
lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] :
tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top :=
(tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm
lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜]
[topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
h₁.eq_or_lt.elim
(assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds])
(assume : 0 < r,
have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0),
from tendsto_inv_at_top_zero.comp
(tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂),
this.congr (λ n, by simp))
lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) :
is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
have H : 0 < r₂ := h₁.trans_lt h₂,
is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $
(tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr
(λ n, div_pow _ _ _)
lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) :
is_O (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O)
lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : abs r₁ < abs r₂) :
is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top :=
begin
refine (is_o.of_norm_left _).of_norm_right,
exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂)
end
/-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`.
* 0: $f n = o(a ^ n)$ for some $-R < a < R$;
* 1: $f n = o(a ^ n)$ for some $0 < a < R$;
* 2: $f n = O(a ^ n)$ for some $-R < a < R$;
* 3: $f n = O(a ^ n)$ for some $0 < a < R$;
* 4: there exist `a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`;
* 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`;
* 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`;
* 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`.
NB: For backwards compatibility, if you add more items to the list, please append them at the end of
the list. -/
lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) :
tfae [∃ a ∈ Ioo (-R) R, is_o f (pow a) at_top,
∃ a ∈ Ioo 0 R, is_o f (pow a) at_top,
∃ a ∈ Ioo (-R) R, is_O f (pow a) at_top,
∃ a ∈ Ioo 0 R, is_O f (pow a) at_top,
∃ (a < R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n,
∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n,
∃ a < R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n,
∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n] :=
begin
have A : Ico 0 R ⊆ Ioo (-R) R,
from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩,
have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A,
-- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1
tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩,
tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩,
tfae_have : 3 → 2,
{ rintro ⟨a, ha, H⟩,
rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩,
exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩,
H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ },
tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩,
tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩,
-- Add 5 and 6 using 4 → 6 → 5 → 3
tfae_have : 4 → 6,
{ rintro ⟨a, ha, H⟩,
rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩,
refine ⟨a, ha, C, hC₀, λ n, _⟩,
simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le]
using hC (pow_ne_zero n ha.1.ne') },
tfae_have : 6 → 5, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩,
tfae_have : 5 → 3,
{ rintro ⟨a, ha, C, hC₀, H⟩,
rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩,
{ exact (lt_irrefl 0 hC₀).elim },
exact ⟨a, A ⟨ha₀, ha⟩,
is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ },
-- Add 7 and 8 using 2 → 8 → 7 → 3
tfae_have : 2 → 8,
{ rintro ⟨a, ha, H⟩,
refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩,
rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn },
tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩,
tfae_have : 7 → 3,
{ rintro ⟨a, ha, H⟩,
have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans),
refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩,
simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] },
tfae_finish
end
lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [metric_space α]
{r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) :
(𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) :=
metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0,
(exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩
lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n)
(h : ∀ k < n, c * u k < u (k + 1)) :
c ^ n * u 0 < u n :=
(monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn (by simp)
(λ k hk, by simp [pow_succ, mul_assoc]) h
lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) :
c ^ n * u 0 ≤ u n :=
by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl]
/-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`,
then it goes to +∞. -/
lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c)
(hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top :=
tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $
(tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀
lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero,
tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr]
lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ennreal} (hr : r < 1) :
tendsto (λ n:ℕ, r^n) at_top (𝓝 0) :=
begin
rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
rw [← ennreal.coe_zero],
norm_cast at *,
apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr
end
/-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/
lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R}
(h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) :=
begin
apply squeeze_zero_norm' (eventually_norm_pow_le x),
exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h,
end
lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) :
tendsto (λn:ℕ, r^n) at_top (𝓝 0) :=
tendsto_pow_at_top_nhds_0_of_norm_lt_1 h
/-! ### Geometric series-/
section geometric
lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) :
has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
have r ≠ 1, from ne_of_lt h₂,
have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds,
have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_series r n) := rfl,
(has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $
by simp [neg_inv, geom_sum, div_eq_mul_inv, *] at *
lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩
lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq
lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 :=
by convert has_sum_geometric_of_lt_1 _ _; norm_num
lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) :=
⟨_, has_sum_geometric_two⟩
lemma tsum_geometric_two : (∑'n:ℕ, ((1:ℝ)/2) ^ n) = 2 :=
has_sum_geometric_two.tsum_eq
lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 :=
begin
have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i,
{ intro i, apply pow_nonneg, norm_num },
convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two,
exact tsum_geometric_two.symm
end
lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a :=
begin
convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1
(le_of_lt one_half_pos) one_half_lt_one),
{ funext n, simp, refl, },
{ norm_num }
end
lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) :=
⟨a, has_sum_geometric_two' a⟩
lemma tsum_geometric_two' (a : ℝ) : (∑' n:ℕ, (a / 2) / 2^n) = a :=
(has_sum_geometric_two' a).tsum_eq
lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) :
has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ :=
begin
apply nnreal.has_sum_coe.1,
push_cast,
rw [nnreal.coe_sub (le_of_lt hr)],
exact has_sum_geometric_of_lt_1 r.coe_nonneg hr
end
lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) :=
⟨_, nnreal.has_sum_geometric hr⟩
lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
(nnreal.has_sum_geometric hr).tsum_eq
/-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number,
and for `1 ≤ r` the RHS equals `∞`. -/
lemma ennreal.tsum_geometric (r : ennreal) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
begin
cases lt_or_le r 1 with hr hr,
{ rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩,
norm_cast at *,
convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr),
rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] },
{ rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top],
refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp
(λ n hn, lt_of_lt_of_le hn _),
have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr,
calc (n:ennreal) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range]
... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) }
end
variables {K : Type*} [normed_field K] {ξ : K}
lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ :=
begin
have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] },
have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)),
from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds,
have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_series ξ n) := rfl,
rw [has_sum_iff_tendsto_nat_of_summable_norm, B],
{ simpa [geom_sum, xi_ne_one, neg_inv] using A },
{ simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] }
end
lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) :=
⟨_, has_sum_geometric_of_norm_lt_1 h⟩
lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : (∑'n:ℕ, ξ ^ n) = (1 - ξ)⁻¹ :=
(has_sum_geometric_of_norm_lt_1 h).tsum_eq
lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ :=
has_sum_geometric_of_norm_lt_1 h
lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) :=
summable_geometric_of_norm_lt_1 h
lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : (∑'n:ℕ, r ^ n) = (1 - r)⁻¹ :=
tsum_geometric_of_norm_lt_1 h
/-- A geometric series in a normed field is summable iff the norm of the common ratio is less than
one. -/
@[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 :=
begin
refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩,
obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ :=
(h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists,
simp only [normed_field.norm_pow, dist_zero_right] at hk,
rw [← one_pow k] at hk,
exact lt_of_pow_lt_pow _ zero_le_one hk
end
end geometric
/-!
### Sequences with geometrically decaying distance in metric spaces
In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance
between two consecutive terms decays geometrically. We show that such sequences are Cauchy
sequences, and bound their distances to the limit. We also discuss series with geometrically
decaying terms.
-/
section edist_le_geometric
variables [emetric_space α] (r C : ennreal) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n)
include hr hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`,
then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f :=
begin
refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _,
rw [ennreal.tsum_mul_left, ennreal.tsum_geometric],
refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _),
exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr)
end
omit hr hC
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
edist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _,
simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, ennreal.div_def, mul_assoc]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
edist (f 0) a ≤ C / (1 - r) :=
by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0
end edist_le_geometric
section edist_le_geometric_two
variables [emetric_space α] (C : ennreal) (hC : C ≠ ⊤) {f : ℕ → α}
(hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a))
include hC hu
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/
lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu,
simp [ennreal.one_lt_two]
end
omit hC
include ha
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) :
edist (f n) a ≤ 2 * C / 2^n :=
begin
simp only [ennreal.div_def, ennreal.inv_pow] at hu,
rw [ennreal.div_def, mul_assoc, mul_comm, ennreal.inv_pow],
convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n,
rw [ennreal.one_sub_inv_two, ennreal.inv_inv]
end
/-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from
`f 0` to the limit of `f` is bounded above by `2 * C`. -/
lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C :=
by simpa only [pow_zero, ennreal.div_def, ennreal.inv_one, mul_one]
using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0
end edist_le_geometric_two
section le_geometric
variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α}
(hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n)
include hr hu
lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) :=
begin
rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩,
{ simp [has_sum_zero] },
{ refine has_sum.mul_left C _,
simpa using has_sum_geometric_of_lt_1 r₀ hr }
end
variables (r C)
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence.
Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/
lemma cauchy_seq_of_le_geometric : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C / (1 - r) :=
(aux_has_sum_of_le_geometric hr hu).tsum_eq ▸
dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha
/-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from
`f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/
lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ (C * r^n) / (1 - r) :=
begin
have := aux_has_sum_of_le_geometric hr hu,
convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n,
simp only [pow_add, mul_left_comm C, mul_div_right_comm],
rw [mul_comm],
exact (this.mul_left _).tsum_eq.symm
end
omit hr hu
variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n)
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/
lemma cauchy_seq_of_le_geometric_two : cauchy_seq f :=
cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f 0` to the limit of `f` is bounded above by `C`. -/
lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) :
dist (f 0) a ≤ C :=
(tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha
include hu₂
/-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from
`f n` to the limit of `f` is bounded above by `C / 2^n`. -/
lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) :
dist (f n) a ≤ C / 2^n :=
begin
convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n,
simp only [add_comm n, pow_add, (div_div_eq_div_mul _ _ _).symm],
symmetry,
exact ((has_sum_geometric_two' C).mul_right _).tsum_eq
end
end le_geometric
section summable_le_geometric
variables [normed_group α] {r C : ℝ} {f : ℕ → α}
lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) :
dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n :=
begin
rw [sum_range_succ, dist_eq_norm, ← norm_neg],
convert hf n,
rw [neg_sub, add_sub_cancel]
end
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a
Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/
lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) :
cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) :=
cauchy_seq_finset_of_norm_bounded _
(aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf
/-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within
distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or
`0 ≤ C`. -/
lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n)
{a : α} (ha : has_sum f a) (n : ℕ) :
∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) :=
begin
rw ← dist_eq_norm,
apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf),
exact ha.tendsto_sum_nat
end
end summable_le_geometric
section normed_ring_geometric
variables {R : Type*} [normed_ring R] [complete_space R]
open normed_space
/-- A geometric series in a complete normed ring is summable.
Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/
lemma normed_ring.summable_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) :=
begin
have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h,
refine summable_of_norm_bounded_eventually _ h1 _,
rw nat.cofinite_eq_at_top,
exact eventually_norm_pow_le x,
end
/-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the
normed ring satisfies the axiom `∥1∥ = 1`. -/
lemma normed_ring.tsum_geometric_of_norm_lt_1
(x : R) (h : ∥x∥ < 1) : ∥(∑' (n:ℕ), x ^ n)∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ :=
begin
rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h),
simp only [pow_zero],
refine le_trans (norm_add_le _ _) _,
have : ∥(∑' (b : ℕ), (λ n, x ^ (n + 1)) b)∥ ≤ (1 - ∥x∥)⁻¹ - 1,
{ refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)),
convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h),
simp },
linarith
end
lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) :
(∑' (i:ℕ), x ^ i) * (1 - x) = 1 :=
begin
have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1),
{ simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←geom_sum_mul_neg, geom_series_def, finset.sum_mul],
end
lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) :
(1 - x) * (∑' (i:ℕ), x ^ i) = 1 :=
begin
have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x),
refine tendsto_nhds_unique this.tendsto_sum_nat _,
have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1),
{ simpa using tendsto_const_nhds.sub
(tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) },
convert ← this,
ext n,
rw [←mul_neg_geom_sum, geom_series_def, finset.mul_sum]
end
end normed_ring_geometric
/-! ### Positive sequences with small sums on encodable types -/
/-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/
def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε)
(ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} :=
begin
let f := λ n, (ε / 2) / 2 ^ n,
have hf : has_sum f ε := has_sum_geometric_two' _,
have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _),
refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩,
rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩,
refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩,
{ assume i _, exact le_of_lt (f0 _) },
{ assume n, exact le_refl _ }
end
namespace nnreal
theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε :=
let ⟨a, a0, aε⟩ := exists_between hε in
let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in
⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i,
⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc,
lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩
end nnreal
namespace ennreal
theorem exists_pos_sum_of_encodable {ε : ennreal} (hε : 0 < ε) (ι) [encodable ι] :
∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ (∑' i, (ε' i : ennreal)) < ε :=
begin
rcases exists_between hε with ⟨r, h0r, hrε⟩,
rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩,
rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩,
exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩
end
end ennreal
/-!
### Factorial
-/
lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top :=
tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩)
lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) :=
tendsto_of_tendsto_of_tendsto_of_le_of_le'
tendsto_const_nhds
(tendsto_const_div_at_top_nhds_0_nat 1)
(eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le)
(pow_nonneg (by exact_mod_cast n.zero_le) _))
begin
refine (eventually_gt_at_top 0).mono (λ n hn, _),
rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩,
rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div,
prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib,
finset.prod_range_succ'],
simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one],
refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _);
intros x hx; rw finset.mem_range at hx,
{ refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith },
{ refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith }
end
|
490894d7d0a0edae2feefe50e32af0ddaeb3f6b1 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/measure_theory/decomposition/jordan.lean | de697ffb6d4429839e844aabfa516daf81d55296 | [
"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 | 25,163 | 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.decomposition.signed_hahn
import measure_theory.measure.mutually_singular
/-!
# Jordan decomposition
This file proves the existence and uniqueness of the Jordan decomposition for signed measures.
The Jordan decomposition theorem states that, given a signed measure `s`, there exists a
unique pair of mutually singular measures `μ` and `ν`, such that `s = μ - ν`.
The Jordan decomposition theorem for measures is a corollary of the Hahn decomposition theorem and
is useful for the Lebesgue decomposition theorem.
## Main definitions
* `measure_theory.jordan_decomposition`: a Jordan decomposition of a measurable space is a
pair of mutually singular finite measures. We say `j` is a Jordan decomposition of a signed
measure `s` if `s = j.pos_part - j.neg_part`.
* `measure_theory.signed_measure.to_jordan_decomposition`: the Jordan decomposition of a
signed measure.
* `measure_theory.signed_measure.to_jordan_decomposition_equiv`: is the `equiv` between
`measure_theory.signed_measure` and `measure_theory.jordan_decomposition` formed by
`measure_theory.signed_measure.to_jordan_decomposition`.
## Main results
* `measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition` : the Jordan
decomposition theorem.
* `measure_theory.jordan_decomposition.to_signed_measure_injective` : the Jordan decomposition of a
signed measure is unique.
## Tags
Jordan decomposition theorem
-/
noncomputable theory
open_locale classical measure_theory ennreal nnreal
variables {α β : Type*} [measurable_space α]
namespace measure_theory
/-- A Jordan decomposition of a measurable space is a pair of mutually singular,
finite measures. -/
@[ext] structure jordan_decomposition (α : Type*) [measurable_space α] :=
(pos_part neg_part : measure α)
[pos_part_finite : is_finite_measure pos_part]
[neg_part_finite : is_finite_measure neg_part]
(mutually_singular : pos_part ⟂ₘ neg_part)
attribute [instance] jordan_decomposition.pos_part_finite
attribute [instance] jordan_decomposition.neg_part_finite
namespace jordan_decomposition
open measure vector_measure
variable (j : jordan_decomposition α)
instance : has_zero (jordan_decomposition α) :=
{ zero := ⟨0, 0, mutually_singular.zero_right⟩ }
instance : inhabited (jordan_decomposition α) :=
{ default := 0 }
instance : has_involutive_neg (jordan_decomposition α) :=
{ neg := λ j, ⟨j.neg_part, j.pos_part, j.mutually_singular.symm⟩,
neg_neg := λ j, jordan_decomposition.ext _ _ rfl rfl }
instance : has_smul ℝ≥0 (jordan_decomposition α) :=
{ smul := λ r j, ⟨r • j.pos_part, r • j.neg_part,
mutually_singular.smul _ (mutually_singular.smul _ j.mutually_singular.symm).symm⟩ }
instance has_smul_real : has_smul ℝ (jordan_decomposition α) :=
{ smul := λ r j, if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) }
@[simp] lemma zero_pos_part : (0 : jordan_decomposition α).pos_part = 0 := rfl
@[simp] lemma zero_neg_part : (0 : jordan_decomposition α).neg_part = 0 := rfl
@[simp] lemma neg_pos_part : (-j).pos_part = j.neg_part := rfl
@[simp] lemma neg_neg_part : (-j).neg_part = j.pos_part := rfl
@[simp] lemma smul_pos_part (r : ℝ≥0) : (r • j).pos_part = r • j.pos_part := rfl
@[simp] lemma smul_neg_part (r : ℝ≥0) : (r • j).neg_part = r • j.neg_part := rfl
lemma real_smul_def (r : ℝ) (j : jordan_decomposition α) :
r • j = if hr : 0 ≤ r then r.to_nnreal • j else - ((-r).to_nnreal • j) :=
rfl
@[simp] lemma coe_smul (r : ℝ≥0) : (r : ℝ) • j = r • j :=
show dite _ _ _ = _, by rw [dif_pos (nnreal.coe_nonneg r), real.to_nnreal_coe]
lemma real_smul_nonneg (r : ℝ) (hr : 0 ≤ r) : r • j = r.to_nnreal • j :=
dif_pos hr
lemma real_smul_neg (r : ℝ) (hr : r < 0) : r • j = - ((-r).to_nnreal • j) :=
dif_neg (not_le.2 hr)
lemma real_smul_pos_part_nonneg (r : ℝ) (hr : 0 ≤ r) :
(r • j).pos_part = r.to_nnreal • j.pos_part :=
by { rw [real_smul_def, ← smul_pos_part, dif_pos hr] }
lemma real_smul_neg_part_nonneg (r : ℝ) (hr : 0 ≤ r) :
(r • j).neg_part = r.to_nnreal • j.neg_part :=
by { rw [real_smul_def, ← smul_neg_part, dif_pos hr] }
lemma real_smul_pos_part_neg (r : ℝ) (hr : r < 0) :
(r • j).pos_part = (-r).to_nnreal • j.neg_part :=
by { rw [real_smul_def, ← smul_neg_part, dif_neg (not_le.2 hr), neg_pos_part] }
lemma real_smul_neg_part_neg (r : ℝ) (hr : r < 0) :
(r • j).neg_part = (-r).to_nnreal • j.pos_part :=
by { rw [real_smul_def, ← smul_pos_part, dif_neg (not_le.2 hr), neg_neg_part] }
/-- The signed measure associated with a Jordan decomposition. -/
def to_signed_measure : signed_measure α :=
j.pos_part.to_signed_measure - j.neg_part.to_signed_measure
lemma to_signed_measure_zero : (0 : jordan_decomposition α).to_signed_measure = 0 :=
begin
ext1 i hi,
erw [to_signed_measure, to_signed_measure_sub_apply hi, sub_self, zero_apply],
end
lemma to_signed_measure_neg : (-j).to_signed_measure = -j.to_signed_measure :=
begin
ext1 i hi,
rw [neg_apply, to_signed_measure, to_signed_measure,
to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, neg_sub],
refl,
end
lemma to_signed_measure_smul (r : ℝ≥0) : (r • j).to_signed_measure = r • j.to_signed_measure :=
begin
ext1 i hi,
rw [vector_measure.smul_apply, to_signed_measure, to_signed_measure,
to_signed_measure_sub_apply hi, to_signed_measure_sub_apply hi, smul_sub,
smul_pos_part, smul_neg_part, ← ennreal.to_real_smul, ← ennreal.to_real_smul],
refl
end
/-- A Jordan decomposition provides a Hahn decomposition. -/
lemma exists_compl_positive_negative :
∃ S : set α, measurable_set S ∧
j.to_signed_measure ≤[S] 0 ∧ 0 ≤[Sᶜ] j.to_signed_measure ∧
j.pos_part S = 0 ∧ j.neg_part Sᶜ = 0 :=
begin
obtain ⟨S, hS₁, hS₂, hS₃⟩ := j.mutually_singular,
refine ⟨S, hS₁, _, _, hS₂, hS₃⟩,
{ refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _),
rw [to_signed_measure, to_signed_measure_sub_apply hA,
show j.pos_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₂ ▸ measure_mono hA₁),
ennreal.zero_to_real, zero_sub, neg_le, zero_apply, neg_zero],
exact ennreal.to_real_nonneg },
{ refine restrict_le_restrict_of_subset_le _ _ (λ A hA hA₁, _),
rw [to_signed_measure, to_signed_measure_sub_apply hA,
show j.neg_part A = 0, by exact nonpos_iff_eq_zero.1 (hS₃ ▸ measure_mono hA₁),
ennreal.zero_to_real, sub_zero],
exact ennreal.to_real_nonneg },
end
end jordan_decomposition
namespace signed_measure
open classical jordan_decomposition measure set vector_measure
variables {s : signed_measure α} {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν]
/-- Given a signed measure `s`, `s.to_jordan_decomposition` is the Jordan decomposition `j`,
such that `s = j.to_signed_measure`. This property is known as the Jordan decomposition
theorem, and is shown by
`measure_theory.signed_measure.to_signed_measure_to_jordan_decomposition`. -/
def to_jordan_decomposition (s : signed_measure α) : jordan_decomposition α :=
let i := some s.exists_compl_positive_negative in
let hi := some_spec s.exists_compl_positive_negative in
{ pos_part := s.to_measure_of_zero_le i hi.1 hi.2.1,
neg_part := s.to_measure_of_le_zero iᶜ hi.1.compl hi.2.2,
pos_part_finite := infer_instance,
neg_part_finite := infer_instance,
mutually_singular :=
begin
refine ⟨iᶜ, hi.1.compl, _, _⟩,
{ rw [to_measure_of_zero_le_apply _ _ hi.1 hi.1.compl], simp },
{ rw [to_measure_of_le_zero_apply _ _ hi.1.compl hi.1.compl.compl], simp }
end }
lemma to_jordan_decomposition_spec (s : signed_measure α) :
∃ (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) (hi₃ : s ≤[iᶜ] 0),
s.to_jordan_decomposition.pos_part = s.to_measure_of_zero_le i hi₁ hi₂ ∧
s.to_jordan_decomposition.neg_part = s.to_measure_of_le_zero iᶜ hi₁.compl hi₃ :=
begin
set i := some s.exists_compl_positive_negative,
obtain ⟨hi₁, hi₂, hi₃⟩ := some_spec s.exists_compl_positive_negative,
exact ⟨i, hi₁, hi₂, hi₃, rfl, rfl⟩,
end
/-- **The Jordan decomposition theorem**: Given a signed measure `s`, there exists a pair of
mutually singular measures `μ` and `ν` such that `s = μ - ν`. In this case, the measures `μ`
and `ν` are given by `s.to_jordan_decomposition.pos_part` and
`s.to_jordan_decomposition.neg_part` respectively.
Note that we use `measure_theory.jordan_decomposition.to_signed_measure` to represent the
signed measure corresponding to
`s.to_jordan_decomposition.pos_part - s.to_jordan_decomposition.neg_part`. -/
@[simp] lemma to_signed_measure_to_jordan_decomposition (s : signed_measure α) :
s.to_jordan_decomposition.to_signed_measure = s :=
begin
obtain ⟨i, hi₁, hi₂, hi₃, hμ, hν⟩ := s.to_jordan_decomposition_spec,
simp only [jordan_decomposition.to_signed_measure, hμ, hν],
ext k hk,
rw [to_signed_measure_sub_apply hk, to_measure_of_zero_le_apply _ hi₂ hi₁ hk,
to_measure_of_le_zero_apply _ hi₃ hi₁.compl hk],
simp only [ennreal.coe_to_real, subtype.coe_mk, ennreal.some_eq_coe, sub_neg_eq_add],
rw [← of_union _ (measurable_set.inter hi₁ hk) (measurable_set.inter hi₁.compl hk),
set.inter_comm i, set.inter_comm iᶜ, set.inter_union_compl _ _],
{ apply_instance },
{ exact (disjoint_compl_right.inf_left _).inf_right _ }
end
section
variables {u v w : set α}
/-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a positive set `u`. -/
lemma subset_positive_null_set
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : 0 ≤[u] s) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 :=
begin
have : s v + s (w \ v) = 0,
{ rw [← hw₁, ← of_union set.disjoint_sdiff_right hv (hw.diff hv),
set.union_diff_self, set.union_eq_self_of_subset_left hwt],
apply_instance },
have h₁ := nonneg_of_zero_le_restrict _ (restrict_le_restrict_subset _ _ hu hsu (hwt.trans hw₂)),
have h₂ := nonneg_of_zero_le_restrict _
(restrict_le_restrict_subset _ _ hu hsu ((w.diff_subset v).trans hw₂)),
linarith,
end
/-- A subset `v` of a null-set `w` has zero measure if `w` is a subset of a negative set `u`. -/
lemma subset_negative_null_set
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : s ≤[u] 0) (hw₁ : s w = 0) (hw₂ : w ⊆ u) (hwt : v ⊆ w) : s v = 0 :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
have := subset_positive_null_set hu hv hw hsu,
simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this,
exact this hw₁ hw₂ hwt,
end
/-- If the symmetric difference of two positive sets is a null-set, then so are the differences
between the two sets. -/
lemma of_diff_eq_zero_of_symm_diff_eq_zero_positive
(hu : measurable_set u) (hv : measurable_set v)
(hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) :
s (u \ v) = 0 ∧ s (v \ u) = 0 :=
begin
rw restrict_le_restrict_iff at hsu hsv,
have a := hsu (hu.diff hv) (u.diff_subset v),
have b := hsv (hv.diff hu) (v.diff_subset u),
erw [of_union (set.disjoint_of_subset_left (u.diff_subset v) disjoint_sdiff_self_right)
(hu.diff hv) (hv.diff hu)] at hs,
rw zero_apply at a b,
split,
all_goals { linarith <|> apply_instance <|> assumption },
end
/-- If the symmetric difference of two negative sets is a null-set, then so are the differences
between the two sets. -/
lemma of_diff_eq_zero_of_symm_diff_eq_zero_negative
(hu : measurable_set u) (hv : measurable_set v)
(hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) :
s (u \ v) = 0 ∧ s (v \ u) = 0 :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv,
have := of_diff_eq_zero_of_symm_diff_eq_zero_positive hu hv hsu hsv,
simp only [pi.neg_apply, neg_eq_zero, coe_neg] at this,
exact this hs,
end
lemma of_inter_eq_of_symm_diff_eq_zero_positive
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : 0 ≤[u] s) (hsv : 0 ≤[v] s) (hs : s (u ∆ v) = 0) :
s (w ∩ u) = s (w ∩ v) :=
begin
have hwuv : s ((w ∩ u) ∆ (w ∩ v)) = 0,
{ refine subset_positive_null_set (hu.union hv) ((hw.inter hu).symm_diff (hw.inter hv))
(hu.symm_diff hv) (restrict_le_restrict_union _ _ hu hsu hv hsv) hs symm_diff_subset_union _,
rw ←inter_symm_diff_distrib_left,
exact inter_subset_right _ _ },
obtain ⟨huv, hvu⟩ := of_diff_eq_zero_of_symm_diff_eq_zero_positive
(hw.inter hu) (hw.inter hv)
(restrict_le_restrict_subset _ _ hu hsu (w.inter_subset_right u))
(restrict_le_restrict_subset _ _ hv hsv (w.inter_subset_right v)) hwuv,
rw [← of_diff_of_diff_eq_zero (hw.inter hu) (hw.inter hv) hvu, huv, zero_add]
end
lemma of_inter_eq_of_symm_diff_eq_zero_negative
(hu : measurable_set u) (hv : measurable_set v) (hw : measurable_set w)
(hsu : s ≤[u] 0) (hsv : s ≤[v] 0) (hs : s (u ∆ v) = 0) :
s (w ∩ u) = s (w ∩ v) :=
begin
rw [← s.neg_le_neg_iff _ hu, neg_zero] at hsu,
rw [← s.neg_le_neg_iff _ hv, neg_zero] at hsv,
have := of_inter_eq_of_symm_diff_eq_zero_positive hu hv hw hsu hsv,
simp only [pi.neg_apply, neg_inj, neg_eq_zero, coe_neg] at this,
exact this hs,
end
end
end signed_measure
namespace jordan_decomposition
open measure vector_measure signed_measure function
private lemma eq_of_pos_part_eq_pos_part {j₁ j₂ : jordan_decomposition α}
(hj : j₁.pos_part = j₂.pos_part) (hj' : j₁.to_signed_measure = j₂.to_signed_measure) :
j₁ = j₂ :=
begin
ext1,
{ exact hj },
{ rw ← to_signed_measure_eq_to_signed_measure_iff,
suffices : j₁.pos_part.to_signed_measure - j₁.neg_part.to_signed_measure =
j₁.pos_part.to_signed_measure - j₂.neg_part.to_signed_measure,
{ exact sub_right_inj.mp this },
convert hj' }
end
/-- The Jordan decomposition of a signed measure is unique. -/
theorem to_signed_measure_injective :
injective $ @jordan_decomposition.to_signed_measure α _ :=
begin
/- The main idea is that two Jordan decompositions of a signed measure provide two
Hahn decompositions for that measure. Then, from `of_symm_diff_compl_positive_negative`,
the symmetric difference of the two Hahn decompositions has measure zero, thus, allowing us to
show the equality of the underlying measures of the Jordan decompositions. -/
intros j₁ j₂ hj,
-- obtain the two Hahn decompositions from the Jordan decompositions
obtain ⟨S, hS₁, hS₂, hS₃, hS₄, hS₅⟩ := j₁.exists_compl_positive_negative,
obtain ⟨T, hT₁, hT₂, hT₃, hT₄, hT₅⟩ := j₂.exists_compl_positive_negative,
rw ← hj at hT₂ hT₃,
-- the symmetric differences of the two Hahn decompositions have measure zero
obtain ⟨hST₁, -⟩ := of_symm_diff_compl_positive_negative hS₁.compl hT₁.compl
⟨hS₃, (compl_compl S).symm ▸ hS₂⟩ ⟨hT₃, (compl_compl T).symm ▸ hT₂⟩,
-- it suffices to show the Jordan decompositions have the same positive parts
refine eq_of_pos_part_eq_pos_part _ hj,
ext1 i hi,
-- we see that the positive parts of the two Jordan decompositions are equal to their
-- associated signed measures restricted on their associated Hahn decompositions
have hμ₁ : (j₁.pos_part i).to_real = j₁.to_signed_measure (i ∩ Sᶜ),
{ rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hS₁.compl),
show j₁.neg_part (i ∩ Sᶜ) = 0, by exact nonpos_iff_eq_zero.1
(hS₅ ▸ measure_mono (set.inter_subset_right _ _)),
ennreal.zero_to_real, sub_zero],
conv_lhs { rw ← set.inter_union_compl i S },
rw [measure_union, show j₁.pos_part (i ∩ S) = 0, by exact nonpos_iff_eq_zero.1
(hS₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add],
{ refine set.disjoint_of_subset_left (set.inter_subset_right _ _)
(set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) },
{ exact hi.inter hS₁.compl } },
have hμ₂ : (j₂.pos_part i).to_real = j₂.to_signed_measure (i ∩ Tᶜ),
{ rw [to_signed_measure, to_signed_measure_sub_apply (hi.inter hT₁.compl),
show j₂.neg_part (i ∩ Tᶜ) = 0, by exact nonpos_iff_eq_zero.1
(hT₅ ▸ measure_mono (set.inter_subset_right _ _)),
ennreal.zero_to_real, sub_zero],
conv_lhs { rw ← set.inter_union_compl i T },
rw [measure_union, show j₂.pos_part (i ∩ T) = 0, by exact nonpos_iff_eq_zero.1
(hT₄ ▸ measure_mono (set.inter_subset_right _ _)), zero_add],
{ exact set.disjoint_of_subset_left (set.inter_subset_right _ _)
(set.disjoint_of_subset_right (set.inter_subset_right _ _) disjoint_compl_right) },
{ exact hi.inter hT₁.compl } },
-- since the two signed measures associated with the Jordan decompositions are the same,
-- and the symmetric difference of the Hahn decompositions have measure zero, the result follows
rw [← ennreal.to_real_eq_to_real (measure_ne_top _ _) (measure_ne_top _ _), hμ₁, hμ₂, ← hj],
exact of_inter_eq_of_symm_diff_eq_zero_positive hS₁.compl hT₁.compl hi hS₃ hT₃ hST₁,
all_goals { apply_instance },
end
@[simp]
lemma to_jordan_decomposition_to_signed_measure (j : jordan_decomposition α) :
(j.to_signed_measure).to_jordan_decomposition = j :=
(@to_signed_measure_injective _ _ j (j.to_signed_measure).to_jordan_decomposition (by simp)).symm
end jordan_decomposition
namespace signed_measure
open jordan_decomposition
/-- `measure_theory.signed_measure.to_jordan_decomposition` and
`measure_theory.jordan_decomposition.to_signed_measure` form a `equiv`. -/
@[simps apply symm_apply]
def to_jordan_decomposition_equiv (α : Type*) [measurable_space α] :
signed_measure α ≃ jordan_decomposition α :=
{ to_fun := to_jordan_decomposition,
inv_fun := to_signed_measure,
left_inv := to_signed_measure_to_jordan_decomposition,
right_inv := to_jordan_decomposition_to_signed_measure }
lemma to_jordan_decomposition_zero : (0 : signed_measure α).to_jordan_decomposition = 0 :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_zero],
end
lemma to_jordan_decomposition_neg (s : signed_measure α) :
(-s).to_jordan_decomposition = -s.to_jordan_decomposition :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_neg],
end
lemma to_jordan_decomposition_smul (s : signed_measure α) (r : ℝ≥0) :
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
apply to_signed_measure_injective,
simp [to_signed_measure_smul],
end
private
lemma to_jordan_decomposition_smul_real_nonneg (s : signed_measure α) (r : ℝ) (hr : 0 ≤ r):
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
lift r to ℝ≥0 using hr,
rw [jordan_decomposition.coe_smul, ← to_jordan_decomposition_smul],
refl
end
lemma to_jordan_decomposition_smul_real (s : signed_measure α) (r : ℝ) :
(r • s).to_jordan_decomposition = r • s.to_jordan_decomposition :=
begin
by_cases hr : 0 ≤ r,
{ exact to_jordan_decomposition_smul_real_nonneg s r hr },
{ ext1,
{ rw [real_smul_pos_part_neg _ _ (not_le.1 hr),
show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg,
neg_pos_part, to_jordan_decomposition_smul_real_nonneg, ← smul_neg_part,
real_smul_nonneg],
all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } },
{ rw [real_smul_neg_part_neg _ _ (not_le.1 hr),
show r • s = -(-r • s), by rw [neg_smul, neg_neg], to_jordan_decomposition_neg,
neg_neg_part, to_jordan_decomposition_smul_real_nonneg, ← smul_pos_part,
real_smul_nonneg],
all_goals { exact left.nonneg_neg_iff.2 (le_of_lt (not_le.1 hr)) } } }
end
lemma to_jordan_decomposition_eq {s : signed_measure α} {j : jordan_decomposition α}
(h : s = j.to_signed_measure) : s.to_jordan_decomposition = j :=
by rw [h, to_jordan_decomposition_to_signed_measure]
/-- The total variation of a signed measure. -/
def total_variation (s : signed_measure α) : measure α :=
s.to_jordan_decomposition.pos_part + s.to_jordan_decomposition.neg_part
lemma total_variation_zero : (0 : signed_measure α).total_variation = 0 :=
by simp [total_variation, to_jordan_decomposition_zero]
lemma total_variation_neg (s : signed_measure α) : (-s).total_variation = s.total_variation :=
by simp [total_variation, to_jordan_decomposition_neg, add_comm]
lemma null_of_total_variation_zero (s : signed_measure α) {i : set α}
(hs : s.total_variation i = 0) : s i = 0 :=
begin
rw [total_variation, measure.coe_add, pi.add_apply, add_eq_zero_iff] at hs,
rw [← to_signed_measure_to_jordan_decomposition s, to_signed_measure, vector_measure.coe_sub,
pi.sub_apply, measure.to_signed_measure_apply, measure.to_signed_measure_apply],
by_cases hi : measurable_set i,
{ rw [if_pos hi, if_pos hi], simp [hs.1, hs.2] },
{ simp [if_neg hi] }
end
lemma absolutely_continuous_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) :
s ≪ᵥ μ ↔ s.total_variation ≪ μ.ennreal_to_measure :=
begin
split; intro h,
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec,
rw [total_variation, measure.add_apply, hpos, hneg,
to_measure_of_zero_le_apply _ _ _ hS₁, to_measure_of_le_zero_apply _ _ _ hS₁],
rw ← vector_measure.absolutely_continuous.ennreal_to_measure at h,
simp [h (measure_mono_null (i.inter_subset_right S) hS₂),
h (measure_mono_null (iᶜ.inter_subset_right S) hS₂)] },
{ refine vector_measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
rw ← vector_measure.ennreal_to_measure_apply hS₁ at hS₂,
exact null_of_total_variation_zero s (h hS₂) }
end
lemma total_variation_absolutely_continuous_iff (s : signed_measure α) (μ : measure α) :
s.total_variation ≪ μ ↔
s.to_jordan_decomposition.pos_part ≪ μ ∧ s.to_jordan_decomposition.neg_part ≪ μ :=
begin
split; intro h,
{ split, all_goals
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
have := h hS₂,
rw [total_variation, measure.add_apply, add_eq_zero_iff] at this },
exacts [this.1, this.2] },
{ refine measure.absolutely_continuous.mk (λ S hS₁ hS₂, _),
rw [total_variation, measure.add_apply, h.1 hS₂, h.2 hS₂, add_zero] }
end
-- TODO: Generalize to vector measures once total variation on vector measures is defined
lemma mutually_singular_iff (s t : signed_measure α) :
s ⟂ᵥ t ↔ s.total_variation ⟂ₘ t.total_variation :=
begin
split,
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
obtain ⟨i, hi₁, hi₂, hi₃, hipos, hineg⟩ := s.to_jordan_decomposition_spec,
obtain ⟨j, hj₁, hj₂, hj₃, hjpos, hjneg⟩ := t.to_jordan_decomposition_spec,
refine ⟨u, hmeas, _, _⟩,
{ rw [total_variation, measure.add_apply, hipos, hineg,
to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas],
simp [hu₁ _ (set.inter_subset_right _ _)] },
{ rw [total_variation, measure.add_apply, hjpos, hjneg,
to_measure_of_zero_le_apply _ _ _ hmeas.compl,
to_measure_of_le_zero_apply _ _ _ hmeas.compl],
simp [hu₂ _ (set.inter_subset_right _ _)] } },
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
exact ⟨u, hmeas,
(λ t htu, null_of_total_variation_zero _ (measure_mono_null htu hu₁)),
(λ t htv, null_of_total_variation_zero _ (measure_mono_null htv hu₂))⟩ }
end
lemma mutually_singular_ennreal_iff (s : signed_measure α) (μ : vector_measure α ℝ≥0∞) :
s ⟂ᵥ μ ↔ s.total_variation ⟂ₘ μ.ennreal_to_measure :=
begin
split,
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
obtain ⟨i, hi₁, hi₂, hi₃, hpos, hneg⟩ := s.to_jordan_decomposition_spec,
refine ⟨u, hmeas, _, _⟩,
{ rw [total_variation, measure.add_apply, hpos, hneg,
to_measure_of_zero_le_apply _ _ _ hmeas, to_measure_of_le_zero_apply _ _ _ hmeas],
simp [hu₁ _ (set.inter_subset_right _ _)] },
{ rw vector_measure.ennreal_to_measure_apply hmeas.compl,
exact hu₂ _ (set.subset.refl _) } },
{ rintro ⟨u, hmeas, hu₁, hu₂⟩,
refine vector_measure.mutually_singular.mk u hmeas
(λ t htu _, null_of_total_variation_zero _ (measure_mono_null htu hu₁)) (λ t htv hmt, _),
rw ← vector_measure.ennreal_to_measure_apply hmt,
exact measure_mono_null htv hu₂ }
end
lemma total_variation_mutually_singular_iff (s : signed_measure α) (μ : measure α) :
s.total_variation ⟂ₘ μ ↔
s.to_jordan_decomposition.pos_part ⟂ₘ μ ∧ s.to_jordan_decomposition.neg_part ⟂ₘ μ :=
measure.mutually_singular.add_left_iff
end signed_measure
end measure_theory
|
a3f1074ae77f65a12936e443899a8a33f807edfd | b3fced0f3ff82d577384fe81653e47df68bb2fa1 | /src/linear_algebra/basic.lean | c896690e408fc48ea62f75a274386007d2a050d8 | [
"Apache-2.0"
] | permissive | ratmice/mathlib | 93b251ef5df08b6fd55074650ff47fdcc41a4c75 | 3a948a6a4cd5968d60e15ed914b1ad2f4423af8d | refs/heads/master | 1,599,240,104,318 | 1,572,981,183,000 | 1,572,981,183,000 | 219,830,178 | 0 | 0 | Apache-2.0 | 1,572,980,897,000 | 1,572,980,896,000 | null | UTF-8 | Lean | false | false | 70,360 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Kevin Buzzard
-/
import algebra.pi_instances data.finsupp data.equiv.algebra order.order_iso
/-!
# Linear algebra
This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of
modules over a ring, submodules, and linear maps. If `p` and `q` are submodules of a module, `p ≤ q`
means that `p ⊆ q`.
Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in
`src/algebra/module.lean`.
## Main definitions
* Many constructors for linear maps, including `pair` and `copair`
* `submodule.span s` is defined to be the smallest submodule containing the set `s`.
* If `p` is a submodule of `M`, `submodule.quotient p` is the quotient of `M` with respect to `p`:
that is, elements of `M` are identified if their difference is in `p`. This is itself a module.
* The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain
respectively.
* `lin_equiv M M₂`, the type of linear equivalences between `M` and `M₂`, is a structure that extends
`linear_map` and `equiv`.
* The general linear group is defined to be the group of invertible linear maps from `M` to itself.
## Main statements
* The first and second isomorphism laws for modules are proved as `quot_ker_equiv_range` and
`sup_quotient_equiv_quotient_inf`.
## Notations
* We continue to use the notation `M →ₗ[R] M₂` for the type of linear maps from `M` to `M₂` over the
ring `R`.
* We introduce the notations `M ≃ₗ M₂` and `M ≃ₗ[R] M₂` for `lin_equiv M M₂`. In the first, the ring
`R` is implicit.
## Implementation notes
We note that, when constructing linear maps, it is convenient to use operations defined on bundled
maps (`pair`, `copair`, arithmetic operations like `+`) instead of defining a function and proving
it is linear.
## Tags
linear algebra, vector space, module
-/
open function lattice
reserve infix ` ≃ₗ `:25
universes u v w x y z u' v' w' y'
variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'}
variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x}
namespace finset
lemma smul_sum {α : Type u} {M : Type v} {R : Type w}
[ring R] [add_comm_group M] [module R M]
{s : finset α} {a : R} {f : α → M} :
a • (s.sum f) = s.sum (λc, a • f c) :=
(finset.sum_hom ((•) a)).symm
end finset
namespace finsupp
lemma smul_sum {α : Type u} {β : Type v} {R : Type w} {M : Type y}
[has_zero β] [ring R] [add_comm_group M] [module R M]
{v : α →₀ β} {c : R} {h : α → β → M} :
c • (v.sum h) = v.sum (λa b, c • h a b) :=
finset.smul_sum
end finsupp
namespace linear_map
section
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄]
variables [module R M] [module R M₂] [module R M₃] [module R M₄]
variables (f g : M →ₗ[R] M₂)
include R
@[simp] theorem comp_id : f.comp id = f :=
linear_map.ext $ λ x, rfl
@[simp] theorem id_comp : id.comp f = f :=
linear_map.ext $ λ x, rfl
theorem comp_assoc (g : M₂ →ₗ[R] M₃) (h : M₃ →ₗ[R] M₄) : (h.comp g).comp f = h.comp (g.comp f) :=
rfl
/-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a
linear map M₂ → p. -/
def cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h : ∀c, f c ∈ p) : M₂ →ₗ[R] p :=
by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp
@[simp] theorem cod_restrict_apply (p : submodule R M) (f : M₂ →ₗ[R] M) {h} (x : M₂) :
(cod_restrict p f h x : M) = f x := rfl
@[simp] lemma comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) (g : M₃ →ₗ[R] M) :
(cod_restrict p f h).comp g = cod_restrict p (f.comp g) (assume b, h _) :=
ext $ assume b, rfl
@[simp] lemma subtype_comp_cod_restrict (p : submodule R M₂) (h : ∀b, f b ∈ p) :
p.subtype.comp (cod_restrict p f h) = f :=
ext $ assume b, rfl
/-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/
def inverse (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₗ[R] M :=
by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact
⟨g, λ x y, by rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂],
λ a b, by rw [← h₁ (g (a • b)), ← h₁ (a • g b)]; simp [h₂]⟩
/-- The constant 0 map is linear. -/
instance : has_zero (M →ₗ[R] M₂) := ⟨⟨λ _, 0, by simp, by simp⟩⟩
@[simp] lemma zero_apply (x : M) : (0 : M →ₗ[R] M₂) x = 0 := rfl
/-- The negation of a linear map is linear. -/
instance : has_neg (M →ₗ[R] M₂) := ⟨λ f, ⟨λ b, - f b, by simp, by simp⟩⟩
@[simp] lemma neg_apply (x : M) : (- f) x = - f x := rfl
/-- The sum of two linear maps is linear. -/
instance : has_add (M →ₗ[R] M₂) := ⟨λ f g, ⟨λ b, f b + g b, by simp, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (x : M) : (f + g) x = f x + g x := rfl
/-- The type of linear maps is an additive group. -/
instance : add_comm_group (M →ₗ[R] M₂) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
intros; ext; simp
instance linear_map.is_add_group_hom : is_add_group_hom f :=
{ map_add := f.add }
instance linear_map_apply_is_add_group_hom (a : M) :
is_add_group_hom (λ f : M →ₗ[R] M₂, f a) :=
{ map_add := λ f g, linear_map.add_apply f g a }
lemma sum_apply (t : finset ι) (f : ι → M →ₗ[R] M₂) (b : M) :
t.sum f b = t.sum (λd, f d b) :=
(@finset.sum_hom _ _ _ t f _ _ (λ g : M →ₗ[R] M₂, g b) _).symm
@[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl
/-- `λb, f b • x` is a linear map. -/
def smul_right (f : M₂ →ₗ[R] R) (x : M) : M₂ →ₗ[R] M :=
⟨λb, f b • x, by simp [add_smul], by simp [smul_smul]⟩.
@[simp] theorem smul_right_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) :
(smul_right f x : M₂ → M) c = f c • x := rfl
instance : has_one (M →ₗ[R] M) := ⟨linear_map.id⟩
instance : has_mul (M →ₗ[R] M) := ⟨linear_map.comp⟩
@[simp] lemma one_app (x : M) : (1 : M →ₗ[R] M) x = x := rfl
@[simp] lemma mul_app (A B : M →ₗ[R] M) (x : M) : (A * B) x = A (B x) := rfl
@[simp] theorem comp_zero : f.comp (0 : M₃ →ₗ[R] M) = 0 :=
ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, f.map_zero]
@[simp] theorem zero_comp : (0 : M₂ →ₗ[R] M₃).comp f = 0 :=
rfl
section
variables (R M)
include M
instance endomorphism_ring : ring (M →ₗ[R] M) :=
by refine {mul := (*), one := 1, ..linear_map.add_comm_group, ..};
{ intros, apply linear_map.ext, simp }
end
section
variables (R M M₂)
/-- The first projection of a product is a linear map. -/
def fst : M × M₂ →ₗ[R] M := ⟨prod.fst, λ x y, rfl, λ x y, rfl⟩
/-- The second projection of a product is a linear map. -/
def snd : M × M₂ →ₗ[R] M₂ := ⟨prod.snd, λ x y, rfl, λ x y, rfl⟩
end
@[simp] theorem fst_apply (x : M × M₂) : fst R M M₂ x = x.1 := rfl
@[simp] theorem snd_apply (x : M × M₂) : snd R M M₂ x = x.2 := rfl
/-- The pair of two linear maps is a linear map. -/
def pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) : M →ₗ[R] M₂ × M₃ :=
⟨λ x, (f x, g x), λ x y, by simp, λ x y, by simp⟩
@[simp] theorem pair_apply (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (x : M) :
pair f g x = (f x, g x) := rfl
@[simp] theorem fst_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
(fst R M₂ M₃).comp (pair f g) = f := by ext; refl
@[simp] theorem snd_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
(snd R M₂ M₃).comp (pair f g) = g := by ext; refl
@[simp] theorem pair_fst_snd : pair (fst R M M₂) (snd R M M₂) = linear_map.id :=
by ext; refl
section
variables (R M M₂)
/-- The left injection into a product is a linear map. -/
def inl : M →ₗ[R] M × M₂ := by refine ⟨prod.inl, _, _⟩; intros; simp [prod.inl]
/-- The right injection into a product is a linear map. -/
def inr : M₂ →ₗ[R] M × M₂ := by refine ⟨prod.inr, _, _⟩; intros; simp [prod.inr]
end
@[simp] theorem inl_apply (x : M) : inl R M M₂ x = (x, 0) := rfl
@[simp] theorem inr_apply (x : M₂) : inr R M M₂ x = (0, x) := rfl
/-- The copair function `λ x : M × M₂, f x.1 + g x.2` is a linear map. -/
def copair (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) : M × M₂ →ₗ[R] M₃ :=
⟨λ x, f x.1 + g x.2, λ x y, by simp, λ x y, by simp [smul_add]⟩
@[simp] theorem copair_apply (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (x : M) (y : M₂) :
copair f g (x, y) = f x + g y := rfl
@[simp] theorem copair_inl (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) :
(copair f g).comp (inl R M M₂) = f := by ext; simp
@[simp] theorem copair_inr (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) :
(copair f g).comp (inr R M M₂) = g := by ext; simp
@[simp] theorem copair_inl_inr : copair (inl R M M₂) (inr R M M₂) = linear_map.id :=
by ext ⟨x, y⟩; simp
theorem fst_eq_copair : fst R M M₂ = copair linear_map.id 0 := by ext ⟨x, y⟩; simp
theorem snd_eq_copair : snd R M M₂ = copair 0 linear_map.id := by ext ⟨x, y⟩; simp
theorem inl_eq_pair : inl R M M₂ = pair linear_map.id 0 := rfl
theorem inr_eq_pair : inr R M M₂ = pair 0 linear_map.id := rfl
end
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f g : M →ₗ[R] M₂)
include R
instance : has_scalar R (M →ₗ[R] M₂) := ⟨λ a f,
⟨λ b, a • f b, by simp [smul_add], by simp [smul_smul, mul_comm]⟩⟩
@[simp] lemma smul_apply (a : R) (x : M) : (a • f) x = a • f x := rfl
instance : module R (M →ₗ[R] M₂) :=
module.of_core $ by refine { smul := (•), ..};
intros; ext; simp [smul_add, add_smul, smul_smul]
/-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of
linear maps `M₂ → M₃`. -/
def congr_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) :=
⟨linear_map.comp f,
λ _ _, linear_map.ext $ λ _, f.2 _ _,
λ _ _, linear_map.ext $ λ _, f.3 _ _⟩
theorem smul_comp (g : M₂ →ₗ[R] M₃) (a : R) : (a • g).comp f = a • (g.comp f) :=
rfl
theorem comp_smul (g : M₂ →ₗ[R] M₃) (a : R) : g.comp (a • f) = a • (g.comp f) :=
ext $ assume b, by rw [comp_apply, smul_apply, g.map_smul]; refl
end comm_ring
end linear_map
namespace submodule
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (p p' : submodule R M) (q q' : submodule R M₂)
variables {r : R} {x y : M}
open set lattice
instance : partial_order (submodule R M) :=
partial_order.lift (coe : submodule R M → set M) (λ a b, ext') (by apply_instance)
lemma le_def {p p' : submodule R M} : p ≤ p' ↔ (p : set M) ⊆ p' := iff.rfl
lemma le_def' {p p' : submodule R M} : p ≤ p' ↔ ∀ x ∈ p, x ∈ p' := iff.rfl
/-- If two submodules p and p' satisfy p ⊆ p', then `of_le p p'` is the linear map version of this
inclusion. -/
def of_le {p p' : submodule R M} (h : p ≤ p') : p →ₗ[R] p' :=
linear_map.cod_restrict _ p.subtype $ λ ⟨x, hx⟩, h hx
@[simp] theorem of_le_apply {p p' : submodule R M} (h : p ≤ p')
(x : p) : (of_le h x : M) = x := rfl
lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) :
(submodule.subtype q).comp (of_le h) = submodule.subtype p :=
by ext ⟨b, hb⟩; simp
/-- The set `{0}` is the bottom element of the lattice of submodules. -/
instance : has_bot (submodule R M) :=
⟨by split; try {exact {0}}; simp {contextual := tt}⟩
@[simp] lemma bot_coe : ((⊥ : submodule R M) : set M) = {0} := rfl
section
variables (R)
@[simp] lemma mem_bot : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_singleton_iff
end
instance : order_bot (submodule R M) :=
{ bot := ⊥,
bot_le := λ p x, by simp {contextual := tt},
..submodule.partial_order }
/-- The universal set is the top element of the lattice of submodules. -/
instance : has_top (submodule R M) :=
⟨by split; try {exact set.univ}; simp⟩
@[simp] lemma top_coe : ((⊤ : submodule R M) : set M) = univ := rfl
@[simp] lemma mem_top : x ∈ (⊤ : submodule R M) := trivial
lemma eq_bot_of_zero_eq_one (zero_eq_one : (0 : R) = 1) : p = ⊥ :=
by ext x; simp [semimodule.eq_zero_of_zero_eq_one _ x zero_eq_one]
instance : order_top (submodule R M) :=
{ top := ⊤,
le_top := λ p x _, trivial,
..submodule.partial_order }
instance : has_Inf (submodule R M) :=
⟨λ S, {
carrier := ⋂ s ∈ S, ↑s,
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
private lemma Inf_le' {S : set (submodule R M)} {p} : p ∈ S → Inf S ≤ p :=
bInter_subset_of_mem
private lemma le_Inf' {S : set (submodule R M)} {p} : (∀p' ∈ S, p ≤ p') → p ≤ Inf S :=
subset_bInter
instance : has_inf (submodule R M) :=
⟨λ p p', {
carrier := p ∩ p',
zero := by simp,
add := by simp [add_mem] {contextual := tt},
smul := by simp [smul_mem] {contextual := tt} }⟩
instance : complete_lattice (submodule R M) :=
{ sup := λ a b, Inf {x | a ≤ x ∧ b ≤ x},
le_sup_left := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, ha,
le_sup_right := λ a b, le_Inf' $ λ x ⟨ha, hb⟩, hb,
sup_le := λ a b c h₁ h₂, Inf_le' ⟨h₁, h₂⟩,
inf := (⊓),
le_inf := λ a b c, subset_inter,
inf_le_left := λ a b, inter_subset_left _ _,
inf_le_right := λ a b, inter_subset_right _ _,
Sup := λtt, Inf {t | ∀t'∈tt, t' ≤ t},
le_Sup := λ s p hs, le_Inf' $ λ p' hp', hp' _ hs,
Sup_le := λ s p hs, Inf_le' hs,
Inf := Inf,
le_Inf := λ s a, le_Inf',
Inf_le := λ s a, Inf_le',
..submodule.lattice.order_top,
..submodule.lattice.order_bot }
instance : add_comm_monoid (submodule R M) :=
{ add := (⊔),
add_assoc := λ _ _ _, sup_assoc,
zero := ⊥,
zero_add := λ _, bot_sup_eq,
add_zero := λ _, sup_bot_eq,
add_comm := λ _ _, sup_comm }
@[simp] lemma add_eq_sup (p q : submodule R M) : p + q = p ⊔ q := rfl
@[simp] lemma zero_eq_bot : (0 : submodule R M) = ⊥ := rfl
lemma eq_top_iff' {p : submodule R M} : p = ⊤ ↔ ∀ x, x ∈ p :=
eq_top_iff.trans ⟨λ h x, @h x trivial, λ h x _, h x⟩
@[simp] theorem inf_coe : (p ⊓ p' : set M) = p ∩ p' := rfl
@[simp] theorem mem_inf {p p' : submodule R M} :
x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl
@[simp] theorem Inf_coe (P : set (submodule R M)) : (↑(Inf P) : set M) = ⋂ p ∈ P, ↑p := rfl
@[simp] theorem infi_coe {ι} (p : ι → submodule R M) :
(↑⨅ i, p i : set M) = ⋂ i, ↑(p i) :=
by rw [infi, Inf_coe]; ext a; simp; exact
⟨λ h i, h _ i rfl, λ h i x e, e ▸ h _⟩
@[simp] theorem mem_infi {ι} (p : ι → submodule R M) :
x ∈ (⨅ i, p i) ↔ ∀ i, x ∈ p i :=
by rw [← mem_coe, infi_coe, mem_Inter]; refl
theorem disjoint_def {p p' : submodule R M} :
disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) :=
show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp
/-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/
def map (f : M →ₗ[R] M₂) (p : submodule R M) : submodule R M₂ :=
{ carrier := f '' p,
zero := ⟨0, p.zero_mem, f.map_zero⟩,
add := by rintro _ _ ⟨b₁, hb₁, rfl⟩ ⟨b₂, hb₂, rfl⟩;
exact ⟨_, p.add_mem hb₁ hb₂, f.map_add _ _⟩,
smul := by rintro a _ ⟨b, hb, rfl⟩;
exact ⟨_, p.smul_mem _ hb, f.map_smul _ _⟩ }
lemma map_coe (f : M →ₗ[R] M₂) (p : submodule R M) :
(map f p : set M₂) = f '' p := rfl
@[simp] lemma mem_map {f : M →ₗ[R] M₂} {p : submodule R M} {x : M₂} :
x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl
theorem mem_map_of_mem {f : M →ₗ[R] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p :=
set.mem_image_of_mem _ h
lemma map_id : map linear_map.id p = p :=
submodule.ext $ λ a, by simp
lemma map_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M) :
map (g.comp f) p = map g (map f p) :=
submodule.ext' $ by simp [map_coe]; rw ← image_comp
lemma map_mono {f : M →ₗ[R] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' :=
image_subset _
@[simp] lemma map_zero : map (0 : M →ₗ[R] M₂) p = ⊥ :=
have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩,
ext $ by simp [this, eq_comm]
/-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/
def comap (f : M →ₗ[R] M₂) (p : submodule R M₂) : submodule R M :=
{ carrier := f ⁻¹' p,
zero := by simp,
add := λ x y h₁ h₂, by simp [p.add_mem h₁ h₂],
smul := λ a x h, by simp [p.smul_mem _ h] }
@[simp] lemma comap_coe (f : M →ₗ[R] M₂) (p : submodule R M₂) :
(comap f p : set M) = f ⁻¹' p := rfl
@[simp] lemma mem_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} :
x ∈ comap f p ↔ f x ∈ p := iff.rfl
lemma comap_id : comap linear_map.id p = p :=
submodule.ext' rfl
lemma comap_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) (p : submodule R M₃) :
comap (g.comp f) p = comap f (comap g p) := rfl
lemma comap_mono {f : M →ₗ[R] M₂} {q q' : submodule R M₂} : q ≤ q' → comap f q ≤ comap f q' :=
preimage_mono
lemma map_le_iff_le_comap {f : M →ₗ[R] M₂} {p : submodule R M} {q : submodule R M₂} :
map f p ≤ q ↔ p ≤ comap f q := image_subset_iff
lemma gc_map_comap (f : M →ₗ[R] M₂) : galois_connection (map f) (comap f)
| p q := map_le_iff_le_comap
@[simp] lemma map_bot (f : M →ₗ[R] M₂) : map f ⊥ = ⊥ :=
(gc_map_comap f).l_bot
@[simp] lemma map_sup (f : M →ₗ[R] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' :=
(gc_map_comap f).l_sup
@[simp] lemma map_supr {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M) :
map f (⨆i, p i) = (⨆i, map f (p i)) :=
(gc_map_comap f).l_supr
@[simp] lemma comap_top (f : M →ₗ[R] M₂) : comap f ⊤ = ⊤ := rfl
@[simp] lemma comap_inf (f : M →ₗ[R] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl
@[simp] lemma comap_infi {ι : Sort*} (f : M →ₗ[R] M₂) (p : ι → submodule R M₂) :
comap f (⨅i, p i) = (⨅i, comap f (p i)) :=
(gc_map_comap f).u_infi
@[simp] lemma comap_zero : comap (0 : M →ₗ[R] M₂) q = ⊤ :=
ext $ by simp
lemma map_comap_le (f : M →ₗ[R] M₂) (q : submodule R M₂) : map f (comap f q) ≤ q :=
(gc_map_comap f).l_u_le _
lemma le_comap_map (f : M →ₗ[R] M₂) (p : submodule R M) : p ≤ comap f (map f p) :=
(gc_map_comap f).le_u_l _
--TODO(Mario): is there a way to prove this from order properties?
lemma map_inf_eq_map_inf_comap {f : M →ₗ[R] M₂}
{p : submodule R M} {p' : submodule R M₂} :
map f p ⊓ p' = map f (p ⊓ comap f p') :=
le_antisymm
(by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩)
(le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right))
lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' :=
ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩
lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0
| ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb
section
variables (R)
/-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/
def span (s : set M) : submodule R M := Inf {p | s ⊆ p}
end
variables {s t : set M}
lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p :=
mem_bInter_iff
lemma subset_span : s ⊆ span R s :=
λ x h, mem_span.2 $ λ p hp, hp h
lemma span_le {p} : span R s ≤ p ↔ s ⊆ p :=
⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩
lemma span_mono (h : s ⊆ t) : span R s ≤ span R t :=
span_le.2 $ subset.trans h subset_span
lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p :=
le_antisymm (span_le.2 h₁) h₂
@[simp] lemma span_eq : span R (p : set M) = p :=
span_eq_of_le _ (subset.refl _) subset_span
/-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is
preserved under addition and scalar multiplication, then `p` holds for all elements of the span of
`s`. -/
@[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s)
(Hs : ∀ x ∈ s, p x) (H0 : p 0)
(H1 : ∀ x y, p x → p y → p (x + y))
(H2 : ∀ (a:R) x, p x → p (a • x)) : p x :=
(@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h
section
variables (R M)
/-- `span` forms a Galois insertion with the coercion from submodule to set. -/
protected def gi : galois_insertion (@span R M _ _ _) coe :=
{ choice := λ s _, span R s,
gc := λ s t, span_le,
le_l_u := λ s, subset_span,
choice_eq := λ s h, rfl }
end
@[simp] lemma span_empty : span R (∅ : set M) = ⊥ :=
(submodule.gi R M).gc.l_bot
@[simp] lemma span_univ : span R (univ : set M) = ⊤ :=
eq_top_iff.2 $ le_def.2 $ subset_span
lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t :=
(submodule.gi R M).gc.l_sup
lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) :=
(submodule.gi R M).gc.l_supr
@[simp] theorem Union_coe_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule R M)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) :
((supr S : submodule R M) : set M) = ⋃ i, S i :=
begin
refine subset.antisymm _ (Union_subset $ le_supr S),
rw [show supr S = ⨆ i, span R (S i), by simp, ← span_Union],
unfreezeI,
refine λ x hx, span_induction hx (λ _, id) _ _ _,
{ cases hι with i, exact mem_Union.2 ⟨i, by simp⟩ },
{ simp, intros x y i hi j hj,
rcases H i j with ⟨k, ik, jk⟩,
exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ },
{ simp [-mem_coe]; exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ },
end
lemma mem_supr_of_mem {ι : Sort*} {b : M} (p : ι → submodule R M) (i : ι) (h : b ∈ p i) :
b ∈ (⨆i, p i) :=
have p i ≤ (⨆i, p i) := le_supr p i,
@this b h
@[simp] theorem mem_supr_of_directed {ι} (hι : nonempty ι)
(S : ι → submodule R M)
(H : ∀ i j, ∃ k, S i ≤ S k ∧ S j ≤ S k) {x} :
x ∈ supr S ↔ ∃ i, x ∈ S i :=
by rw [← mem_coe, Union_coe_of_directed hι S H, mem_Union]; refl
theorem mem_Sup_of_directed {s : set (submodule R M)}
{z} (hzs : z ∈ Sup s) (x ∈ s)
(hdir : ∀ i ∈ s, ∀ j ∈ s, ∃ k ∈ s, i ≤ k ∧ j ≤ k) :
∃ y ∈ s, z ∈ y :=
begin
haveI := classical.dec, rw Sup_eq_supr at hzs,
have : ∃ (i : submodule R M), z ∈ ⨆ (H : i ∈ s), i,
{ refine (mem_supr_of_directed ⟨⊥⟩ _ (λ i j, _)).1 hzs,
by_cases his : i ∈ s; by_cases hjs : j ∈ s,
{ rcases hdir i his j hjs with ⟨k, hks, hik, hjk⟩,
exact ⟨k, le_supr_of_le hks (supr_le $ λ _, hik),
le_supr_of_le hks (supr_le $ λ _, hjk)⟩ },
{ exact ⟨i, le_refl _, supr_le $ hjs.elim⟩ },
{ exact ⟨j, supr_le $ his.elim, le_refl _⟩ },
{ exact ⟨⊥, supr_le $ his.elim, supr_le $ hjs.elim⟩ } },
cases this with N hzn, by_cases hns : N ∈ s,
{ have : (⨆ (H : N ∈ s), N) ≤ N := supr_le (λ _, le_refl _),
exact ⟨N, hns, this hzn⟩ },
{ have : (⨆ (H : N ∈ s), N) ≤ ⊥ := supr_le hns.elim,
cases (mem_bot R).1 (this hzn), exact ⟨x, H, x.zero_mem⟩ }
end
section
variables {p p'}
lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x :=
⟨λ h, begin
rw [← span_eq p, ← span_eq p', ← span_union] at h,
apply span_induction h,
{ rintro y (h | h),
{ exact ⟨y, h, 0, by simp, by simp⟩ },
{ exact ⟨0, by simp, y, h, by simp⟩ } },
{ exact ⟨0, by simp, 0, by simp⟩ },
{ rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩,
exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp⟩ },
{ rintro a _ ⟨y, hy, z, hz, rfl⟩,
exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ }
end,
by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _
((le_sup_left : p ≤ p ⊔ p') hy)
((le_sup_right : p' ≤ p ⊔ p') hz)⟩
end
lemma mem_span_singleton {y : M} : x ∈ span R ({y} : set M) ↔ ∃ a:R, a • y = x :=
⟨λ h, begin
apply span_induction h,
{ rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ },
{ exact ⟨0, by simp⟩ },
{ rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩,
exact ⟨a + b, by simp [add_smul]⟩ },
{ rintro a _ ⟨b, rfl⟩,
exact ⟨a * b, by simp [smul_smul]⟩ }
end,
by rintro ⟨a, y, rfl⟩; exact
smul_mem _ _ (subset_span $ by simp)⟩
lemma span_singleton_eq_range (y : M) : (span R ({y} : set M) : set M) = range ((• y) : R → M) :=
set.ext $ λ x, mem_span_singleton
lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z :=
begin
rw [← union_singleton, span_union, mem_sup],
simp [mem_span_singleton], split,
{ rintro ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩, exact ⟨a, z, hz, rfl⟩ },
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨z, hz, _, ⟨a, rfl⟩, rfl⟩ }
end
lemma mem_span_insert' {y} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s :=
begin
rw mem_span_insert, split,
{ rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz]⟩ },
{ rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp⟩ }
end
lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s :=
span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _)
lemma span_span : span R (span R s : set M) = span R s := span_eq _
lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 :=
eq_bot_iff.trans ⟨
λ H x h, (mem_bot R).1 $ H $ subset_span h,
λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩
lemma span_singleton_eq_bot : span R ({x} : set M) = ⊥ ↔ x = 0 :=
span_eq_bot.trans $ by simp
@[simp] lemma span_image (f : M →ₗ[R] M₂) : span R (f '' s) = map f (span R s) :=
span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $
span_le.2 $ image_subset_iff.1 subset_span
lemma linear_eq_on (s : set M) {f g : M →ₗ[R] M₂} (H : ∀x∈s, f x = g x) {x} (h : x ∈ span R s) :
f x = g x :=
by apply span_induction h H; simp {contextual := tt}
/-- The product of two submodules is a submodule. -/
def prod : submodule R (M × M₂) :=
{ carrier := set.prod p q,
zero := ⟨zero_mem _, zero_mem _⟩,
add := by rintro ⟨x₁, y₁⟩ ⟨x₂, y₂⟩ ⟨hx₁, hy₁⟩ ⟨hx₂, hy₂⟩;
exact ⟨add_mem _ hx₁ hx₂, add_mem _ hy₁ hy₂⟩,
smul := by rintro a ⟨x, y⟩ ⟨hx, hy⟩;
exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩ }
@[simp] lemma prod_coe :
(prod p q : set (M × M₂)) = set.prod p q := rfl
@[simp] lemma mem_prod {p : submodule R M} {q : submodule R M₂} {x : M × M₂} :
x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod
lemma span_prod_le (s : set M) (t : set M₂) :
span R (set.prod s t) ≤ prod (span R s) (span R t) :=
span_le.2 $ set.prod_mono subset_span subset_span
@[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M₂)) = ⊤ :=
by ext; simp
@[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M₂)) = ⊥ :=
by ext ⟨x, y⟩; simp [prod.zero_eq_mk]
lemma prod_mono {p p' : submodule R M} {q q' : submodule R M₂} :
p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono
@[simp] lemma prod_inf_prod : prod p q ⊓ prod p' q' = prod (p ⊓ p') (q ⊓ q') :=
ext' set.prod_inter_prod
@[simp] lemma prod_sup_prod : prod p q ⊔ prod p' q' = prod (p ⊔ p') (q ⊔ q') :=
begin
refine le_antisymm (sup_le
(prod_mono le_sup_left le_sup_left)
(prod_mono le_sup_right le_sup_right)) _,
simp [le_def'], intros xx yy hxx hyy,
rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩,
rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩,
refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩
end
-- TODO(Mario): Factor through add_subgroup
/-- The equivalence relation associated to a submodule `p`, defined by `x ≈ y` iff `y - x ∈ p`. -/
def quotient_rel : setoid M :=
⟨λ x y, x - y ∈ p, λ x, by simp,
λ x y h, by simpa using neg_mem _ h,
λ x y z h₁ h₂, by simpa using add_mem _ h₁ h₂⟩
/-- The quotient of a module `M` by a submodule `p ⊆ M`. -/
def quotient : Type* := quotient (quotient_rel p)
namespace quotient
/-- Map associating to an element of `M` the corresponding element of `M/p`,
when `p` is a submodule of `M`. -/
def mk {p : submodule R M} : M → quotient p := quotient.mk'
@[simp] theorem mk_eq_mk {p : submodule R M} (x : M) : (quotient.mk x : quotient p) = mk x := rfl
@[simp] theorem mk'_eq_mk {p : submodule R M} (x : M) : (quotient.mk' x : quotient p) = mk x := rfl
@[simp] theorem quot_mk_eq_mk {p : submodule R M} (x : M) : (quot.mk _ x : quotient p) = mk x := rfl
protected theorem eq {x y : M} : (mk x : quotient p) = mk y ↔ x - y ∈ p := quotient.eq'
instance : has_zero (quotient p) := ⟨mk 0⟩
@[simp] theorem mk_zero : mk 0 = (0 : quotient p) := rfl
@[simp] theorem mk_eq_zero : (mk x : quotient p) = 0 ↔ x ∈ p :=
by simpa using (quotient.eq p : mk x = 0 ↔ _)
instance : has_add (quotient p) :=
⟨λ a b, quotient.lift_on₂' a b (λ a b, mk (a + b)) $
λ a₁ a₂ b₁ b₂ h₁ h₂, (quotient.eq p).2 $ by simpa using add_mem p h₁ h₂⟩
@[simp] theorem mk_add : (mk (x + y) : quotient p) = mk x + mk y := rfl
instance : has_neg (quotient p) :=
⟨λ a, quotient.lift_on' a (λ a, mk (-a)) $
λ a b h, (quotient.eq p).2 $ by simpa using neg_mem p h⟩
@[simp] theorem mk_neg : (mk (-x) : quotient p) = -mk x := rfl
instance : add_comm_group (quotient p) :=
by refine {zero := 0, add := (+), neg := has_neg.neg, ..};
repeat {rintro ⟨⟩};
simp [-mk_zero, (mk_zero p).symm, -mk_add, (mk_add p).symm, -mk_neg, (mk_neg p).symm]
instance : has_scalar R (quotient p) :=
⟨λ a x, quotient.lift_on' x (λ x, mk (a • x)) $
λ x y h, (quotient.eq p).2 $ by simpa [smul_add] using smul_mem p a h⟩
@[simp] theorem mk_smul : (mk (r • x) : quotient p) = r • mk x := rfl
instance : module R (quotient p) :=
module.of_core $ by refine {smul := (•), ..};
repeat {rintro ⟨⟩ <|> intro}; simp [smul_add, add_smul, smul_smul,
-mk_add, (mk_add p).symm, -mk_smul, (mk_smul p).symm]
instance {K M} {R:discrete_field K} [add_comm_group M] [vector_space K M]
(p : submodule K M) : vector_space K (quotient p) := {}
end quotient
end submodule
namespace submodule
variables [discrete_field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group V₂] [vector_space K V₂]
lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) :
p.comap (a • f) = p.comap f :=
by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply]
lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) :
p.map (a • f) = p.map f :=
le_antisymm
begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end
set_option class.instance_max_depth 40
lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) :
p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) :=
by by_cases a = 0; simp [h, comap_smul]
lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) :
p.map (a • f) = (⨆ h : a ≠ 0, p.map f) :=
by by_cases a = 0; simp [h, map_smul]
end submodule
namespace linear_map
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open submodule
@[simp] lemma finsupp_sum {R M M₂ γ} [ring R] [add_comm_group M] [module R M]
[add_comm_group M₂] [module R M₂] [has_zero γ]
(f : M →ₗ[R] M₂) {t : ι →₀ γ} {g : ι → γ → M} :
f (t.sum g) = t.sum (λi d, f (g i d)) := f.map_sum
theorem map_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (h p') :
submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) :=
submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.coe_ext]
theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf p') :
submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') :=
submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩
/-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. -/
def range (f : M →ₗ[R] M₂) : submodule R M₂ := map f ⊤
theorem range_coe (f : M →ₗ[R] M₂) : (range f : set M₂) = set.range f := set.image_univ
@[simp] theorem mem_range {f : M →ₗ[R] M₂} : ∀ {x}, x ∈ range f ↔ ∃ y, f y = x :=
(set.ext_iff _ _).1 (range_coe f).
@[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := map_id _
theorem range_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) = map g (range f) :=
map_comp _ _ _
theorem range_comp_le_range (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : range (g.comp f) ≤ range g :=
by rw range_comp; exact map_mono le_top
theorem range_eq_top {f : M →ₗ[R] M₂} : range f = ⊤ ↔ surjective f :=
by rw [← submodule.ext'_iff, range_coe, top_coe, set.range_iff_surjective]
lemma range_le_iff_comap {f : M →ₗ[R] M₂} {p : submodule R M₂} : range f ≤ p ↔ comap f p = ⊤ :=
by rw [range, map_le_iff_le_comap, eq_top_iff]
lemma map_le_range {f : M →ₗ[R] M₂} {p : submodule R M} : map f p ≤ range f :=
map_mono le_top
lemma sup_range_inl_inr :
(inl R M M₂).range ⊔ (inr R M M₂).range = ⊤ :=
begin
refine eq_top_iff'.2 (λ x, mem_sup.2 _),
rcases x with ⟨x₁, x₂⟩ ,
have h₁ : prod.mk x₁ (0 : M₂) ∈ (inl R M M₂).range,
by simp,
have h₂ : prod.mk (0 : M) x₂ ∈ (inr R M M₂).range,
by simp,
use [⟨x₁, 0⟩, h₁, ⟨0, x₂⟩, h₂],
simp
end
/-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the
set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/
def ker (f : M →ₗ[R] M₂) : submodule R M := comap f ⊥
@[simp] theorem mem_ker {f : M →ₗ[R] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R
@[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl
theorem ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker (g.comp f) = comap f (ker g) := rfl
theorem ker_le_ker_comp (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : ker f ≤ ker (g.comp f) :=
by rw ker_comp; exact comap_mono bot_le
theorem sub_mem_ker_iff {f : M →ₗ[R] M₂} {x y} : x - y ∈ f.ker ↔ f x = f y :=
by rw [mem_ker, map_sub, sub_eq_zero]
theorem disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 :=
by simp [disjoint_def]
theorem disjoint_ker' {f : M →ₗ[R] M₂} {p : submodule R M} :
disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y :=
disjoint_ker.trans
⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]),
λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩
theorem inj_of_disjoint_ker {f : M →ₗ[R] M₂} {p : submodule R M}
{s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) :
∀ x y ∈ s, f x = f y → x = y :=
λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy)
lemma disjoint_inl_inr : disjoint (inl R M M₂).range (inr R M M₂).range :=
by simp [disjoint_def, @eq_comm M 0, @eq_comm M₂ 0] {contextual := tt}; intros; refl
theorem ker_eq_bot {f : M →ₗ[R] M₂} : ker f = ⊥ ↔ injective f :=
by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ f ⊤
theorem ker_eq_bot' {f : M →ₗ[R] M₂} :
ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) :=
have h : (∀ m ∈ (⊤ : submodule R M), f m = 0 → m = 0) ↔ (∀ m, f m = 0 → m = 0),
from ⟨λ h m, h m mem_top, λ h m _, h m⟩,
by simpa [h, disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ f ⊤
lemma le_ker_iff_map {f : M →ₗ[R] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ :=
by rw [ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
ker (cod_restrict p f hf) = ker f :=
by rw [ker, comap_cod_restrict, map_bot]; refl
lemma range_cod_restrict (p : submodule R M) (f : M₂ →ₗ[R] M) (hf) :
range (cod_restrict p f hf) = comap p.subtype f.range :=
map_cod_restrict _ _ _ _
lemma map_comap_eq (f : M →ₗ[R] M₂) (q : submodule R M₂) :
map f (comap f q) = range f ⊓ q :=
le_antisymm (le_inf (map_mono le_top) (map_comap_le _ _)) $
by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩
lemma map_comap_eq_self {f : M →ₗ[R] M₂} {q : submodule R M₂} (h : q ≤ range f) :
map f (comap f q) = q :=
by rw [map_comap_eq, inf_of_le_right h]
lemma comap_map_eq (f : M →ₗ[R] M₂) (p : submodule R M) :
comap f (map f p) = p ⊔ ker f :=
begin
refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)),
rintro x ⟨y, hy, e⟩,
exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩
end
lemma comap_map_eq_self {f : M →ₗ[R] M₂} {p : submodule R M} (h : ker f ≤ p) :
comap f (map f p) = p :=
by rw [comap_map_eq, sup_of_le_left h]
@[simp] theorem ker_zero : ker (0 : M →ₗ[R] M₂) = ⊤ :=
eq_top_iff'.2 $ λ x, by simp
@[simp] theorem range_zero : range (0 : M →ₗ[R] M₂) = ⊥ :=
submodule.map_zero _
theorem ker_eq_top {f : M →ₗ[R] M₂} : ker f = ⊤ ↔ f = 0 :=
⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩
lemma range_le_bot_iff (f : M →ₗ[R] M₂) : range f ≤ ⊥ ↔ f = 0 :=
by rw [range_le_iff_comap]; exact ker_eq_top
theorem map_le_map_iff {f : M →ₗ[R] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' :=
⟨λ H x hx, let ⟨y, hy, e⟩ := H ⟨x, hx, rfl⟩ in ker_eq_bot.1 hf e ▸ hy, map_mono⟩
theorem map_injective {f : M →ₗ[R] M₂} (hf : ker f = ⊥) : injective (map f) :=
λ p p' h, le_antisymm ((map_le_map_iff hf).1 (le_of_eq h)) ((map_le_map_iff hf).1 (ge_of_eq h))
theorem comap_le_comap_iff {f : M →ₗ[R] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' :=
⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩
theorem comap_injective {f : M →ₗ[R] M₂} (hf : range f = ⊤) : injective (comap f) :=
λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h))
theorem map_copair_prod (f : M →ₗ[R] M₃) (g : M₂ →ₗ[R] M₃) (p : submodule R M) (q : submodule R M₂) :
map (copair f g) (p.prod q) = map f p ⊔ map g q :=
begin
refine le_antisymm _ (sup_le (map_le_iff_le_comap.2 _) (map_le_iff_le_comap.2 _)),
{ rw le_def', rintro _ ⟨x, ⟨h₁, h₂⟩, rfl⟩,
exact mem_sup.2 ⟨_, ⟨_, h₁, rfl⟩, _, ⟨_, h₂, rfl⟩, rfl⟩ },
{ exact λ x hx, ⟨(x, 0), by simp [hx]⟩ },
{ exact λ x hx, ⟨(0, x), by simp [hx]⟩ }
end
theorem comap_pair_prod (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) (p : submodule R M₂) (q : submodule R M₃) :
comap (pair f g) (p.prod q) = comap f p ⊓ comap g q :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_inf_comap (p : submodule R M) (q : submodule R M₂) :
p.prod q = p.comap (linear_map.fst R M M₂) ⊓ q.comap (linear_map.snd R M M₂) :=
submodule.ext $ λ x, iff.rfl
theorem prod_eq_sup_map (p : submodule R M) (q : submodule R M₂) :
p.prod q = p.map (linear_map.inl R M M₂) ⊔ q.map (linear_map.inr R M M₂) :=
by rw [← map_copair_prod, copair_inl_inr, map_id]
lemma span_inl_union_inr {s : set M} {t : set M₂} :
span R (prod.inl '' s ∪ prod.inr '' t) = (span R s).prod (span R t) :=
by rw [span_union, prod_eq_sup_map, ← span_image, ← span_image]; refl
lemma ker_pair (f : M →ₗ[R] M₂) (g : M →ₗ[R] M₃) :
ker (pair f g) = ker f ⊓ ker g :=
by rw [ker, ← prod_bot, comap_pair_prod]; refl
end linear_map
namespace linear_map
variables [discrete_field K]
variables [add_comm_group V] [vector_space K V]
variables [add_comm_group V₂] [vector_space K V₂]
lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f :=
submodule.comap_smul f _ a h
lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f :=
submodule.comap_smul' f _ a
lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f :=
submodule.map_smul f _ a h
lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f :=
submodule.map_smul' f _ a
end linear_map
namespace is_linear_map
lemma is_linear_map_add {R M : Type*} [ring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 + x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
lemma is_linear_map_sub {R M : Type*} [ring R] [add_comm_group M] [module R M]:
is_linear_map R (λ (x : M × M), x.1 - x.2) :=
begin
apply is_linear_map.mk,
{ intros x y,
simp },
{ intros x y,
simp [smul_add] }
end
end is_linear_map
namespace submodule
variables {T : ring R} [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
variables (p p' : submodule R M) (q : submodule R M₂)
include T
open linear_map
@[simp] theorem map_top (f : M →ₗ[R] M₂) : map f ⊤ = range f := rfl
@[simp] theorem comap_bot (f : M →ₗ[R] M₂) : comap f ⊥ = ker f := rfl
@[simp] theorem ker_subtype : p.subtype.ker = ⊥ :=
ker_eq_bot.2 $ λ x y, subtype.eq'
@[simp] theorem range_subtype : p.subtype.range = p :=
by simpa using map_comap_subtype p ⊤
lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p :=
by simpa using (map_mono le_top : map p.subtype p' ≤ p.subtype.range)
@[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ :=
by rw [of_le, ker_cod_restrict, ker_subtype]
lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p :=
by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype]
lemma disjoint_iff_comap_eq_bot (p q : submodule R M) :
disjoint p q ↔ comap p.subtype q = ⊥ :=
by rw [eq_bot_iff, ← map_le_map_iff p.ker_subtype, map_bot, map_comap_subtype]; refl
/-- If N ⊆ M then submodules of N are the same as submodules of M contained in N -/
def map_subtype.order_iso :
((≤) : submodule R p → submodule R p → Prop) ≃o
((≤) : {p' : submodule R M // p' ≤ p} → {p' : submodule R M // p' ≤ p} → Prop) :=
{ to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩,
inv_fun := λ q, comap p.subtype q,
left_inv := λ p', comap_map_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [map_comap_subtype p, inf_of_le_right hq],
ord := λ p₁ p₂, (map_le_map_iff $ ker_subtype _).symm }
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of M. -/
def map_subtype.le_order_embedding :
((≤) : submodule R p → submodule R p → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) :=
(order_iso.to_order_embedding $ map_subtype.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma map_subtype_embedding_eq (p' : submodule R p) :
map_subtype.le_order_embedding p p' = map p.subtype p' := rfl
/-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of
submodules of M. -/
def map_subtype.lt_order_embedding :
((<) : submodule R p → submodule R p → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) :=
(map_subtype.le_order_embedding p).lt_embedding_of_le_embedding
@[simp] theorem map_inl : p.map (inl R M M₂) = prod p ⊥ :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem map_inr : q.map (inr R M M₂) = prod ⊥ q :=
by ext ⟨x, y⟩; simp [and.left_comm, eq_comm]
@[simp] theorem comap_fst : p.comap (fst R M M₂) = prod p ⊤ :=
by ext ⟨x, y⟩; simp
@[simp] theorem comap_snd : q.comap (snd R M M₂) = prod ⊤ q :=
by ext ⟨x, y⟩; simp
@[simp] theorem prod_comap_inl : (prod p q).comap (inl R M M₂) = p := by ext; simp
@[simp] theorem prod_comap_inr : (prod p q).comap (inr R M M₂) = q := by ext; simp
@[simp] theorem prod_map_fst : (prod p q).map (fst R M M₂) = p :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ q)]
@[simp] theorem prod_map_snd : (prod p q).map (snd R M M₂) = q :=
by ext x; simp [(⟨0, zero_mem _⟩ : ∃ x, x ∈ p)]
@[simp] theorem ker_inl : (inl R M M₂).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inl]
@[simp] theorem ker_inr : (inr R M M₂).ker = ⊥ :=
by rw [ker, ← prod_bot, prod_comap_inr]
@[simp] theorem range_fst : (fst R M M₂).range = ⊤ :=
by rw [range, ← prod_top, prod_map_fst]
@[simp] theorem range_snd : (snd R M M₂).range = ⊤ :=
by rw [range, ← prod_top, prod_map_snd]
/-- The map from a module `M` to the quotient of `M` by a submodule `p` is a linear map. -/
def mkq : M →ₗ[R] p.quotient := ⟨quotient.mk, by simp, by simp⟩
@[simp] theorem mkq_apply (x : M) : p.mkq x = quotient.mk x := rfl
/-- The map from the quotient of `M` by a submodule `p` to `M₂` along `f : M → M₂` is linear. -/
def liftq (f : M →ₗ[R] M₂) (h : p ≤ f.ker) : p.quotient →ₗ[R] M₂ :=
⟨λ x, _root_.quotient.lift_on' x f $
λ a b (ab : a - b ∈ p), eq_of_sub_eq_zero $ by simpa using h ab,
by rintro ⟨x⟩ ⟨y⟩; exact f.map_add x y,
by rintro a ⟨x⟩; exact f.map_smul a x⟩
@[simp] theorem liftq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
p.liftq f h (quotient.mk x) = f x := rfl
@[simp] theorem liftq_mkq (f : M →ₗ[R] M₂) (h) : (p.liftq f h).comp p.mkq = f :=
by ext; refl
@[simp] theorem range_mkq : p.mkq.range = ⊤ :=
eq_top_iff'.2 $ by rintro ⟨x⟩; exact ⟨x, trivial, rfl⟩
@[simp] theorem ker_mkq : p.mkq.ker = p :=
by ext; simp
lemma le_comap_mkq (p' : submodule R p.quotient) : p ≤ comap p.mkq p' :=
by simpa using (comap_mono bot_le : p.mkq.ker ≤ comap p.mkq p')
@[simp] theorem mkq_map_self : map p.mkq p = ⊥ :=
by rw [eq_bot_iff, map_le_iff_le_comap, comap_bot, ker_mkq]; exact le_refl _
@[simp] theorem comap_map_mkq : comap p.mkq (map p.mkq p') = p ⊔ p' :=
by simp [comap_map_eq, sup_comm]
/-- The map from the quotient of `M` by submodule `p` to the quotient of `M₂` by submodule `q` along
`f : M → M₂` is linear. -/
def mapq (f : M →ₗ[R] M₂) (h : p ≤ comap f q) : p.quotient →ₗ[R] q.quotient :=
p.liftq (q.mkq.comp f) $ by simpa [ker_comp] using h
@[simp] theorem mapq_apply (f : M →ₗ[R] M₂) {h} (x : M) :
mapq p q f h (quotient.mk x) = quotient.mk (f x) := rfl
theorem mapq_mkq (f : M →ₗ[R] M₂) {h} : (mapq p q f h).comp p.mkq = q.mkq.comp f :=
by ext x; refl
theorem comap_liftq (f : M →ₗ[R] M₂) (h) :
q.comap (p.liftq f h) = (q.comap f).map (mkq p) :=
le_antisymm
(by rintro ⟨x⟩ hx; exact ⟨_, hx, rfl⟩)
(by rw [map_le_iff_le_comap, ← comap_comp, liftq_mkq]; exact le_refl _)
theorem map_liftq (f : M →ₗ[R] M₂) (h) (q : submodule R (quotient p)) :
q.map (p.liftq f h) = (q.comap p.mkq).map f :=
le_antisymm
(by rintro _ ⟨⟨x⟩, hxq, rfl⟩; exact ⟨x, hxq, rfl⟩)
(by rintro _ ⟨x, hxq, rfl⟩; exact ⟨quotient.mk x, hxq, rfl⟩)
theorem ker_liftq (f : M →ₗ[R] M₂) (h) :
ker (p.liftq f h) = (ker f).map (mkq p) := comap_liftq _ _ _ _
theorem range_liftq (f : M →ₗ[R] M₂) (h) :
range (p.liftq f h) = range f := map_liftq _ _ _ _
theorem ker_liftq_eq_bot (f : M →ₗ[R] M₂) (h) (h' : ker f ≤ p) : ker (p.liftq f h) = ⊥ :=
by rw [ker_liftq, le_antisymm h h', mkq_map_self]
/-- The correspondence theorem for modules: there is an order isomorphism between submodules of the
quotient of `M` by `p`, and submodules of `M` larger than `p`. -/
def comap_mkq.order_iso :
((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≃o
((≤) : {p' : submodule R M // p ≤ p'} → {p' : submodule R M // p ≤ p'} → Prop) :=
{ to_fun := λ p', ⟨comap p.mkq p', le_comap_mkq p _⟩,
inv_fun := λ q, map p.mkq q,
left_inv := λ p', map_comap_eq_self $ by simp,
right_inv := λ ⟨q, hq⟩, subtype.eq' $ by simp [comap_map_mkq p, sup_of_le_right hq],
ord := λ p₁ p₂, (comap_le_comap_iff $ range_mkq _).symm }
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.le_order_embedding :
((≤) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((≤) : submodule R M → submodule R M → Prop) :=
(order_iso.to_order_embedding $ comap_mkq.order_iso p).trans (subtype.order_embedding _ _)
@[simp] lemma comap_mkq_embedding_eq (p' : submodule R p.quotient) :
comap_mkq.le_order_embedding p p' = comap p.mkq p' := rfl
/-- The ordering on submodules of the quotient of `M` by `p` embeds into the ordering on submodules
of `M`. -/
def comap_mkq.lt_order_embedding :
((<) : submodule R p.quotient → submodule R p.quotient → Prop) ≼o ((<) : submodule R M → submodule R M → Prop) :=
(comap_mkq.le_order_embedding p).lt_embedding_of_le_embedding
end submodule
section
set_option old_structure_cmd true
/-- A linear equivalence is an invertible linear map. -/
structure linear_equiv (R : Type u) (M : Type v) (M₂ : Type w)
[ring R] [add_comm_group M] [add_comm_group M₂] [module R M] [module R M₂]
extends M →ₗ[R] M₂, M ≃ M₂
end
infix ` ≃ₗ ` := linear_equiv _
notation M ` ≃ₗ[`:50 R `] ` M₂ := linear_equiv R M M₂
namespace linear_equiv
section ring
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
instance : has_coe (M ≃ₗ[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩
@[simp] theorem coe_apply (e : M ≃ₗ[R] M₂) (b : M) : (e : M →ₗ[R] M₂) b = e b := rfl
lemma to_equiv_injective : function.injective (to_equiv : (M ≃ₗ[R] M₂) → M ≃ M₂) :=
λ ⟨_, _, _, _, _, _⟩ ⟨_, _, _, _, _, _⟩ h, linear_equiv.mk.inj_eq.mpr (equiv.mk.inj h)
@[extensionality] lemma ext {f g : M ≃ₗ[R] M₂} (h : (f : M → M₂) = g) : f = g :=
to_equiv_injective (equiv.eq_of_to_fun_eq h)
section
variable (M)
/-- The identity map is a linear equivalence. -/
def refl : M ≃ₗ[R] M := { .. linear_map.id, .. equiv.refl M }
end
/-- Linear equivalences are symmetric. -/
def symm (e : M ≃ₗ[R] M₂) : M₂ ≃ₗ[R] M :=
{ .. e.to_linear_map.inverse e.inv_fun e.left_inv e.right_inv,
.. e.to_equiv.symm }
/-- Linear equivalences are transitive. -/
def trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : M ≃ₗ[R] M₃ :=
{ .. e₂.to_linear_map.comp e₁.to_linear_map,
.. e₁.to_equiv.trans e₂.to_equiv }
@[simp] theorem apply_symm_apply (e : M ≃ₗ[R] M₂) (c : M₂) : e (e.symm c) = c := e.6 c
@[simp] theorem symm_apply_apply (e : M ≃ₗ[R] M₂) (b : M) : e.symm (e b) = b := e.5 b
/-- A bijective linear map is a linear equivalence. Here, bijectivity is described by saying that
the kernel of `f` is `{0}` and the range is the universal set. -/
noncomputable def of_bijective
(f : M →ₗ[R] M₂) (hf₁ : f.ker = ⊥) (hf₂ : f.range = ⊤) : M ≃ₗ[R] M₂ :=
{ ..f, ..@equiv.of_bijective _ _ f
⟨linear_map.ker_eq_bot.1 hf₁, linear_map.range_eq_top.1 hf₂⟩ }
@[simp] theorem of_bijective_apply (f : M →ₗ[R] M₂) {hf₁ hf₂} (x : M) :
of_bijective f hf₁ hf₂ x = f x := rfl
/-- If a linear map has an inverse, it is a linear equivalence. -/
def of_linear (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M)
(h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₗ[R] M₂ :=
{ inv_fun := g,
left_inv := linear_map.ext_iff.1 h₂,
right_inv := linear_map.ext_iff.1 h₁,
..f }
@[simp] theorem of_linear_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂}
(x : M) : of_linear f g h₁ h₂ x = f x := rfl
@[simp] theorem of_linear_symm_apply (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M) {h₁ h₂}
(x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl
@[simp] protected theorem ker (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).ker = ⊥ :=
linear_map.ker_eq_bot.2 f.to_equiv.injective
@[simp] protected theorem range (f : M ≃ₗ[R] M₂) : (f : M →ₗ[R] M₂).range = ⊤ :=
linear_map.range_eq_top.2 f.to_equiv.surjective
/-- The top submodule of `M` is linearly equivalent to `M`. -/
def of_top (p : submodule R M) (h : p = ⊤) : p ≃ₗ[R] M :=
{ inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩,
left_inv := λ ⟨x, h⟩, rfl,
right_inv := λ x, rfl,
.. p.subtype }
@[simp] theorem of_top_apply (p : submodule R M) {h} (x : p) :
of_top p h x = x := rfl
@[simp] theorem of_top_symm_apply (p : submodule R M) {h} (x : M) :
↑((of_top p h).symm x) = x := rfl
lemma eq_bot_of_equiv (p : submodule R M) (e : p ≃ₗ[R] (⊥ : submodule R M₂)) :
p = ⊥ :=
begin
refine bot_unique (submodule.le_def'.2 $ assume b hb, (submodule.mem_bot R).2 _),
have := e.symm_apply_apply ⟨b, hb⟩,
rw [← e.coe_apply, submodule.eq_zero_of_bot_submodule ((e : p →ₗ[R] (⊥ : submodule R M₂)) ⟨b, hb⟩),
← e.symm.coe_apply, linear_map.map_zero] at this,
exact congr_arg (coe : p → M) this.symm
end
end ring
section comm_ring
variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
include R
open linear_map
set_option class.instance_max_depth 39
/-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/
def smul_of_unit (a : units R) : M ≃ₗ[R] M :=
of_linear ((a:R) • 1 : M →ₗ M) (((a⁻¹ : units R) : R) • 1 : M →ₗ M)
(by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl)
(by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl)
/-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a
linear isomorphism between the two function spaces. -/
def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_ring R]
[add_comm_group M₁] [add_comm_group M₂] [add_comm_group M₂₁] [add_comm_group M₂₂]
[module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂]
(e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) :
(M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) :=
{ to_fun := λ f, e₂.to_linear_map.comp $ f.comp e₁.symm.to_linear_map,
inv_fun := λ f, e₂.symm.to_linear_map.comp $ f.comp e₁.to_linear_map,
left_inv := λ f, by { ext x, unfold_coes,
change e₂.inv_fun (e₂.to_fun $ f.to_fun $ e₁.inv_fun $ e₁.to_fun x) = _,
rw [e₁.left_inv, e₂.left_inv] },
right_inv := λ f, by { ext x, unfold_coes,
change e₂.to_fun (e₂.inv_fun $ f.to_fun $ e₁.to_fun $ e₁.inv_fun x) = _,
rw [e₁.right_inv, e₂.right_inv] },
add := λ f g, by { ext x, change e₂.to_fun ((f + g) (e₁.inv_fun x)) = _,
rw [linear_map.add_apply, e₂.add], refl },
smul := λ c f, by { ext x, change e₂.to_fun ((c • f) (e₁.inv_fun x)) = _,
rw [linear_map.smul_apply, e₂.smul], refl } }
/-- If M₂ and M₃ are linearly isomorphic then the two spaces of linear maps from M into M₂ and
M into M₃ are linearly isomorphic. -/
def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ (M →ₗ M₃) := arrow_congr (linear_equiv.refl M) f
/-- If M and M₂ are linearly isomorphic then the two spaces of linear maps from M and M₂ to themselves
are linearly isomorphic. -/
def conj (e : M ≃ₗ[R] M₂) : (M →ₗ[R] M) ≃ₗ[R] (M₂ →ₗ[R] M₂) := arrow_congr e e
end comm_ring
section field
variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module K M] [module K M₂] [module K M₃]
variable (M)
open linear_map
/-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/
def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M :=
smul_of_unit $ units.mk0 a ha
end field
end linear_equiv
namespace equiv
variables [ring R] [add_comm_group M] [module R M] [add_comm_group M₂] [module R M₂]
/-- An equivalence whose underlying function is linear is a linear equivalence. -/
def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ :=
{ add := h.add, smul := h.smul, .. e}
end equiv
namespace linear_map
variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
variables [module R M] [module R M₂] [module R M₃]
variables (f : M →ₗ[R] M₂)
/-- The first isomorphism law for modules. The quotient of `M` by the kernel of `f` is linearly
equivalent to the range of `f`. -/
noncomputable def quot_ker_equiv_range : f.ker.quotient ≃ₗ[R] f.range :=
have hr : ∀ x : f.range, ∃ y, f y = ↑x := λ x, x.2.imp $ λ _, and.right,
let F : f.ker.quotient →ₗ[R] f.range :=
f.ker.liftq (cod_restrict f.range f $ λ x, ⟨x, trivial, rfl⟩)
(λ x hx, by simp; apply subtype.coe_ext.2; simpa using hx) in
{ inv_fun := λx, submodule.quotient.mk (classical.some (hr x)),
left_inv := by rintro ⟨x⟩; exact
(submodule.quotient.eq _).2 (sub_mem_ker_iff.2 $
classical.some_spec $ hr $ F $ submodule.quotient.mk x),
right_inv := λ x : range f, subtype.eq $ classical.some_spec (hr x),
.. F }
open submodule
/--
Canonical linear map from the quotient p/(p ∩ p') to (p+p')/p', mapping x + (p ∩ p') to x + p',
where p and p' are submodules of an ambient module.
-/
def sup_quotient_to_quotient_inf (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient →ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
(comap p.subtype (p ⊓ p')).liftq
((comap (p ⊔ p').subtype p').mkq.comp (of_le le_sup_left)) begin
rw [ker_comp, of_le, comap_cod_restrict, ker_mkq, map_comap_subtype],
exact comap_mono (inf_le_inf le_sup_left (le_refl _)) end
set_option class.instance_max_depth 41
/--
Second Isomorphism Law : the canonical map from p/(p ∩ p') to (p+p')/p' as a linear isomorphism.
-/
noncomputable def sup_quotient_equiv_quotient_inf (p p' : submodule R M) :
(comap p.subtype (p ⊓ p')).quotient ≃ₗ[R] (comap (p ⊔ p').subtype p').quotient :=
{ .. sup_quotient_to_quotient_inf p p',
.. show (comap p.subtype (p ⊓ p')).quotient ≃ (comap (p ⊔ p').subtype p').quotient, from
@equiv.of_bijective _ _ (sup_quotient_to_quotient_inf p p') begin
constructor,
{ rw [← ker_eq_bot, sup_quotient_to_quotient_inf, ker_liftq_eq_bot],
rw [ker_comp, ker_mkq],
rintros ⟨x, hx1⟩ hx2, exact ⟨hx1, hx2⟩ },
rw [← range_eq_top, sup_quotient_to_quotient_inf, range_liftq, eq_top_iff'],
rintros ⟨x, hx⟩, rcases mem_sup.1 hx with ⟨y, hy, z, hz, rfl⟩,
use [⟨y, hy⟩, trivial], apply (submodule.quotient.eq _).2,
change y - (y + z) ∈ p', rwa [sub_add_eq_sub_sub, sub_self, zero_sub, neg_mem_iff]
end }
section prod
/-- The cartesian product of two linear maps as a linear map. -/
def prod {R M M₂ M₃ : Type*} [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃]
[module R M] [module R M₂] [module R M₃]
(f₁ : M →ₗ[R] M₂) (f₂ : M →ₗ[R] M₃) : M →ₗ[R] (M₂ × M₃) :=
{ to_fun := λx, (f₁ x, f₂ x),
add := λx y, begin
change (f₁ (x + y), f₂ (x+y)) = (f₁ x, f₂ x) + (f₁ y, f₂ y),
simp only [linear_map.map_add],
refl
end,
smul := λc x, by simp only [linear_map.map_smul] }
lemma is_linear_map_prod_iso {R M M₂ M₃ : Type*} [comm_ring R] [add_comm_group M] [add_comm_group M₂]
[add_comm_group M₃] [module R M] [module R M₂] [module R M₃] :
is_linear_map R (λ(p : (M →ₗ[R] M₂) × (M →ₗ[R] M₃)), (linear_map.prod p.1 p.2 : (M →ₗ[R] (M₂ × M₃)))) :=
⟨λu v, rfl, λc u, rfl⟩
end prod
section pi
universe i
variables {φ : ι → Type i}
variables [∀i, add_comm_group (φ i)] [∀i, module R (φ i)]
/-- `pi` construction for linear functions. From a family of linear functions it produces a linear
function into a family of modules. -/
def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) :=
⟨λc i, f i c,
assume c d, funext $ assume i, (f i).add _ _, assume c d, funext $ assume i, (f i).smul _ _⟩
@[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) :
pi f c i = f i c := rfl
lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) :=
by ext c; simp [funext_iff]; refl
lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩
lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 :=
by ext; refl
lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) :=
rfl
/-- The projections from a family of modules are linear maps. -/
def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i :=
⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩
@[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl
lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ :=
bot_unique $ submodule.le_def'.2 $ assume a h,
begin
simp only [mem_infi, mem_ker, proj_apply] at h,
exact (mem_bot _).2 (funext $ assume i, h i)
end
section
variables (R φ)
/-- If `I` and `J` are disjoint index sets, the product of the kernels of the `J`th projections of
`φ` is linearly equivalent to the product over `I`. -/
def infi_ker_proj_equiv {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) :=
begin
refine linear_equiv.of_linear
(pi $ λi, (proj (i:ι)).comp (submodule.subtype _))
(cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _,
{ assume b,
simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply],
assume j hjJ,
have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩,
rw [dif_neg this, zero_apply] },
{ simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.val_prop'],
ext b ⟨j, hj⟩, refl },
{ ext ⟨b, hb⟩,
apply subtype.coe_ext.2,
ext j,
have hb : ∀i ∈ J, b i = 0,
{ simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb },
simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply],
split_ifs,
{ rw [dif_pos h], refl },
{ rw [dif_neg h],
exact (hb _ $ (hu trivial).resolve_left h).symm } }
end
end
section
variable [decidable_eq ι]
/-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/
def diag (i j : ι) : φ i →ₗ[R] φ j :=
@function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j
lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) :
(update f i b j) c = update (λi, f i c) i (b c) j :=
begin
by_cases j = i,
{ rw [h, update_same, update_same] },
{ rw [update_noteq h, update_noteq h] }
end
end
section
variable [decidable_eq ι]
variables (R φ)
/-- The standard basis of the product of `φ`. -/
def std_basis (i : ι) : φ i →ₗ[R] (Πi, φ i) := pi (diag i)
lemma std_basis_apply (i : ι) (b : φ i) : std_basis R φ i b = update 0 i b :=
by ext j; rw [std_basis, pi_apply, diag, update_apply]; refl
@[simp] lemma std_basis_same (i : ι) (b : φ i) : std_basis R φ i b i = b :=
by rw [std_basis_apply, update_same]
lemma std_basis_ne (i j : ι) (h : j ≠ i) (b : φ i) : std_basis R φ i b j = 0 :=
by rw [std_basis_apply, update_noteq h]; refl
lemma ker_std_basis (i : ι) : ker (std_basis R φ i) = ⊥ :=
ker_eq_bot.2 $ assume f g hfg,
have std_basis R φ i f i = std_basis R φ i g i := hfg ▸ rfl,
by simpa only [std_basis_same]
lemma proj_comp_std_basis (i j : ι) : (proj i).comp (std_basis R φ j) = diag j i :=
by rw [std_basis, proj_pi]
lemma proj_std_basis_same (i : ι) : (proj i).comp (std_basis R φ i) = id :=
by ext b; simp
lemma proj_std_basis_ne (i j : ι) (h : i ≠ j) : (proj i).comp (std_basis R φ j) = 0 :=
by ext b; simp [std_basis_ne R φ _ _ h]
lemma supr_range_std_basis_le_infi_ker_proj (I J : set ι) (h : disjoint I J) :
(⨆i∈I, range (std_basis R φ i)) ≤ (⨅i∈J, ker (proj i)) :=
begin
refine (supr_le $ assume i, supr_le $ assume hi, range_le_iff_comap.2 _),
simp only [(ker_comp _ _).symm, eq_top_iff, le_def', mem_ker, comap_infi, mem_infi],
assume b hb j hj,
have : i ≠ j := assume eq, h ⟨hi, eq.symm ▸ hj⟩,
rw [proj_std_basis_ne R φ j i this.symm, zero_apply]
end
lemma infi_ker_proj_le_supr_range_std_basis {I : finset ι} {J : set ι} (hu : set.univ ⊆ ↑I ∪ J) :
(⨅ i∈J, ker (proj i)) ≤ (⨆i∈I, range (std_basis R φ i)) :=
submodule.le_def'.2
begin
assume b hb,
simp only [mem_infi, mem_ker, proj_apply] at hb,
rw ← show I.sum (λi, std_basis R φ i (b i)) = b,
{ ext i,
rw [pi.finset_sum_apply, ← std_basis_same R φ i (b i)],
refine finset.sum_eq_single i (assume j hjI ne, std_basis_ne _ _ _ _ ne.symm _) _,
assume hiI,
rw [std_basis_same],
exact hb _ ((hu trivial).resolve_left hiI) },
exact sum_mem _ (assume i hiI, mem_supr_of_mem _ i $ mem_supr_of_mem _ hiI $
linear_map.mem_range.2 ⟨_, rfl⟩)
end
lemma supr_range_std_basis_eq_infi_ker_proj {I J : set ι}
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) (hI : set.finite I) :
(⨆i∈I, range (std_basis R φ i)) = (⨅i∈J, ker (proj i)) :=
begin
refine le_antisymm (supr_range_std_basis_le_infi_ker_proj _ _ _ _ hd) _,
have : set.univ ⊆ ↑hI.to_finset ∪ J, { rwa [finset.coe_to_finset] },
refine le_trans (infi_ker_proj_le_supr_range_std_basis R φ this) (supr_le_supr $ assume i, _),
rw [← finset.mem_coe, finset.coe_to_finset],
exact le_refl _
end
lemma supr_range_std_basis [fintype ι] : (⨆i:ι, range (std_basis R φ i)) = ⊤ :=
have (set.univ : set ι) ⊆ ↑(finset.univ : finset ι) ∪ ∅ := by rw [finset.coe_univ, set.union_empty],
begin
apply top_unique,
convert (infi_ker_proj_le_supr_range_std_basis R φ this),
exact infi_emptyset.symm,
exact (funext $ λi, (@supr_pos _ _ _ (λh, range (std_basis R φ i)) $ finset.mem_univ i).symm)
end
lemma disjoint_std_basis_std_basis (I J : set ι) (h : disjoint I J) :
disjoint (⨆i∈I, range (std_basis R φ i)) (⨆i∈J, range (std_basis R φ i)) :=
begin
refine disjoint_mono
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl I)
(supr_range_std_basis_le_infi_ker_proj _ _ _ _ $ set.disjoint_compl J) _,
simp only [disjoint, submodule.le_def', mem_infi, mem_inf, mem_ker, mem_bot, proj_apply,
funext_iff],
rintros b ⟨hI, hJ⟩ i,
classical,
by_cases hiI : i ∈ I,
{ by_cases hiJ : i ∈ J,
{ exact (h ⟨hiI, hiJ⟩).elim },
{ exact hJ i hiJ } },
{ exact hI i hiI }
end
lemma std_basis_eq_single {a : R} :
(λ (i : ι), (std_basis R (λ _ : ι, R) i) a) = λ (i : ι), (finsupp.single i a) :=
begin
ext i j,
rw [std_basis_apply, finsupp.single_apply],
split_ifs,
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h)], refl },
end
end
end pi
variables (R M)
instance automorphism_group : group (M ≃ₗ[R] M) :=
{ mul := λ f g, g.trans f,
one := linear_equiv.refl M,
inv := λ f, f.symm,
mul_assoc := λ f g h, by {ext, refl},
mul_one := λ f, by {ext, refl},
one_mul := λ f, by {ext, refl},
mul_left_inv := λ f, by {ext, exact f.left_inv x} }
instance automorphism_group.to_linear_map_is_monoid_hom :
is_monoid_hom (linear_equiv.to_linear_map : (M ≃ₗ[R] M) → (M →ₗ[R] M)) :=
{ map_one := rfl,
map_mul := λ f g, rfl }
/-- The group of invertible linear maps from `M` to itself -/
def general_linear_group := units (M →ₗ[R] M)
namespace general_linear_group
variables {R M}
instance : group (general_linear_group R M) := by delta general_linear_group; apply_instance
/-- An invertible linear map `f` determines an equivalence from `M` to itself. -/
def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) :=
{ inv_fun := f.inv.to_fun,
left_inv := λ m, show (f.inv * f.val) m = m,
by erw f.inv_val; simp,
right_inv := λ m, show (f.val * f.inv) m = m,
by erw f.val_inv; simp,
..f.val }
/-- An equivalence from `M` to itself determines an invertible linear map. -/
def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M :=
{ val := f,
inv := f.symm,
val_inv := linear_map.ext $ λ _, f.apply_symm_apply _,
inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ }
variables (R M)
/-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear
equivalences between `M` and itself. -/
def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) :=
{ to_fun := to_linear_equiv,
inv_fun := of_linear_equiv,
left_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f with f f_inv, cases f, cases f_inv,
congr
end,
right_inv := λ f,
begin
delta to_linear_equiv of_linear_equiv,
cases f,
congr
end,
map_mul' := λ x y, by {ext, refl} }
@[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) :
((general_linear_equiv R M).to_equiv f).to_linear_map = f.val :=
by {ext, refl}
end general_linear_group
end linear_map
|
650628a7613298e34f40b1a089f1df19e8ae8aa8 | c3de33d4701e6113627153fe1103b255e752ed7d | /algebra/lattice/filter.lean | 270841ced2259e36946b11b7fc27792052439362 | [] | no_license | jroesch/library_dev | 77d2b246ff47ab05d55cb9706a37d3de97038388 | 4faa0a45c6aa7eee6e661113c2072b8840bff79b | refs/heads/master | 1,611,281,606,352 | 1,495,661,644,000 | 1,495,661,644,000 | 92,340,430 | 0 | 0 | null | 1,495,663,344,000 | 1,495,663,344,000 | null | UTF-8 | Lean | false | false | 65,715 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
Theory of filters on sets.
-/
import .complete_lattice ...data.set .zorn
open lattice set
universes u v w x
section applicative
variables {f : Type u → Type v} [applicative f] {α β : Type u}
lemma pure_seq_eq_map : ∀ {α β : Type u} (g : α → β) (x : f α), pure g <*> x = g <$> x :=
@applicative.pure_seq_eq_map f _
end applicative
section monad
variables {α β γ : Type u} {m : Type u → Type v} [monad m]
theorem map_bind (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = (x >>= λa, f <$> g a) :=
show f <$> (bind x g) = bind x (λa, f <$> (g a)),
by rw [-monad.bind_pure_comp_eq_map]; simp [monad.bind_pure_comp_eq_map, monad.bind_assoc]
theorem seq_bind_eq (x : m α) {g : β → m γ} {f : α → β} : (f <$> x) >>= g = (x >>= g ∘ f) :=
show bind (f <$> x) g = bind x (g ∘ f),
by rw [-monad.bind_pure_comp_eq_map, monad.bind_assoc]; simp [monad.pure_bind]
theorem seq_eq_bind_map {x : m α} {f : m (α → β)} : f <*> x = (f >>= (<$> x)) :=
(monad.bind_map_eq_seq m f x)^.symm
theorem bind_assoc : ∀ {α β γ : Type u} (x : m α) (f : α → m β) (g : β → m γ),
x >>= f >>= g = x >>= λ x, f x >>= g :=
@monad.bind_assoc m _
end monad
section prod
variables {α : Type u} {β : Type v}
@[simp] -- copied from parser
lemma prod.mk.eta : ∀{p : α × β}, (p.1, p.2) = p
| (a, b) := rfl
def prod.swap : (α×β) → (β×α) := λp, (p.2, p.1)
@[simp]
lemma prod.swap_swap : ∀x:α×β, prod.swap (prod.swap x) = x
| ⟨a, b⟩ := rfl
@[simp]
lemma prod.fst_swap {p : α×β} : (prod.swap p).1 = p.2 := rfl
@[simp]
lemma prod.snd_swap {p : α×β} : (prod.swap p).2 = p.1 := rfl
@[simp]
lemma prod.swap_prod_mk {a : α} {b : β} : prod.swap (a, b) = (b, a) := rfl
@[simp]
lemma prod.swap_swap_eq : prod.swap ∘ prod.swap = @id (α × β) :=
funext $ prod.swap_swap
end prod
namespace lattice
variables {α : Type u} {ι : Sort v} [complete_lattice α]
lemma Inf_eq_finite_sets {s : set α} :
Inf s = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t) :=
le_antisymm
(le_infi $ take t, le_infi $ take ⟨_, h⟩, Inf_le_Inf h)
(le_Inf $ take b h, infi_le_of_le {b} $ infi_le_of_le (by simp [h]) $ Inf_le $ by simp)
lemma Sup_le_iff {s : set α} {a : α} : Sup s ≤ a ↔ (∀x∈s, x ≤ a) :=
⟨take h x hx, le_trans (le_Sup hx) h, Sup_le⟩
end lattice
instance : monad set :=
{ monad .
pure := λ(α : Type u) a, {a},
bind := λ(α β : Type u) s f, ⋃i∈s, f i,
map := λ(α β : Type u), set.image,
pure_bind := take α β x f, by simp,
bind_assoc := take α β γ s f g, set.ext $ take a,
by simp; exact ⟨take ⟨b, ag, a, as, bf⟩, ⟨a, as, b, bf, ag⟩,
take ⟨a, as, b, bf, ag⟩, ⟨b, ag, a, as, bf⟩⟩,
id_map := take α, functor.id_map,
bind_pure_comp_eq_map := take α β f s, set.ext $ by simp [set.image, eq_comm] }
namespace set
section
variables {α β : Type u}
@[simp] theorem bind_def (s : set α) (f : α → set β) : s >>= f = ⋃i∈s, f i := rfl
theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s :=
⟨exists_mem_of_ne_empty, take ⟨x, (hx : x ∈ s)⟩ h, by rw [h] at hx; assumption⟩
lemma fmap_eq_image {f : α → β} {s : set α} : f <$> s = f '' s :=
rfl
lemma mem_seq_iff {f : set (α → β)} {s : set α} {b : β} :
b ∈ (f <*> s) ↔ (∃(f' : α → β), ∃a ∈ s, f' ∈ f ∧ b = f' a) :=
begin
simp [seq_eq_bind_map],
apply exists_congr,
intro f',
exact ⟨take ⟨hf', a, ha, h_eq⟩, ⟨a, h_eq^.symm, ha, hf'⟩,
take ⟨a, h_eq, ha, hf'⟩, ⟨hf', a, ha, h_eq^.symm⟩⟩
end
end
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
protected def prod (s : set α) (t : set β) : set (α × β) :=
{p | p.1 ∈ s ∧ p.2 ∈ t}
lemma mem_prod_eq {s : set α} {t : set β} {p : α × β} :
p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) :=
rfl
lemma prod_vimage_eq {s : set α} {t : set β} {f : γ → α} {g : δ → β} :
set.prod (vimage f s) (vimage g t) = vimage (λp, (f p.1, g p.2)) (set.prod s t) :=
rfl
lemma prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) :
set.prod s₁ t₁ ⊆ set.prod s₂ t₂ :=
take x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩
lemma prod_inter_prod {s₁ s₂ : set α} {t₁ t₂ : set β} :
set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) :=
subset.antisymm
(take ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩)
(subset_inter
(prod_mono (inter_subset_left _ _) (inter_subset_left _ _))
(prod_mono (inter_subset_right _ _) (inter_subset_right _ _)))
lemma monotone_prod [weak_order α] {f : α → set β} {g : α → set γ}
(hf : monotone f) (hg : monotone g) : monotone (λx, set.prod (f x) (g x)) :=
take a b h, prod_mono (hf h) (hg h)
lemma image_swap_prod {s : set α} {t : set β} :
image (λp:β×α, (p.2, p.1)) (set.prod t s) = set.prod s t :=
set.ext $ take ⟨a, b⟩, by simp [mem_image_eq, set.prod]; exact
⟨ take ⟨b', a', h_a, h_b, h⟩, by rw [h_a, h_b] at h; assumption,
take ⟨ha, hb⟩, ⟨b, a, rfl, rfl, ⟨ha, hb⟩⟩⟩
lemma prod_image_image_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{s₁ : set α₁} {s₂ : set α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
set.prod (image m₁ s₁) (image m₂ s₂) = image (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (set.prod s₁ s₂) :=
set.ext $ take ⟨b₁, b₂⟩,
⟨take ⟨⟨a₁, ha₁, (eq₁ : m₁ a₁ = b₁)⟩, ⟨a₂, ha₂, (eq₂ : m₂ a₂ = b₂)⟩⟩,
mem_image
(show (a₁, a₂) ∈ set.prod s₁ s₂, from ⟨ha₁, ha₂⟩)
(by simp [eq₁, eq₂]),
take ⟨⟨a₁, a₂⟩, ⟨ha₁, ha₂⟩, eq⟩, eq ▸ ⟨mem_image_of_mem m₁ ha₁, mem_image_of_mem m₂ ha₂⟩⟩
@[simp]
lemma prod_singleton_singleton {a : α} {b : β} :
set.prod {a} {b} = ({(a, b)} : set (α×β)) :=
set.ext $ take ⟨a', b'⟩, by simp [set.prod]
lemma prod_neq_empty_iff {s : set α} {t : set β} :
set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) :=
begin
rw [ne_empty_iff_exists_mem, ne_empty_iff_exists_mem, ne_empty_iff_exists_mem,
prod.exists],
exact ⟨take ⟨a, b, ha, hb⟩, ⟨⟨a, ha⟩, ⟨b, hb⟩⟩,
take ⟨⟨a, ha⟩, ⟨b, hb⟩⟩, ⟨a, b, ha, hb⟩⟩
end
@[simp]
lemma prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} :
(a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) :=
rfl
lemma monotone_inter [weak_order β] {f g : β → set α}
(hf : monotone f) (hg : monotone g) : monotone (λx, (f x) ∩ (g x)) :=
take a b h x ⟨h₁, h₂⟩, ⟨hf h h₁, hg h h₂⟩
@[simp]
lemma vimage_set_of_eq {p : α → Prop} {f : β → α} :
vimage f {a | p a} = {a | p (f a)} :=
rfl
@[simp]
lemma set_of_mem_eq {s : set α} : {x | x ∈ s} = s :=
rfl
lemma mem_image_iff_of_inverse (f : α → β) (g : β → α) {b : β} {s : set α}
(h₁ : ∀a, g (f a) = a ) (h₂ : ∀b, f (g b) = b ) : b ∈ f '' s ↔ g b ∈ s :=
⟨take ⟨a, ha, fa_eq⟩, fa_eq ▸ (h₁ a)^.symm ▸ ha,
take h, ⟨g b, h, h₂ b⟩⟩
lemma image_eq_vimage_of_inverse (f : α → β) (g : β → α)
(h₁ : ∀a, g (f a) = a ) (h₂ : ∀b, f (g b) = b ) : image f = vimage g :=
funext $ take s, set.ext $ take b, mem_image_iff_of_inverse f g h₁ h₂
lemma image_swap_eq_vimage_swap : image (@prod.swap α β) = vimage prod.swap :=
image_eq_vimage_of_inverse (@prod.swap α β) (@prod.swap β α)
begin simp; intros; trivial end
begin simp; intros; trivial end
lemma monotone_set_of [weak_order α] {p : α → β → Prop}
(hp : ∀b, monotone (λa, p a b)) : monotone (λa, {b | p a b}) :=
take a a' h b, hp b h
lemma diff_right_antimono {s t u : set α} (h : t ⊆ u) : s - u ⊆ s - t :=
take x ⟨hs, hnx⟩, ⟨hs, take hx, hnx $ h hx⟩
end set
section
variables {α : Type u} {ι : Sort v}
lemma sUnion_mono {s t : set (set α)} (h : s ⊆ t) : (⋃₀ s) ⊆ (⋃₀ t) :=
sUnion_subset $ take t' ht', subset_sUnion_of_mem $ h ht'
lemma Union_subset_Union {s t : ι → set α} (h : ∀i, s i ⊆ t i) : (⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr (set α) ι _ s t h
lemma Union_subset_Union2 {ι₂ : Sort x} {s : ι → set α} {t : ι₂ → set α} (h : ∀i, ∃j, s i ⊆ t j) : (⋃i, s i) ⊆ (⋃i, t i) :=
@supr_le_supr2 (set α) ι ι₂ _ s t h
lemma Union_subset_Union_const {ι₂ : Sort x} {s : set α} (h : ι → ι₂) : (⋃ i:ι, s) ⊆ (⋃ j:ι₂, s) :=
@supr_le_supr_const (set α) ι ι₂ _ s h
lemma diff_neq_empty {s t : set α} : s - t = ∅ ↔ s ⊆ t :=
⟨take h x hx, classical.by_contradiction $ suppose x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩,
take h, bot_unique $ take x ⟨hx, hnx⟩, hnx $ h hx⟩
@[simp]
lemma diff_empty {s : set α} : s - ∅ = s :=
set.ext $ take x, ⟨take ⟨hx, _⟩, hx, take h, ⟨h, not_false⟩⟩
end
@[simp] -- should be handled by implies_true_iff
lemma implies_implies_true_iff {α : Sort u} {β : Sort v} : (α → β → true) ↔ true :=
⟨take _, trivial, take _ _ _ , trivial⟩
@[simp]
lemma not_not_mem_iff {α : Type u} {a : α} {s : set α} : ¬ (a ∉ s) ↔ a ∈ s :=
classical.not_not_iff _
@[simp]
lemma singleton_neq_emptyset {α : Type u} {a : α} : {a} ≠ (∅ : set α) :=
take h,
have a ∉ ({a} : set α),
by simp [h],
this $ mem_singleton a
lemma not_imp_iff_not_imp {a b : Prop} :
(¬ a → ¬ b) ↔ (b → a) :=
⟨take h hb, classical.by_contradiction $ take na, h na hb,
contrapos⟩
lemma eq_of_sup_eq_inf_eq {α : Type u} [distrib_lattice α] {a b c : α}
(h₁ : b ⊓ a = c ⊓ a) (h₂ : b ⊔ a = c ⊔ a) : b = c :=
le_antisymm
(calc b ≤ (c ⊓ a) ⊔ b : le_sup_right
... = (c ⊔ b) ⊓ (a ⊔ b) : sup_inf_right
... = c ⊔ (c ⊓ a) : by rw [-h₁, sup_inf_left, -h₂]; simp [sup_comm]
... = c : sup_inf_self)
(calc c ≤ (b ⊓ a) ⊔ c : le_sup_right
... = (b ⊔ c) ⊓ (a ⊔ c) : sup_inf_right
... = b ⊔ (b ⊓ a) : by rw [h₁, sup_inf_left, h₂]; simp [sup_comm]
... = b : sup_inf_self)
lemma inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a b c : α}
(h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c :=
⟨suppose a ⊓ b = ⊥,
calc a ≤ a ⊓ (b ⊔ c) : by simp [h₁]
... = (a ⊓ b) ⊔ (a ⊓ c) : by simp [inf_sup_left]
... ≤ c : by simp [this, inf_le_right],
suppose a ≤ c,
bot_unique $
calc a ⊓ b ≤ b ⊓ c : by rw [inf_comm]; exact inf_le_inf (le_refl _) this
... = ⊥ : h₂⟩
lemma compl_image_set_of {α : Type u} {p : set α → Prop} :
compl '' {x | p x} = {x | p (- x)} :=
set.ext $ take x, ⟨take ⟨y, (hy : p y), (h_eq : -y = x)⟩,
show p (- x), by rw [-h_eq, lattice.neg_neg]; assumption,
assume h : p (-x), ⟨_, h, lattice.neg_neg⟩⟩
lemma neg_subset_neg_iff_subset {α : Type u} {x y : set α} : - y ⊆ - x ↔ x ⊆ y :=
@neg_le_neg_iff_le (set α) _ _ _
lemma sUnion_eq_Union {α : Type u} {s : set (set α)} :
(⋃₀ s) = (⋃ (i : set α) (h : i ∈ s), i) :=
set.ext $ by simp
lemma not_or_iff_implies {a b : Prop} : (¬ a ∨ b) ↔ (a → b) :=
⟨take h ha, h.neg_resolve_left ha, classical.not_or_of_implies⟩
section order
variables {α : Type u} (r : α → α → Prop)
local infix `≼` : 50 := r
def directed {ι : Sort v} (f : ι → α) := ∀x, ∀y, ∃z, f z ≼ f x ∧ f z ≼ f y
def directed_on (s : set α) := ∀x ∈ s, ∀y ∈ s, ∃z ∈ s, z ≼ x ∧ z ≼ y
lemma directed_on_Union {r} {ι : Sort v} {f : ι → set α} (hd : directed (⊇) f)
(h : ∀x, directed_on r (f x)) : directed_on r (⋃x, f x) :=
by simp [directed_on]; exact
take a₁ ⟨b₁, fb₁⟩ a₂ ⟨b₂, fb₂⟩,
let
⟨z, zb₁, zb₂⟩ := hd b₁ b₂,
⟨x, xf, xa₁, xa₂⟩ := h z a₁ (zb₁ fb₁) a₂ (zb₂ fb₂)
in
⟨x, xa₁, xa₂, z, xf⟩
def upwards (s : set α) := ∀{x y}, x ∈ s → x ≼ y → y ∈ s
end order
lemma directed_of_chain {α : Type u} {β : Type v} [weak_order β] {f : α → β} {c : set α}
(h : @zorn.chain α (λa b, f b ≤ f a) c) :
directed (≤) (λx:{a:α // a ∈ c}, f (x.val)) :=
take ⟨a, ha⟩ ⟨b, hb⟩, classical.by_cases
(suppose a = b, begin simp [this]; exact ⟨⟨b, hb⟩, le_refl _⟩ end)
(suppose a ≠ b,
have f b ≤ f a ∨ f a ≤ f b, from h a ha b hb this,
or.elim this
(suppose f b ≤ f a, ⟨⟨b, hb⟩, this, le_refl _⟩)
(suppose f a ≤ f b, ⟨⟨a, ha⟩, le_refl _, this⟩))
structure filter (α : Type u) :=
(sets : set (set α))
(inhabited : ∃x, x ∈ sets)
(upwards_sets : upwards (⊆) sets)
(directed_sets : directed_on (⊆) sets)
namespace filter
variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x}
lemma filter_eq : ∀{f g : filter α}, f^.sets = g^.sets → f = g
| ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl
lemma univ_mem_sets' {f : filter α} {s : set α} (h : ∀ a, a ∈ s): s ∈ f^.sets :=
let ⟨x, x_in_s⟩ := f^.inhabited in
f^.upwards_sets x_in_s (take x _, h x)
lemma univ_mem_sets {f : filter α} : univ ∈ f^.sets :=
univ_mem_sets' mem_univ
lemma inter_mem_sets {f : filter α} {x y : set α} (hx : x ∈ f^.sets) (hy : y ∈ f^.sets) :
x ∩ y ∈ f^.sets :=
let ⟨z, ⟨z_in_s, z_le_x, z_le_y⟩⟩ := f^.directed_sets _ hx _ hy in
f^.upwards_sets z_in_s (subset_inter z_le_x z_le_y)
lemma Inter_mem_sets {f : filter α} {s : β → set α}
{is : set β} (hf : finite is) (hs : ∀i∈is, s i ∈ f^.sets) : (⋂i∈is, s i) ∈ f^.sets :=
begin /- equation compiler complains that this is requires well-founded recursion -/
induction hf with i is _ hf hi,
{ simp [univ_mem_sets] },
begin
simp,
apply inter_mem_sets,
apply hs i,
simp,
exact (hi $ take a ha, hs _ $ by simp [ha])
end
end
lemma exists_sets_subset_iff {f : filter α} {x : set α} :
(∃y∈f^.sets, y ⊆ x) ↔ x ∈ f^.sets :=
⟨take ⟨y, hy, yx⟩, f^.upwards_sets hy yx,
take hx, ⟨x, hx, subset.refl _⟩⟩
lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f^.sets) :=
take s t hst h, f^.upwards_sets h hst
def principal (s : set α) : filter α :=
{ filter .
sets := {t | s ⊆ t},
inhabited := ⟨s, subset.refl _⟩,
upwards_sets := take x y hx hy, subset.trans hx hy,
directed_sets := take x hx y hy, ⟨s, subset.refl _, hx, hy⟩ }
def join (f : filter (filter α)) : filter α :=
{ filter .
sets := {s | {t | s ∈ filter.sets t} ∈ f^.sets},
inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := take x y hx xy, f^.upwards_sets hx $ take a h, a^.upwards_sets h xy,
directed_sets := take x hx y hy, ⟨x ∩ y,
f^.upwards_sets (inter_mem_sets hx hy) $ take z ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def map (m : α → β) (f : filter α) : filter β :=
{ filter .
sets := vimage (vimage m) f^.sets,
inhabited := ⟨univ, univ_mem_sets⟩,
upwards_sets := take s t hs st, f^.upwards_sets hs (take x h, st h),
directed_sets := take s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def vmap (m : α → β) (f : filter β) : filter α :=
{ filter .
sets := { s | ∃t∈f.sets, vimage m t ⊆ s },
inhabited := ⟨univ, univ, univ_mem_sets, by simp⟩,
upwards_sets := take a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩,
directed_sets := take a ⟨a', ha₁, ha₂⟩ b ⟨b', hb₁, hb₂⟩,
⟨vimage m (a' ∩ b'),
⟨a' ∩ b', inter_mem_sets ha₁ hb₁, subset.refl _⟩,
subset.trans (vimage_mono $ inter_subset_left _ _) ha₂,
subset.trans (vimage_mono $ inter_subset_right _ _) hb₂⟩ }
protected def sup (f g : filter α) : filter α :=
{ filter .
sets := f^.sets ∩ g^.sets,
inhabited := ⟨univ, by simp [univ_mem_sets]; exact univ_mem_sets⟩,
upwards_sets := take x y hx xy,
and.imp (take h, f^.upwards_sets h xy) (take h, g^.upwards_sets h xy) hx,
directed_sets := take x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∩ y,
⟨inter_mem_sets hx₁ hy₁, inter_mem_sets hx₂ hy₂⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
protected def inf (f g : filter α) :=
{ filter .
sets := {s | ∃ a ∈ f^.sets, ∃ b ∈ g^.sets, a ∩ b ⊆ s },
inhabited := ⟨univ, univ, univ_mem_sets, univ, univ_mem_sets, subset_univ _⟩,
upwards_sets := take x y ⟨a, ha, b, hb, h⟩ xy,
⟨a, ha, b, hb, subset.trans h xy⟩,
directed_sets := take x ⟨a₁, ha₁, b₁, hb₁, h₁⟩ y ⟨a₂, ha₂, b₂, hb₂, h₂⟩,
⟨x ∩ y,
⟨_, inter_mem_sets ha₁ ha₂, _, inter_mem_sets hb₁ hb₂,
calc (a₁ ⊓ a₂) ⊓ (b₁ ⊓ b₂) = (a₁ ⊓ b₁) ⊓ (a₂ ⊓ b₂) : by ac_refl
... ≤ x ∩ y : inf_le_inf h₁ h₂ ⟩,
inter_subset_left _ _, inter_subset_right _ _⟩ }
def cofinite : filter α :=
{ filter .
sets := {s | finite (- s)},
inhabited := ⟨univ, by simp⟩,
upwards_sets := take s t, assume hs : finite (-s), assume st: s ⊆ t,
finite_subset hs $ @lattice.neg_le_neg (set α) _ _ _ st,
directed_sets := take s, assume hs : finite (-s), take t, assume ht : finite (-t),
⟨s ∩ t, by simp [compl_inter, finite_union, ht, hs],
inter_subset_left _ _, inter_subset_right _ _⟩ }
instance weak_order_filter : weak_order (filter α) :=
{ weak_order .
le := λf g, g^.sets ⊆ f^.sets,
le_antisymm := take a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁,
le_refl := take a, subset.refl _,
le_trans := take a b c h₁ h₂, subset.trans h₂ h₁ }
instance : has_Sup (filter α) := ⟨join ∘ principal⟩
instance inhabited' : _root_.inhabited (filter α) :=
⟨principal ∅⟩
protected lemma le_Sup {s : set (filter α)} {f : filter α} : f ∈ s → f ≤ Sup s :=
take f_in_s t' h, h f_in_s
protected lemma Sup_le {s : set (filter α)} {f : filter α} : (∀g∈s, g ≤ f) → Sup s ≤ f :=
take h a ha g hg, h g hg ha
@[simp]
lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ (join f)^.sets = ({t | s ∈ filter.sets t} ∈ f^.sets) :=
rfl
@[simp]
lemma mem_principal_sets {s t : set α} : s ∈ (principal t)^.sets = (t ⊆ s) :=
rfl
@[simp]
lemma le_principal_iff {s : set α} {f : filter α} : f ≤ principal s ↔ s ∈ f^.sets :=
show (∀{t}, s ⊆ t → t ∈ f^.sets) ↔ s ∈ f^.sets,
from ⟨take h, h (subset.refl s), take hs t ht, f^.upwards_sets hs ht⟩
lemma principal_mono {s t : set α} : principal s ≤ principal t ↔ s ⊆ t :=
by simp
lemma monotone_principal : monotone (principal : set α → filter α) :=
by simp [monotone, principal_mono]; exact take a b h, h
@[simp]
lemma principal_eq_iff_eq {s t : set α} : principal s = principal t ↔ s = t :=
by simp [eq_iff_le_and_le]; refl
instance complete_lattice_filter : complete_lattice (filter α) :=
{ filter.weak_order_filter with
sup := filter.sup,
le_sup_left := take a b, inter_subset_left _ _,
le_sup_right := take a b, inter_subset_right _ _,
sup_le := take a b c h₁ h₂, subset_inter h₁ h₂,
inf := filter.inf,
le_inf := take f g h fg fh s ⟨a, ha, b, hb, h⟩,
f^.upwards_sets (inter_mem_sets (fg ha) (fh hb)) h,
inf_le_left := take f g s h, ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩,
inf_le_right := take f g s h, ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩,
top := principal univ,
le_top := take a, show a ≤ principal univ, by simp [univ_mem_sets],
bot := principal ∅,
bot_le := take a, show a^.sets ⊆ {x | ∅ ⊆ x}, by simp; apply subset_univ,
Sup := Sup,
le_Sup := take s f, filter.le_Sup,
Sup_le := take s f, filter.Sup_le,
Inf := λs, Sup {x | ∀y∈s, x ≤ y},
le_Inf := take s a h, filter.le_Sup h,
Inf_le := take s a ha, filter.Sup_le $ take b h, h _ ha }
@[simp]
lemma map_principal {s : set α} {f : α → β} :
map f (principal s) = principal (set.image f s) :=
filter_eq $ set.ext $ take a, image_subset_iff_subset_vimage^.symm
@[simp]
lemma join_principal_eq_Sup {s : set (filter α)} : join (principal s) = Sup s :=
rfl
instance monad_filter : monad filter :=
{ monad .
bind := λ(α β : Type u) f m, join (map m f),
pure := λ(α : Type u) x, principal {x},
map := λ(α β : Type u), filter.map,
id_map := take α f, filter_eq $ rfl,
pure_bind := take α β a f, by simp [Sup_image],
bind_assoc := take α β γ f m₁ m₂, filter_eq $ rfl,
bind_pure_comp_eq_map := take α β f x, filter_eq $ by simp [join, map, vimage, principal] }
@[simp] theorem pure_def (x : α) : pure x = principal {x} := rfl
@[simp] theorem bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = join (map m f) := rfl
instance : alternative filter :=
{ filter.monad_filter with
failure := λα, bot,
orelse := λα x y, x ⊔ y }
def at_top [weak_order α] : filter α := ⨅ a, principal {b | a ≤ b}
def at_bot [weak_order α] : filter α := ⨅ a, principal {b | b ≤ a}
/- lattice equations -/
lemma mem_inf_sets_of_left {f g : filter α} {s : set α} :
s ∈ f.sets → s ∈ (f ⊓ g)^.sets :=
have f ⊓ g ≤ f, from inf_le_left,
take hs, this hs
lemma mem_inf_sets_of_right {f g : filter α} {s : set α} :
s ∈ g.sets → s ∈ (f ⊓ g)^.sets :=
have f ⊓ g ≤ g, from inf_le_right,
take hs, this hs
@[simp]
lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α)^.sets :=
take x, false.elim
lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f^.sets ↔ f = ⊥ :=
⟨take h, bot_unique $ take s _, f.upwards_sets h (empty_subset s),
suppose f = ⊥, this.symm ▸ mem_bot_sets⟩
lemma inhabited_of_mem_sets {f : filter α} {s : set α} (hf : f ≠ ⊥) (hs : s ∈ f^.sets) :
∃x, x ∈ s :=
have ∅ ∉ f^.sets, from take h, hf $ empty_in_sets_eq_bot.mp h,
have s ≠ ∅, from take h, this (h ▸ hs),
exists_mem_of_ne_empty this
lemma filter_eq_bot_of_not_nonempty {f : filter α} (ne : ¬ nonempty α) : f = ⊥ :=
empty_in_sets_eq_bot.mp $ f.upwards_sets univ_mem_sets $
take x, false.elim (ne ⟨x⟩)
lemma forall_sets_neq_empty_iff_neq_bot {f : filter α} :
(∀ (s : set α), s ∈ f.sets → s ≠ ∅) ↔ f ≠ ⊥ :=
by
simp [(@empty_in_sets_eq_bot α f).symm];
exact ⟨take h hs, h _ hs rfl, take h s hs eq, h $ eq ▸ hs⟩
lemma mem_sets_of_neq_bot {f : filter α} {s : set α} (h : f ⊓ principal (-s) = ⊥) : s ∈ f.sets :=
have ∅ ∈ (f ⊓ principal (- s)).sets, from h.symm ▸ mem_bot_sets,
let ⟨s₁, hs₁, s₂, (hs₂ : -s ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in
have s₁ ⊆ s, from take a ha, classical.by_contradiction $ take ha', hs ⟨ha, hs₂ ha'⟩,
f.upwards_sets hs₁ this
@[simp]
lemma mem_sup_sets {f g : filter α} {s : set α} :
s ∈ (f ⊔ g)^.sets = (s ∈ f^.sets ∧ s ∈ g^.sets) :=
by refl
@[simp]
lemma mem_inf_sets {f g : filter α} {s : set α} :
s ∈ (f ⊓ g)^.sets = (∃t₁∈f^.sets, ∃t₂∈g^.sets, t₁ ∩ t₂ ⊆ s) :=
by refl
lemma infi_sets_eq {f : ι → filter α} (h : directed (≤) f) (ne : nonempty ι) :
(infi f)^.sets = (⋃ i, (f i)^.sets) :=
let
⟨i⟩ := ne,
u := { filter .
sets := (⋃ i, (f i)^.sets),
inhabited := ⟨univ, begin simp, exact ⟨i, univ_mem_sets⟩ end⟩,
directed_sets := directed_on_Union (show directed (≤) f, from h) (take i, (f i)^.directed_sets),
upwards_sets := by simp [upwards]; exact take x y ⟨j, xf⟩ xy, ⟨j, (f j)^.upwards_sets xf xy⟩ }
in
subset.antisymm
(show u ≤ infi f, from le_infi $ take i, le_supr (λi, (f i)^.sets) i)
(Union_subset $ take i, infi_le f i)
lemma infi_sets_eq' {f : β → filter α} {s : set β} (h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) :
(⨅ i∈s, f i)^.sets = (⋃ i ∈ s, (f i)^.sets) :=
let ⟨i, hi⟩ := ne in
calc (⨅ i ∈ s, f i)^.sets = (⨅ t : {t // t ∈ s}, (f t^.val))^.sets : by simp [infi_subtype]; refl
... = (⨆ t : {t // t ∈ s}, (f t^.val)^.sets) : infi_sets_eq
(take ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨆ t ∈ {t | t ∈ s}, (f t)^.sets) : by simp [supr_subtype]; refl
lemma Inf_sets_eq_finite {s : set (filter α)} :
(complete_lattice.Inf s)^.sets = (⋃ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t)^.sets) :=
calc (Inf s)^.sets = (⨅ t ∈ { t | finite t ∧ t ⊆ s}, Inf t)^.sets : by rw [lattice.Inf_eq_finite_sets]
... = (⨆ t ∈ {t | finite t ∧ t ⊆ s}, (Inf t)^.sets) : infi_sets_eq'
(take x ⟨hx₁, hx₂⟩ y ⟨hy₁, hy₂⟩, ⟨x ∪ y, ⟨finite_union hx₁ hy₁, union_subset hx₂ hy₂⟩,
Inf_le_Inf $ subset_union_left _ _, Inf_le_Inf $ subset_union_right _ _⟩)
⟨∅, by simp⟩
lemma supr_sets_eq {f : ι → filter α} : (supr f)^.sets = (⋂i, (f i)^.sets) :=
set.ext $ take s,
show s ∈ (join (principal {a : filter α | ∃i : ι, a = f i}))^.sets ↔ s ∈ (⋂i, (f i)^.sets),
begin
rw [mem_join_sets],
simp,
exact ⟨take h i, h (f i) ⟨_, rfl⟩, take h x ⟨i, eq⟩, eq^.symm ▸ h i⟩
end
@[simp]
lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) :=
filter_eq $ set.ext $ take x, by simp [supr_sets_eq, join]
@[simp]
lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) :=
filter_eq $ set.ext $ take x, by simp [supr_sets_eq, join]
instance : bounded_distrib_lattice (filter α) :=
{ filter.complete_lattice_filter with
le_sup_inf := take x y z s h,
begin
cases h with h₁ h₂, revert h₂,
simp,
exact take ⟨t₁, ht₁, t₂, ht₂, hs⟩, ⟨s ∪ t₁,
x^.upwards_sets h₁ $ subset_union_left _ _,
y^.upwards_sets ht₁ $ subset_union_right _ _,
s ∪ t₂,
x^.upwards_sets h₁ $ subset_union_left _ _,
z^.upwards_sets ht₂ $ subset_union_right _ _,
subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hs)⟩
end }
private theorem infi_finite_distrib {s : set (filter α)} {f : filter α} (h : finite s) :
(⨅ a ∈ s, f ⊔ a) = f ⊔ (Inf s) :=
begin
induction h with a s hn hs hi,
{ simp, exact infi_const bot },
{ rw [infi_insert], simp [hi, infi_or, sup_inf_left] }
end
/- the complementary version with ⨆ g∈s, f ⊓ g does not hold! -/
lemma binfi_sup_eq { f : filter α } {s : set (filter α)} :
(⨅ g∈s, f ⊔ g) = f ⊔ complete_lattice.Inf s :=
le_antisymm
begin
intros t h,
cases h with h₁ h₂,
rw [Inf_sets_eq_finite] at h₂,
simp at h₂,
cases h₂ with s' hs', cases hs' with hs' hs'', cases hs'' with hs's ht',
assert ht : t ∈ (⨅ a ∈ s', f ⊔ a)^.sets,
{ rw [infi_finite_distrib], exact ⟨h₁, ht'⟩, exact hs' },
clear h₁ ht',
revert ht t,
change (⨅ a ∈ s, f ⊔ a) ≤ (⨅ a ∈ s', f ⊔ a),
apply infi_le_infi2 _,
exact take i, ⟨i, infi_le_infi2 $ take h, ⟨hs's h, le_refl _⟩⟩
end
(le_infi $ take g, le_infi $ take h, sup_le_sup (le_refl f) $ Inf_le h)
lemma infi_sup_eq { f : filter α } {g : ι → filter α} :
(⨅ x, f ⊔ g x) = f ⊔ infi g :=
calc (⨅ x, f ⊔ g x) = (⨅ x (h : ∃i, g i = x), f ⊔ x) : by simp; rw [infi_comm]; simp
... = f ⊔ Inf {x | ∃i, g i = x} : binfi_sup_eq
... = f ⊔ infi g : by rw [Inf_eq_infi]; dsimp; simp; rw [infi_comm]; simp
/- principal equations -/
@[simp]
lemma inf_principal {s t : set α} : principal s ⊓ principal t = principal (s ∩ t) :=
le_antisymm
(by simp; exact ⟨s, subset.refl s, t, subset.refl t, subset.refl _⟩)
(by simp [le_inf_iff, inter_subset_left, inter_subset_right])
@[simp]
lemma sup_principal {s t : set α} : principal s ⊔ principal t = principal (s ∪ t) :=
filter_eq $ set.ext $ by simp [union_subset_iff]
@[simp]
lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, principal (s x)) = principal (⋃i, s i) :=
filter_eq $ set.ext $ take x, by simp [supr_sets_eq]; exact (@supr_le_iff (set α) _ _ _ _)^.symm
lemma principal_univ : principal (univ : set α) = top :=
rfl
lemma principal_empty : principal (∅ : set α) = bot :=
rfl
@[simp]
lemma principal_eq_bot_iff {s : set α} : principal s = ⊥ ↔ s = ∅ :=
⟨take h, principal_eq_iff_eq.mp $ by simp [principal_empty, h], take h, by simph [principal_empty]⟩
@[simp]
lemma mem_pure {a : α} {s : set α} : a ∈ s → s ∈ (pure a : filter α).sets :=
by simp; exact id
/- map equations -/
@[simp]
lemma mem_map {f : filter α} {s : set β} {m : α → β} :
(s ∈ (map m f)^.sets) = ({x | m x ∈ s} ∈ f^.sets) :=
rfl
lemma image_mem_map {f : filter α} {m : α → β} {s : set α} (hs : s ∈ f.sets):
m '' s ∈ (map m f).sets :=
f.upwards_sets hs $ take x hx, ⟨x, hx, rfl⟩
@[simp]
lemma map_id {f : filter α} : filter.map id f = f :=
filter_eq $ rfl
@[simp]
lemma map_compose {γ : Type w} {f : α → β} {g : β → γ} :
filter.map g ∘ filter.map f = filter.map (g ∘ f) :=
funext $ take _, filter_eq $ rfl
@[simp]
lemma map_sup {f g : filter α} {m : α → β} : map m (f ⊔ g) = map m f ⊔ map m g :=
filter_eq $ set.ext $ take x, by simp
@[simp]
lemma supr_map {ι : Sort w} {f : ι → filter α} {m : α → β} : (⨆x, map m (f x)) = map m (⨆x, f x) :=
filter_eq $ set.ext $ take x, by simp [supr_sets_eq, map]
@[simp]
lemma map_bot {m : α → β} : map m ⊥ = ⊥ :=
filter_eq $ set.ext $ take x, by simp
@[simp]
lemma map_eq_bot_iff {f : filter α} {m : α → β} : map m f = ⊥ ↔ f = ⊥ :=
⟨by rw [-empty_in_sets_eq_bot, -empty_in_sets_eq_bot]; exact id,
take h, by simph⟩
lemma map_mono {f g : filter α} {m : α → β} (h : f ≤ g) : map m f ≤ map m g :=
le_of_sup_eq $ calc
map m f ⊔ map m g = map m (f ⊔ g) : map_sup
... = map m g : congr_arg (map m) $ sup_of_le_right h
lemma monotone_map {m : α → β} : monotone (map m : filter α → filter β) :=
take a b h, map_mono h
-- this is a generic rule for monotone functions:
lemma map_infi_le {f : ι → filter α} {m : α → β} :
map m (infi f) ≤ (⨅ i, map m (f i)) :=
le_infi $ take i, map_mono $ infi_le _ _
lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≤) f) (hι : nonempty ι) :
map m (infi f) = (⨅ i, map m (f i)) :=
le_antisymm
map_infi_le
(take s (hs : vimage m s ∈ (infi f).sets),
have ∃i, vimage m s ∈ (f i).sets,
by simp [infi_sets_eq hf hι] at hs; assumption,
let ⟨i, hi⟩ := this in
have (⨅ i, map m (f i)) ≤ principal s,
from infi_le_of_le i $ by simp; assumption,
by simp at this; assumption)
lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {s : set ι}
(h : directed_on (λx y, f x ≤ f y) s) (ne : ∃i, i ∈ s) : map m (⨅i∈s, f i) = (⨅i∈s, map m (f i)) :=
let ⟨i, hi⟩ := ne in
calc map m (⨅i∈s, f i) = map m (⨅i:{i // i ∈ s}, f i.val) : by simp [infi_subtype]
... = (⨅i:{i // i ∈ s}, map m (f i.val)) : map_infi_eq
(take ⟨x, hx⟩ ⟨y, hy⟩, match h x hx y hy with ⟨z, h₁, h₂, h₃⟩ := ⟨⟨z, h₁⟩, h₂, h₃⟩ end)
⟨⟨i, hi⟩⟩
... = (⨅i∈s, map m (f i)) : by simp [infi_subtype]
/- bind equations -/
lemma mem_bind_sets {β : Type u} {s : set β} {f : filter α} {m : α → filter β} :
s ∈ (f >>= m)^.sets ↔ (∃t ∈ f^.sets, ∀x ∈ t, s ∈ (m x)^.sets) :=
calc s ∈ (f >>= m)^.sets ↔ {a | s ∈ (m a)^.sets} ∈ f^.sets : by simp
... ↔ (∃t ∈ f^.sets, t ⊆ {a | s ∈ (m a)^.sets}) : exists_sets_subset_iff^.symm
... ↔ (∃t ∈ f^.sets, ∀x ∈ t, s ∈ (m x)^.sets) : iff.refl _
lemma bind_mono {β : Type u} {f : filter α} {g h : α → filter β} (h₁ : {a | g a ≤ h a} ∈ f^.sets) :
f >>= g ≤ f >>= h :=
take x h₂, f^.upwards_sets (inter_mem_sets h₁ h₂) $ take s ⟨gh', h'⟩, gh' h'
lemma bind_sup {β : Type u} {f g : filter α} {h : α → filter β} :
(f ⊔ g) >>= h = (f >>= h) ⊔ (g >>= h) :=
by simp
lemma bind_mono2 {β : Type u} {f g : filter α} {h : α → filter β} (h₁ : f ≤ g) :
f >>= h ≤ g >>= h :=
take s h', h₁ h'
lemma principal_bind {β : Type u} {s : set α} {f : α → filter β} :
(principal s >>= f) = (⨆x ∈ s, f x) :=
show join (map f (principal s)) = (⨆x ∈ s, f x),
by simp [Sup_image]
lemma seq_mono {β : Type u} {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α}
(hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ <*> g₁ ≤ f₂ <*> g₂ :=
le_trans (bind_mono2 hf) (bind_mono $ univ_mem_sets' $ take f, map_mono hg)
@[simp]
lemma fmap_principal {β : Type u} {s : set α} {f : α → β} :
f <$> principal s = principal (set.image f s) :=
filter_eq $ set.ext $ take a, image_subset_iff_subset_vimage^.symm
lemma mem_return_sets {a : α} {s : set α} : s ∈ (return a : filter α)^.sets ↔ a ∈ s :=
show s ∈ (principal {a})^.sets ↔ a ∈ s,
by simp
lemma infi_neq_bot_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) (hb : ∀i, f i ≠ ⊥): (infi f) ≠ ⊥ :=
let ⟨x⟩ := hn in
take h, have he: ∅ ∈ (infi f)^.sets, from h.symm ▸ mem_bot_sets,
classical.by_cases
(suppose nonempty ι,
have ∃i, ∅ ∈ (f i).sets,
by rw [infi_sets_eq hd this] at he; simp at he; assumption,
let ⟨i, hi⟩ := this in
hb i $ bot_unique $
take s _, (f i)^.upwards_sets hi $ empty_subset _)
(suppose ¬ nonempty ι,
have univ ⊆ (∅ : set α),
begin
rw [-principal_mono, principal_univ, principal_empty, -h],
exact (le_infi $ take i, false.elim $ this ⟨i⟩)
end,
this $ mem_univ x)
lemma infi_neq_bot_iff_of_directed {f : ι → filter α}
(hn : nonempty α) (hd : directed (≤) f) : (infi f) ≠ ⊥ ↔ (∀i, f i ≠ ⊥) :=
⟨take neq_bot i eq_bot, neq_bot $ bot_unique $ infi_le_of_le i $ eq_bot ▸ le_refl _,
infi_neq_bot_of_directed hn hd⟩
@[simp] lemma return_neq_bot {α : Type u} {a : α} : return a ≠ (⊥ : filter α) :=
by simp [return]
section vmap
variables {f f₁ f₂ : filter β} {m : α → β}
lemma mem_vmap_of_mem {s : set β} (h : s ∈ f.sets) : vimage m s ∈ (vmap m f).sets :=
⟨s, h, subset.refl _⟩
lemma vmap_mono (h : f₁ ≤ f₂) : vmap m f₁ ≤ vmap m f₂ :=
take s ⟨t, ht, h_sub⟩, ⟨t, h ht, h_sub⟩
lemma monotone_vmap : monotone (vmap m : filter β → filter α) :=
take a b h, vmap_mono h
@[simp]
lemma vmap_principal {t : set β} : vmap m (principal t) = principal (vimage m t) :=
filter_eq $ set.ext $ take s,
⟨take ⟨u, (hu : t ⊆ u), (b : vimage m u ⊆ s)⟩, subset.trans (vimage_mono hu) b,
suppose vimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩
lemma vimage_mem_vmap {f : filter β} {m : α → β} {s : set β} (hs : s ∈ f.sets):
vimage m s ∈ (vmap m f).sets :=
⟨s, hs, subset.refl _⟩
lemma le_map_vmap {f : filter β} {m : α → β} (hm : ∀x, ∃y, m y = x) :
f ≤ map m (vmap m f) :=
take s ⟨t, ht, (sub : ∀x, m x ∈ t → m x ∈ s)⟩,
f.upwards_sets ht $
take x, let ⟨y, (hy : m y = x)⟩ := hm x in
hy ▸ sub y
lemma vmap_map {f : filter α} {m : α → β} (h : ∀ x y, m x = m y → x = y) :
vmap m (map m f) = f :=
have ∀s, vimage m (image m s) = s,
from take s, vimage_image_eq h,
le_antisymm
(take s hs, ⟨
image m s,
f.upwards_sets hs $ by simp [this, subset.refl],
by simp [this, subset.refl]⟩)
(take s ⟨t, (h₁ : vimage m t ∈ f.sets), (h₂ : vimage m t ⊆ s)⟩,
f.upwards_sets h₁ h₂)
lemma vmap_neq_bot {f : filter β} {m : α → β}
(hm : ∀t∈f.sets, ∃a, m a ∈ t) : vmap m f ≠ ⊥ :=
forall_sets_neq_empty_iff_neq_bot.mp $ take s ⟨t, ht, t_s⟩,
let ⟨a, (ha : a ∈ vimage m t)⟩ := hm t ht in
neq_bot_of_le_neq_bot (ne_empty_of_mem ha) t_s
lemma vmap_neq_bot_of_surj {f : filter β} {m : α → β}
(hf : f ≠ ⊥) (hm : ∀b, ∃a, m a = b) : vmap m f ≠ ⊥ :=
vmap_neq_bot $ take t ht,
let
⟨b, (hx : b ∈ t)⟩ := inhabited_of_mem_sets hf ht,
⟨a, (ha : m a = b)⟩ := hm b
in ⟨a, ha.symm ▸ hx⟩
lemma map_vmap_le {f : filter β} {m : α → β} : map m (vmap m f) ≤ f :=
take s hs, ⟨s, hs, subset.refl _⟩
lemma le_vmap_map {f : filter α} {m : α → β} : f ≤ vmap m (map m f) :=
take s ⟨t, ht, h_eq⟩, f.upwards_sets ht h_eq
lemma vmap_vmap_comp {f : filter α} {m : γ → β} {n : β → α} :
vmap m (vmap n f) = vmap (n ∘ m) f :=
le_antisymm
(take c ⟨b, hb, (h : vimage (n ∘ m) b ⊆ c)⟩, ⟨vimage n b, vimage_mem_vmap hb, h⟩)
(take c ⟨b, ⟨a, ha, (h₁ : vimage n a ⊆ b)⟩, (h₂ : vimage m b ⊆ c)⟩,
⟨a, ha, show vimage m (vimage n a) ⊆ c, from subset.trans (vimage_mono h₁) h₂⟩)
lemma le_vmap_iff_map_le {f : filter α} {g : filter β} {m : α → β} :
f ≤ vmap m g ↔ map m f ≤ g :=
⟨take h, le_trans (map_mono h) map_vmap_le,
take h, le_trans le_vmap_map (vmap_mono h)⟩
end vmap
section lift
protected def lift (f : filter α) (g : set α → filter β) :=
(⨅s ∈ f^.sets, g s)
section
variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β}
lemma lift_sets_eq (hg : monotone g) : (f^.lift g)^.sets = (⋃t∈f^.sets, (g t)^.sets) :=
infi_sets_eq'
(take s hs t ht, ⟨s ∩ t, inter_mem_sets hs ht,
hg $ inter_subset_left s t, hg $ inter_subset_right s t⟩)
⟨univ, univ_mem_sets⟩
lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f^.sets) (hs : s ∈ (g t)^.sets) :
s ∈ (f^.lift g)^.sets :=
le_principal_iff.mp $ show f^.lift g ≤ principal s,
from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs
lemma mem_lift_iff (hg : monotone g) {s : set β} :
s ∈ (f^.lift g)^.sets ↔ (∃t∈f^.sets, s ∈ (g t)^.sets) :=
by rw [lift_sets_eq hg]; simp
lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁^.lift g₁ ≤ f₂^.lift g₂ :=
infi_le_infi $ take s, infi_le_infi2 $ take hs, ⟨hf hs, hg s⟩
lemma lift_mono' (hg : ∀s∈f^.sets, g₁ s ≤ g₂ s) : f^.lift g₁ ≤ f^.lift g₂ :=
infi_le_infi $ take s, infi_le_infi $ take hs, hg s hs
lemma map_lift_eq {m : β → γ} (hg : monotone g) :
map m (f^.lift g) = f^.lift (map m ∘ g) :=
have monotone (map m ∘ g),
from monotone_comp hg monotone_map,
filter_eq $ set.ext $
by simp [mem_lift_iff, hg, @mem_lift_iff _ _ f _ this]
lemma vmap_lift_eq {m : γ → β} (hg : monotone g) :
vmap m (f^.lift g) = f^.lift (vmap m ∘ g) :=
have monotone (vmap m ∘ g),
from monotone_comp hg monotone_vmap,
filter_eq $ set.ext $
begin
simp [vmap, mem_lift_iff, hg, @mem_lift_iff _ _ f _ this],
simp [vmap, function.comp],
exact take s, ⟨take ⟨t₁, hs, t₂, ht, ht₁⟩, ⟨t₂, ht, t₁, hs, ht₁⟩,
take ⟨t₂, ht, t₁, hs, ht₁⟩, ⟨t₁, hs, t₂, ht, ht₁⟩⟩
end
lemma vmap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) :
(vmap m f)^.lift g = f^.lift (g ∘ vimage m) :=
le_antisymm
(le_infi $ take s, le_infi $ take hs,
infi_le_of_le (vimage m s) $ infi_le _ ⟨s, hs, subset.refl _⟩)
(le_infi $ take s, le_infi $ take ⟨s', hs', (h_sub : vimage m s' ⊆ s)⟩,
infi_le_of_le s' $ infi_le_of_le hs' $ hg h_sub)
lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) :
(map m f)^.lift g = f^.lift (g ∘ image m) :=
le_antisymm
(infi_le_infi2 $ take s, ⟨image m s,
infi_le_infi2 $ take hs, ⟨
f^.upwards_sets hs $ take a h, mem_image_of_mem _ h,
le_refl _⟩⟩)
(infi_le_infi2 $ take t, ⟨vimage m t,
infi_le_infi2 $ take ht, ⟨ht,
hg $ take x, assume h : x ∈ m '' vimage m t,
let ⟨y, hy, h_eq⟩ := h in
show x ∈ t, from h_eq ▸ hy⟩⟩)
lemma lift_comm {g : filter β} {h : set α → set β → filter γ} :
f^.lift (λs, g^.lift (h s)) = g^.lift (λt, f^.lift (λs, h s t)) :=
le_antisymm
(le_infi $ take i, le_infi $ take hi, le_infi $ take j, le_infi $ take hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
(le_infi $ take i, le_infi $ take hi, le_infi $ take j, le_infi $ take hj,
infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi)
lemma lift_assoc {h : set β → filter γ} (hg : monotone g) :
(f^.lift g)^.lift h = f^.lift (λs, (g s)^.lift h) :=
le_antisymm
(le_infi $ take s, le_infi $ take hs, le_infi $ take t, le_infi $ take ht,
infi_le_of_le t $ infi_le _ $ (mem_lift_iff hg)^.mpr ⟨_, hs, ht⟩)
(le_infi $ take t, le_infi $ take ht,
let ⟨s, hs, h'⟩ := (mem_lift_iff hg)^.mp ht in
infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h')
lemma lift_lift_same_le_lift {g : set α → set α → filter β} :
f^.lift (λs, f^.lift (g s)) ≤ f^.lift (λs, g s s) :=
le_infi $ take s, le_infi $ take hs, infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le s $ infi_le _ hs
lemma lift_lift_same_eq_lift {g : set α → set α → filter β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f^.lift (λs, f^.lift (g s)) = f^.lift (λs, g s s) :=
le_antisymm
lift_lift_same_le_lift
(le_infi $ take s, le_infi $ take hs, le_infi $ take t, le_infi $ take ht,
infi_le_of_le (s ∩ t) $
infi_le_of_le (inter_mem_sets hs ht) $
calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _)
... ≤ g s t : hg₁ s (inter_subset_right _ _))
lemma lift_principal {s : set α} (hg : monotone g) :
(principal s)^.lift g = g s :=
le_antisymm
(infi_le_of_le s $ infi_le _ $ subset.refl _)
(le_infi $ take t, le_infi $ take hi, hg hi)
lemma monotone_lift [weak_order γ] {f : γ → filter α} {g : γ → set α → filter β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c)^.lift (g c)) :=
take a b h, lift_mono (hf h) (hg h)
lemma lift_neq_bot_iff (hm : monotone g) : (f^.lift g ≠ ⊥) ↔ (∀s∈f.sets, g s ≠ ⊥) :=
classical.by_cases
(assume hn : nonempty β,
calc f^.lift g ≠ ⊥ ↔ (⨅s : { s // s ∈ f^.sets}, g s.val) ≠ ⊥ : by simp [filter.lift, infi_subtype]
... ↔ (∀s:{ s // s ∈ f^.sets}, g s.val ≠ ⊥) :
infi_neq_bot_iff_of_directed hn
(take ⟨a, ha⟩ ⟨b, hb⟩, ⟨⟨a ∩ b, inter_mem_sets ha hb⟩,
hm $ inter_subset_left _ _, hm $ inter_subset_right _ _⟩)
... ↔ (∀s∈f.sets, g s ≠ ⊥) : ⟨take h s hs, h ⟨s, hs⟩, take h ⟨s, hs⟩, h s hs⟩)
(assume hn : ¬ nonempty β,
have h₁ : f.lift g = ⊥, from filter_eq_bot_of_not_nonempty hn,
have h₂ : ∀s, g s = ⊥, from take s, filter_eq_bot_of_not_nonempty hn,
calc (f.lift g ≠ ⊥) ↔ false : by simp [h₁]
... ↔ (∀s∈f.sets, false) : ⟨false.elim, take h, h univ univ_mem_sets⟩
... ↔ (∀s∈f.sets, g s ≠ ⊥) : by simp [h₂])
end
section
protected def lift' (f : filter α) (h : set α → set β) :=
f^.lift (principal ∘ h)
variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β}
lemma mem_lift' {t : set α} (ht : t ∈ f^.sets) : h t ∈ (f^.lift' h)^.sets :=
le_principal_iff.mp $ show f^.lift' h ≤ principal (h t),
from infi_le_of_le t $ infi_le_of_le ht $ le_refl _
lemma mem_lift'_iff (hh : monotone h) {s : set β} : s ∈ (f^.lift' h)^.sets ↔ (∃t∈f^.sets, h t ⊆ s) :=
have monotone (principal ∘ h),
from take a b h, principal_mono.mpr $ hh h,
by simp [filter.lift', @mem_lift_iff α β f _ this]
lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁^.lift' h₁ ≤ f₂^.lift' h₂ :=
lift_mono hf $ take s, principal_mono.mpr $ hh s
lemma lift'_mono' (hh : ∀s∈f^.sets, h₁ s ⊆ h₂ s) : f^.lift' h₁ ≤ f^.lift' h₂ :=
infi_le_infi $ take s, infi_le_infi $ take hs, principal_mono.mpr $ hh s hs
lemma lift'_cong (hh : ∀s∈f^.sets, h₁ s = h₂ s) : f^.lift' h₁ = f^.lift' h₂ :=
le_antisymm (lift'_mono' $ take s hs, le_of_eq $ hh s hs) (lift'_mono' $ take s hs, le_of_eq $ (hh s hs).symm)
lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f^.lift' h) = f^.lift' (image m ∘ h) :=
calc map m (f^.lift' h) = f^.lift (map m ∘ principal ∘ h) :
map_lift_eq $ monotone_comp hh monotone_principal
... = f^.lift' (image m ∘ h) : by simp [function.comp, filter.lift']
lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) :
(map m f)^.lift' g = f^.lift' (g ∘ image m) :=
map_lift_eq2 $ monotone_comp hg monotone_principal
lemma vmap_lift'_eq {m : γ → β} (hh : monotone h) :
vmap m (f^.lift' h) = f^.lift' (vimage m ∘ h) :=
calc vmap m (f^.lift' h) = f^.lift (vmap m ∘ principal ∘ h) :
vmap_lift_eq $ monotone_comp hh monotone_principal
... = f^.lift' (vimage m ∘ h) : by simp [function.comp, filter.lift']
lemma vmap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) :
(vmap m f)^.lift' g = f^.lift' (g ∘ vimage m) :=
vmap_lift_eq2 $ monotone_comp hg monotone_principal
lemma lift'_principal {s : set α} (hh : monotone h) :
(principal s)^.lift' h = principal (h s) :=
lift_principal $ monotone_comp hh monotone_principal
lemma principal_le_lift' {t : set β} (hh : ∀s∈f^.sets, t ⊆ h s) :
principal t ≤ f^.lift' h :=
le_infi $ take s, le_infi $ take hs, principal_mono^.mpr (hh s hs)
lemma monotone_lift' [weak_order γ] {f : γ → filter α} {g : γ → set α → set β}
(hf : monotone f) (hg : monotone g) : monotone (λc, (f c)^.lift' (g c)) :=
take a b h, lift'_mono (hf h) (hg h)
lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ}
(hg : monotone g) (hh : monotone h) :
(f^.lift' g)^.lift h = f^.lift (λs, h (g s)) :=
calc (f^.lift' g)^.lift h = f^.lift (λs, (principal (g s))^.lift h) :
lift_assoc (monotone_comp hg monotone_principal)
... = f^.lift (λs, h (g s)) : by simp [lift_principal, hh]
lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ}
(hg : monotone g) (hh : monotone h) :
(f^.lift' g)^.lift' h = f^.lift' (λs, h (g s)) :=
lift_lift'_assoc hg (monotone_comp hh monotone_principal)
lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ}
(hg : monotone g) : (f^.lift g)^.lift' h = f^.lift (λs, (g s)^.lift' h) :=
lift_assoc hg
lemma lift_lift'_same_le_lift' {g : set α → set α → set β} :
f^.lift (λs, f^.lift' (g s)) ≤ f^.lift' (λs, g s s) :=
lift_lift_same_le_lift
lemma lift_lift'_same_eq_lift' {g : set α → set α → set β}
(hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)):
f^.lift (λs, f^.lift' (g s)) = f^.lift' (λs, g s s) :=
lift_lift_same_eq_lift
(take s, monotone_comp monotone_id $ monotone_comp (hg₁ s) monotone_principal)
(take t, monotone_comp (hg₂ t) monotone_principal)
lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} :
f^.lift' h ⊓ principal s = f^.lift' (λt, h t ∩ s) :=
le_antisymm
(le_infi $ take t, le_infi $ take ht,
calc filter.lift' f h ⊓ principal s ≤ principal (h t) ⊓ principal s :
inf_le_inf (infi_le_of_le t $ infi_le _ ht) (le_refl _)
... = _ : by simp)
(le_inf
(le_infi $ take t, le_infi $ take ht,
infi_le_of_le t $ infi_le_of_le ht $ by simp; exact inter_subset_right _ _)
(infi_le_of_le univ $ infi_le_of_le univ_mem_sets $ by simp; exact inter_subset_left _ _))
lemma lift'_neq_bot_iff (hh : monotone h) : (f^.lift' h ≠ ⊥) ↔ (∀s∈f.sets, h s ≠ ∅) :=
calc (f^.lift' h ≠ ⊥) ↔ (∀s∈f.sets, principal (h s) ≠ ⊥) :
lift_neq_bot_iff (monotone_comp hh monotone_principal)
... ↔ (∀s∈f.sets, h s ≠ ∅) : by simp [principal_eq_bot_iff]
@[simp]
lemma lift'_id {f : filter α} : f.lift' id = f :=
le_antisymm
(take s hs, mem_lift' hs)
(le_infi $ take s, le_infi $ take hs, by simp [hs])
lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β}
(h_le : ∀s∈f.sets, h s ∈ g.sets) : g ≤ f.lift' h :=
le_infi $ take s, le_infi $ take hs, by simp [h_le]; exact h_le s hs
end
end lift
lemma vmap_eq_lift' {f : filter β} {m : α → β} :
vmap m f = f.lift' (vimage m) :=
filter_eq $ set.ext $ by simp [mem_lift'_iff, monotone_vimage, vmap]
/- product filter -/
/- The product filter cannot be defined using the monad structure on filters. For example:
F := do {x <- seq, y <- top, return (x, y)}
hence:
s ∈ F <-> ∃n, [n..∞] × univ ⊆ s
G := do {y <- top, x <- seq, return (x, y)}
hence:
s ∈ G <-> ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s
Now ⋃i, [i..∞] × {i} is in G but not in F.
As product filter we want to have F as result.
-/
section prod
protected def prod (f : filter α) (g : filter β) : filter (α × β) :=
f^.lift $ λs, g^.lift' $ λt, set.prod s t
lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β}
(hs : s ∈ f^.sets) (ht : t ∈ g^.sets) : set.prod s t ∈ (filter.prod f g)^.sets :=
le_principal_iff^.mp $ show filter.prod f g ≤ principal (set.prod s t),
from infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ ht
lemma prod_same_eq {f : filter α} : filter.prod f f = f^.lift' (λt, set.prod t t) :=
lift_lift'_same_eq_lift'
(take s, set.monotone_prod monotone_const monotone_id)
(take t, set.monotone_prod monotone_id monotone_const)
lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} :
s ∈ (filter.prod f g)^.sets ↔ (∃t₁∈f^.sets, ∃t₂∈g^.sets, set.prod t₁ t₂ ⊆ s) :=
begin
delta filter.prod,
rw [mem_lift_iff],
apply exists_congr, intro t₁,
apply exists_congr, intro ht₁,
rw [mem_lift'_iff],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $ take b, set.monotone_prod monotone_id monotone_const)
end
lemma mem_prod_same_iff {s : set (α×α)} {f : filter α} :
s ∈ (filter.prod f f)^.sets ↔ (∃t∈f^.sets, set.prod t t ⊆ s) :=
by rw [prod_same_eq, mem_lift'_iff]; exact set.monotone_prod monotone_id monotone_id
lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) :
filter.prod f₁ g₁ ≤ filter.prod f₂ g₂ :=
lift_mono hf $ take s, lift'_mono hg $ le_refl _
lemma prod_comm {f : filter α} {g : filter β} :
filter.prod f g = map (λp:β×α, (p.2, p.1)) (filter.prod g f) :=
eq.symm $ calc map (λp:β×α, (p.2, p.1)) (filter.prod g f) =
(g^.lift $ λt, map (λp:β×α, (p.2, p.1)) (f^.lift' $ λs, set.prod t s)) :
map_lift_eq $ take a b h, lift'_mono (le_refl f) (take t, set.prod_mono h (subset.refl t))
... = (g^.lift $ λt, f^.lift' $ λs, image (λp:β×α, (p.2, p.1)) (set.prod t s)) :
congr_arg (filter.lift g) $ funext $ take s, map_lift'_eq $ take a b h, set.prod_mono (subset.refl s) h
... = (g^.lift $ λt, f^.lift' $ λs, set.prod s t) : by simp [set.image_swap_prod]
... = filter.prod f g : lift_comm
lemma prod_lift_lift {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift g₁) (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, filter.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_assoc],
apply congr_arg, apply funext, intro x,
rw [lift_comm],
apply congr_arg, apply funext, intro y,
rw [lift'_lift_assoc],
exact hg₂,
exact hg₁
end
lemma prod_lift'_lift' {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂}
(hg₁ : monotone g₁) (hg₂ : monotone g₂) :
filter.prod (f₁.lift' g₁) (f₂.lift' g₂) = f₁.lift (λs, f₂.lift' (λt, set.prod (g₁ s) (g₂ t))) :=
begin
delta filter.prod,
rw [lift_lift'_assoc],
apply congr_arg, apply funext, intro x,
rw [lift'_lift'_assoc],
exact hg₂,
exact set.monotone_prod monotone_const monotone_id,
exact hg₁,
exact (monotone_lift' monotone_const $ monotone_lam $
take x, set.monotone_prod monotone_id monotone_const)
end
lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} :
filter.prod (map m₁ f₁) (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
begin
simp [filter.prod],
rw [map_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $
monotone_lam $ take t, set.monotone_prod monotone_id monotone_const),
rw [map_lift_eq2], tactic.swap, exact (monotone_lift' monotone_const $
monotone_lam $ take t, set.monotone_prod monotone_id monotone_const),
apply congr_arg, apply funext, intro t,
dsimp,
rw [map_lift'_eq], tactic.swap, exact set.monotone_prod monotone_const monotone_id,
rw [map_lift'_eq2], tactic.swap, exact set.monotone_prod monotone_const monotone_id,
apply congr_arg, apply funext, intro t,
exact set.prod_image_image_eq
end
lemma prod_vmap_vmap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x}
{f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} :
filter.prod (vmap m₁ f₁) (vmap m₂ f₂) = vmap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (filter.prod f₁ f₂) :=
have ∀s t, set.prod (vimage m₁ s) (vimage m₂ t) = vimage (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (set.prod s t),
from take s t, rfl,
begin
rw [vmap_eq_lift', vmap_eq_lift', prod_lift'_lift'],
simp [this, filter.prod],
rw [vmap_lift_eq], tactic.swap, exact (monotone_lift' monotone_const $
monotone_lam $ take t, set.monotone_prod monotone_id monotone_const),
apply congr_arg, apply funext, intro t',
dsimp [function.comp],
rw [vmap_lift'_eq],
exact set.monotone_prod monotone_const monotone_id,
exact monotone_vimage,
exact monotone_vimage
end
lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} :
filter.prod f₁ g₁ ⊓ filter.prod f₂ g₂ = filter.prod (f₁ ⊓ f₂) (g₁ ⊓ g₂) :=
le_antisymm
(le_infi $ take s, le_infi $ take hs, le_infi $ take t, le_infi $ take ht,
begin
revert s hs t ht,
simp,
exact take s ⟨s₁, hs₁, s₂, hs₂, hs⟩ t ⟨t₁, ht₁, t₂, ht₂, ht⟩,
⟨set.prod s₁ t₁, prod_mem_prod hs₁ ht₁, set.prod s₂ t₂, prod_mem_prod hs₂ ht₂,
by rw [set.prod_inter_prod]; exact set.prod_mono hs ht⟩
end)
(le_inf (prod_mono inf_le_left inf_le_left) (prod_mono inf_le_right inf_le_right))
lemma prod_neq_bot {f : filter α} {g : filter β} :
filter.prod f g ≠ ⊥ ↔ (f ≠ ⊥ ∧ g ≠ ⊥) :=
calc filter.prod f g ≠ ⊥ ↔ (∀s∈f.sets, g.lift' (set.prod s) ≠ ⊥) :
begin
delta filter.prod,
rw [lift_neq_bot_iff],
exact (monotone_lift' monotone_const $ monotone_lam $ take s, set.monotone_prod monotone_id monotone_const)
end
... ↔ (∀s∈f.sets, ∀t∈g.sets, s ≠ ∅ ∧ t ≠ ∅) :
begin
apply forall_congr, intro s,
apply forall_congr, intro hs,
rw [lift'_neq_bot_iff],
apply forall_congr, intro t,
apply forall_congr, intro ht,
rw [set.prod_neq_empty_iff],
exact set.monotone_prod monotone_const monotone_id
end
... ↔ (∀s∈f.sets, s ≠ ∅) ∧ (∀t∈g.sets, t ≠ ∅) :
⟨take h, ⟨take s hs, (h s hs univ univ_mem_sets).left,
take t ht, (h univ univ_mem_sets t ht).right⟩,
take ⟨h₁, h₂⟩ s hs t ht, ⟨h₁ s hs, h₂ t ht⟩⟩
... ↔ _ : by simp [forall_sets_neq_empty_iff_neq_bot]
lemma prod_principal_principal {s : set α} {t : set β} :
filter.prod (principal s) (principal t) = principal (set.prod s t) :=
begin
delta filter.prod,
rw [lift_principal, lift'_principal],
exact set.monotone_prod monotone_const monotone_id,
exact (monotone_lift' monotone_const $ monotone_lam $
take s, set.monotone_prod monotone_id monotone_const)
end
end prod
lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ (f i).sets → s ∈ (⨅i, f i).sets :=
show (⨅i, f i) ≤ f i, from infi_le _ _
@[simp]
lemma mem_top_sets_iff {s : set α} : s ∈ (⊤ : filter α).sets ↔ s = univ :=
⟨take h, top_unique $ h, take h, h.symm ▸ univ_mem_sets⟩
@[elab_as_eliminator]
lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ (infi f).sets) {p : set α → Prop}
(uni : p univ)
(ins : ∀{i s₁ s₂}, s₁ ∈ (f i).sets → p s₂ → p (s₁ ∩ s₂))
(upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s :=
begin
note hs' : s ∈ (complete_lattice.Inf {a : filter α | ∃ (i : ι), a = f i}).sets := hs,
rw [Inf_sets_eq_finite] at hs',
simp at hs',
cases hs' with is hs, cases hs with fin_is hs, cases hs with hs his,
induction fin_is generalizing s,
case finite.empty hs' s hs' hs {
simp at hs, subst hs, assumption },
case finite.insert fi is fi_ne_is fin_is ih fi_sub s hs' hs {
simp at hs,
cases hs with s₁ hs, cases hs with hs₁ hs, cases hs with s₂ hs, cases hs with hs hs₂,
note hi : ∃i, fi = f i := fi_sub (mem_insert _ _),
cases hi with i hi,
have hs₁ : s₁ ∈ (f i).sets, from hi ▸ hs₁,
have hs₂ : p s₂, from
have his : is ⊆ {x | ∃i, x = f i}, from take i hi, fi_sub $ mem_insert_of_mem _ hi,
have infi f ≤ Inf is, from Inf_le_Inf his,
ih his (this hs₂) hs₂,
show p s, from upw hs $ ins hs₁ hs₂ }
end
lemma lift_infi {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hg : ∀{s t}, g s ⊓ g t = g (s ∩ t)) : (infi f)^.lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ take i, lift_mono (infi_le _ _) (le_refl _))
(take s,
have g_mono : monotone g,
from take s t h, le_of_inf_eq $ eq.trans hg $ congr_arg g $ inter_eq_self_of_subset_left h,
have ∀t∈(infi f).sets, (⨅ (i : ι), filter.lift (f i) g) ≤ g t,
from take t ht, infi_sets_induct ht
(let ⟨i⟩ := hι in infi_le_of_le i $ infi_le_of_le univ $ infi_le _ univ_mem_sets)
(take i s₁ s₂ hs₁ hs₂,
@hg s₁ s₂ ▸ le_inf (infi_le_of_le i $ infi_le_of_le s₁ $ infi_le _ hs₁) hs₂)
(take s₁ s₂ hs₁ hs₂, le_trans hs₂ $ g_mono hs₁),
by rw [lift_sets_eq g_mono]; simp; exact take ⟨t, hs, ht⟩, this t ht hs)
lemma lift_infi' {f : ι → filter α} {g : set α → filter β}
(hι : nonempty ι) (hf : directed (≤) f) (hg : monotone g) : (infi f)^.lift g = (⨅i, (f i).lift g) :=
le_antisymm
(le_infi $ take i, lift_mono (infi_le _ _) (le_refl _))
(take s,
begin
rw [lift_sets_eq hg],
simp [infi_sets_eq hf hι],
exact take ⟨t, hs, i, ht⟩, mem_infi_sets i $ mem_lift ht hs
end)
lemma lift'_infi {f : ι → filter α} {g : set α → set β}
(hι : nonempty ι) (hg : ∀{s t}, g s ∩ g t = g (s ∩ t)) : (infi f)^.lift' g = (⨅i, (f i).lift' g) :=
lift_infi hι $ by simp; apply take s t, hg
lemma map_eq_vmap_of_inverse {f : filter α} {m : α → β} {n : β → α}
(h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = vmap n f :=
le_antisymm
(take b ⟨a, ha, (h : vimage n a ⊆ b)⟩, f.upwards_sets ha $
calc a = vimage (n ∘ m) a : by simp [h₂, vimage_id]
... ⊆ vimage m b : vimage_mono h)
(take b (hb : vimage m b ∈ f.sets),
⟨vimage m b, hb, show vimage (m ∘ n) b ⊆ b, by simp [h₁]; apply subset.refl⟩)
lemma map_swap_vmap_swap_eq {f : filter (α × β)} : prod.swap <$> f = vmap prod.swap f :=
map_eq_vmap_of_inverse prod.swap_swap_eq prod.swap_swap_eq
/- towards -/
def towards (f : α → β) (l₁ : filter α) (l₂ : filter β) := filter.map f l₁ ≤ l₂
/- ultrafilter -/
section ultrafilter
open classical zorn
local attribute [instance] prop_decidable
variables {f g : filter α}
def ultrafilter (f : filter α) := f ≠ ⊥ ∧ ∀g, g ≠ ⊥ → g ≤ f → f ≤ g
lemma ultrafilter_pure {a : α} : ultrafilter (pure a) :=
⟨return_neq_bot,
take g hg ha,
have {a} ∈ g.sets, by simp at ha; assumption,
show ∀s∈g.sets, {a} ⊆ s, from classical.by_contradiction $
begin
simp [classical.not_forall_iff_exists_not, classical.not_implies_iff_and_not],
exact take ⟨s, hna, hs⟩,
have {a} ∩ s ∈ g.sets, from inter_mem_sets ‹{a} ∈ g.sets› hs,
have ∅ ∈ g.sets, from g.upwards_sets this $
take x ⟨hxa, hxs⟩, begin simp at hxa; simp [hxa] at hxs, exact hna hxs end,
have g = ⊥, from empty_in_sets_eq_bot.mp this,
hg this
end⟩
lemma ultrafilter_unique (hg : ultrafilter g) (hf : f ≠ ⊥) (h : f ≤ g) : f = g :=
le_antisymm h (hg.right _ hf h)
lemma exists_ultrafilter (h : f ≠ ⊥) : ∃u, u ≤ f ∧ ultrafilter u :=
let
τ := {f' // f' ≠ ⊥ ∧ f' ≤ f},
r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val,
⟨a, ha⟩ := inhabited_of_mem_sets h univ_mem_sets,
top : τ := ⟨f, h, le_refl f⟩,
sup : Π(c:set τ), chain c → τ :=
λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.val.val,
infi_neq_bot_of_directed ⟨a⟩
(directed_of_chain $ chain_insert hc $ take ⟨b, _, hb⟩ _ _, or.inl hb)
(take ⟨⟨a, ha, _⟩, _⟩, ha),
infi_le_of_le ⟨top, mem_insert _ _⟩ (le_refl _)⟩
in
have ∀c (hc: chain c) a (ha : a ∈ c), r a (sup c hc),
from take c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ (le_refl _),
have (∃ (u : τ), ∀ (a : τ), r u a → r a u),
from zorn (take c hc, ⟨sup c hc, this c hc⟩) (take f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁),
let ⟨uτ, hmin⟩ := this in
⟨uτ.val, uτ.property.right, uτ.property.left, take g hg₁ hg₂,
hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩
lemma le_of_ultrafilter {g : filter α} (hf : ultrafilter f) (h : f ⊓ g ≠ ⊥) :
f ≤ g :=
le_of_inf_eq $ ultrafilter_unique hf h inf_le_left
lemma mem_or_compl_mem_of_ultrafilter (hf : ultrafilter f) (s : set α) :
s ∈ f.sets ∨ - s ∈ f.sets :=
or_of_not_implies $ suppose - s ∉ f.sets,
have f ≤ principal s,
from le_of_ultrafilter hf $ take h, this $ mem_sets_of_neq_bot $ by simph,
by simp at this; assumption
lemma mem_or_mem_of_ultrafilter {s t : set α} (hf : ultrafilter f) (h : s ∪ t ∈ f.sets) :
s ∈ f.sets ∨ t ∈ f.sets :=
(mem_or_compl_mem_of_ultrafilter hf s).imp_right
(suppose -s ∈ f.sets, f.upwards_sets (inter_mem_sets this h) $
take x ⟨hnx, hx⟩, hx.resolve_left hnx)
lemma mem_of_finite_sUnion_ultrafilter {s : set (set α)} (hf : ultrafilter f) (hs : finite s)
: ⋃₀ s ∈ f.sets → ∃t∈s, t ∈ f.sets :=
begin
induction hs,
case finite.empty { simp [empty_in_sets_eq_bot, hf.left] },
case finite.insert t s' ht' hs' ih {
simp,
exact take h, (mem_or_mem_of_ultrafilter hf h).elim
(suppose t ∈ f.sets, ⟨t, this, or.inl rfl⟩)
(take h, let ⟨t, hts', ht⟩ := ih h in ⟨t, ht, or.inr hts'⟩) }
end
lemma mem_of_finite_Union_ultrafilter {is : set β} {s : β → set α}
(hf : ultrafilter f) (his : finite is) (h : (⋃i∈is, s i) ∈ f.sets) : ∃i∈is, s i ∈ f.sets :=
have his : finite (image s is), from finite_image his,
have h : (⋃₀ image s is) ∈ f.sets, from by simp [sUnion_image]; assumption,
let ⟨t, ⟨i, hi, h_eq⟩, (ht : t ∈ f.sets)⟩ := mem_of_finite_sUnion_ultrafilter hf his h in
⟨i, hi, h_eq.symm ▸ ht⟩
lemma ultrafilter_of_split {f : filter α} (hf : f ≠ ⊥) (h : ∀s, s ∈ f.sets ∨ - s ∈ f.sets) :
ultrafilter f :=
⟨hf, take g hg g_le s hs, (h s).elim id $
suppose - s ∈ f.sets,
have s ∩ -s ∈ g.sets, from inter_mem_sets hs (g_le this),
by simp [empty_in_sets_eq_bot, hg] at this; contradiction⟩
lemma ultrafilter_map {f : filter α} {m : α → β} (h : ultrafilter f) : ultrafilter (map m f) :=
ultrafilter_of_split (by simp [map_eq_bot_iff, h.left]) $
take s, show vimage m s ∈ f.sets ∨ - vimage m s ∈ f.sets,
from mem_or_compl_mem_of_ultrafilter h (vimage m s)
noncomputable def ultrafilter_of (f : filter α) : filter α :=
if h : f = ⊥ then ⊥ else epsilon (λu, u ≤ f ∧ ultrafilter u)
lemma ultrafilter_of_spec (h : f ≠ ⊥) : ultrafilter_of f ≤ f ∧ ultrafilter (ultrafilter_of f) :=
begin
note h' := epsilon_spec (exists_ultrafilter h),
simp [ultrafilter_of, dif_neg, h],
simp at h',
assumption
end
lemma ultrafilter_of_le : ultrafilter_of f ≤ f :=
if h : f = ⊥ then by simp [ultrafilter_of, dif_pos, h]; exact le_refl _
else (ultrafilter_of_spec h).left
lemma ultrafilter_ultrafilter_of (h : f ≠ ⊥) : ultrafilter (ultrafilter_of f) :=
(ultrafilter_of_spec h).right
lemma ultrafilter_of_ultrafilter (h : ultrafilter f) : ultrafilter_of f = f :=
ultrafilter_unique h (ultrafilter_ultrafilter_of h.left).left ultrafilter_of_le
end ultrafilter
end filter
|
139c1ae11c29532db11d1905f0d00ac486161dac | c31182a012eec69da0a1f6c05f42b0f0717d212d | /src/normed_spectral.lean | a865d4ed49254595452c03576ccb8cf7523d29a5 | [] | no_license | Ja1941/lean-liquid | fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc | 8e80ed0cbdf5145d6814e833a674eaf05a1495c1 | refs/heads/master | 1,689,437,983,362 | 1,628,362,719,000 | 1,628,362,719,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,288 | lean | import system_of_complexes.double
import system_of_complexes.truncate
import normed_snake
import category_theory.concrete_category
import thm95.constants.spectral_constants
noncomputable theory
open_locale nnreal
open category_theory
universe variables u
namespace system_of_double_complexes
@[simps]
def truncate : system_of_double_complexes.{u} ⥤ system_of_double_complexes.{u} :=
(whiskering_right _ _ _).obj $
@functor.map_homological_complex _ _ _ _ _ _ _ _ SemiNormedGroup.truncate.additive.{u u} _
-- TODO: why do I need to give the instance manually? ↑ ↑ ↑
namespace truncate
variables (M : system_of_double_complexes.{u})
-- defeq abuse for the win!!!
lemma row (p : ℕ) :
(truncate.obj M).row p = system_of_complexes.truncate.obj (M.row p) := rfl
lemma col_pos (q : ℕ) :
(truncate.obj M).col (q+1) = M.col (q+1+1) :=
rfl
@[simp]
lemma d'_zero_one (c : ℝ≥0) (p : ℕ) (x : M.X c p 1) :
(truncate.obj M).d' 0 1 (SemiNormedGroup.coker.π x) = M.d' 1 2 x := rfl
@[simp]
lemma d_π (c : ℝ≥0) (p p' : ℕ) (x : M.X c p 1) :
@d (truncate.obj M) _ p p' 0 (SemiNormedGroup.coker.π x) = SemiNormedGroup.coker.π (M.d p p' x) := rfl
@[simp]
lemma res_π (c₁ c₂ : ℝ≥0) (p : ℕ) (h : fact (c₁ ≤ c₂)) (x : M.X c₂ p 1) :
@res (truncate.obj M) _ _ p 0 h (SemiNormedGroup.coker.π x) = SemiNormedGroup.coker.π (M.res x) := rfl
def quotient_map : M.col 1 ⟶ (truncate.obj M).col 0 :=
{ app := λ c,
{ f := λ p, SemiNormedGroup.coker.π,
comm' := λ p p' _, by { ext, refl } },
naturality' := by { intros, ext, refl } }
lemma admissible (hM : M.admissible) : (truncate.obj M).admissible :=
{ d_norm_noninc' := λ c p' p q h,
begin
cases q,
{ apply SemiNormedGroup.coker.lift_norm_noninc,
exact SemiNormedGroup.coker.π_norm_noninc.comp (hM.d_norm_noninc _ _ _ _) },
{ exact hM.d_norm_noninc c p' p _ }
end,
d'_norm_noninc' := λ c p,
((M.row p).truncate_admissible (hM.row p)).d_norm_noninc' c,
res_norm_noninc := λ c₁ c₂ p,
((M.row p).truncate_admissible (hM.row p)).res_norm_noninc c₁ c₂ }
end truncate
open opposite
structure normed_spectral_homotopy {row₀ row₁ : system_of_complexes.{u}} (d : row₀ ⟶ row₁)
(m : ℕ) (k' ε : ℝ≥0) [fact (1 ≤ k')] (c₀ H : ℝ≥0) [fact (0 < H)] :=
(h : Π (q : ℕ) {q' : ℕ} {c}, row₀ (k' * c) q' ⟶ row₁ c q)
(norm_h_le : ∀ (q q' : ℕ) (hq : q ≤ m) (hq' : q+1 = q') (c) [fact (c₀ ≤ c)],
∥(h q : row₀ (k' * c) q' ⟶ row₁ c q)∥ ≤ H)
(δ : Π (c : ℝ≥0), row₀.obj (op $ c) ⟶ row₁.obj (op $ k' * c))
(hδ : ∀ (c : ℝ≥0) [fact (c₀ ≤ c)] (q : ℕ) (hq : q ≤ m),
(system_of_complexes.res : row₀ (k' * (k' * c)) q ⟶ _) ≫ (δ c).f q =
d.apply ≫ system_of_complexes.res + row₀.d q (q+1) ≫ h q + h (q-1) ≫ row₁.d (q-1) q)
(norm_δ_le : ∀ (c : ℝ≥0) [fact (c₀ ≤ c)] (q : ℕ) (hq : q ≤ m), ∥(δ c).f q∥ ≤ ε)
.
lemma normed_spectral_homotopy.hδ_apply {row₀ row₁ : system_of_complexes.{u}} {d : row₀ ⟶ row₁}
{m : ℕ} {k' ε : ℝ≥0} [fact (1 ≤ k')] {c₀ H : ℝ≥0} [fact (0 < H)]
(NSH : normed_spectral_homotopy d m k' ε c₀ H)
(c : ℝ≥0) [fact (c₀ ≤ c)] (q : ℕ) (hq : q ≤ m) (x : row₀ (k' * (k' * c)) q) :
(NSH.δ c).f q (system_of_complexes.res x) =
system_of_complexes.res (d x) + NSH.h q (row₀.d q (q+1) x) + row₁.d (q-1) q (NSH.h (q-1) x) :=
begin
show ((system_of_complexes.res : row₀ (k' * (k' * c)) q ⟶ _) ≫ (NSH.δ c).f q) x = _,
rw NSH.hδ c q hq,
dsimp, refl
end
def normed_spectral_homotopy.of_iso {row₀ row₁ : system_of_complexes.{u}} {d : row₀ ⟶ row₁}
{m : ℕ} {k' ε : ℝ≥0} [fact (1 ≤ k')] {c₀ H : ℝ≥0} [fact (0 < H)]
(NSH : normed_spectral_homotopy d m k' ε c₀ H)
(row'₀ row'₁ : system_of_complexes.{u}) (d' : row'₀ ⟶ row'₁)
(φ₀ : row₀ ≅ row'₀) (φ₁ : row₁ ≅ row'₁)
(hφ₀ : ∀ c i (x : row'₀ c i), ∥φ₀.inv x∥ = ∥x∥)
(hφ₁ : ∀ c i (x : row₁ c i), ∥φ₁.hom x∥ = ∥x∥)
(hcomm : d' = φ₀.inv ≫ d ≫ φ₁.hom) :
normed_spectral_homotopy d' m k' ε c₀ H :=
{ h := λ q q' c, φ₀.inv.apply ≫ NSH.h q ≫ φ₁.hom.apply,
δ := λ c, φ₀.inv.app (op $ c) ≫ NSH.δ c ≫ φ₁.hom.app (op $ k' * c),
norm_h_le :=
begin
introsI q q' hqm hq' c hc,
refine normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg H) (λ x, _),
calc ∥φ₁.hom (NSH.h q (φ₀.inv x))∥
= ∥NSH.h q (φ₀.inv x)∥ : hφ₁ _ _ _
... ≤ ↑H * ∥φ₀.inv x∥ :
normed_group_hom.le_of_op_norm_le _ (NSH.norm_h_le _ _ hqm hq' _) (φ₀.inv x)
... = ↑H * ∥x∥ : congr_arg _ (hφ₀ _ _ _),
end,
hδ :=
begin
introsI c hc q hq,
ext1 x,
have := congr_arg (λ x, φ₁.hom x) (NSH.hδ_apply c q hq (φ₀.inv x)),
simp only [coe_comp, hcomm, system_of_complexes.res_apply, system_of_complexes.d_apply] at this ⊢,
refine this.trans _, clear this,
calc φ₁.hom (d (φ₀.inv (system_of_complexes.res x)) +
(NSH.h q) (φ₀.inv (row'₀.d q (q+1) x)) +
(row₁.d (q - 1) q) (NSH.h (q - 1) (φ₀.inv x)))
= φ₁.hom (d (φ₀.inv (system_of_complexes.res x)) +
(NSH.h q) (φ₀.inv (row'₀.d q (q+1) x))) +
φ₁.hom ((row₁.d (q - 1) q) (NSH.h (q - 1) (φ₀.inv x))) : _
... = _ : _,
{ apply normed_group_hom.map_add },
congr' 1,
{ refine (normed_group_hom.map_add _ _ _).trans _,
simp only [← comp_apply, ← system_of_complexes.res_comp_apply], refl },
{ erw [system_of_complexes.d_apply], refl }
end,
norm_δ_le := λ c hc q hq,
begin
resetI,
refine normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg ε) _,
rintro (x : row'₀ c q),
calc ∥φ₁.hom ((NSH.δ c).f q (φ₀.inv x))∥
= ∥(NSH.δ c).f q (φ₀.inv x)∥ : hφ₁ _ _ _
... ≤ ↑ε * ∥φ₀.inv x∥ : normed_group_hom.le_of_op_norm_le _ (NSH.norm_δ_le _ _ hq) (φ₀.inv x)
... = ↑ε * ∥x∥ : congr_arg _ (hφ₀ _ _ _),
end }
/-- The assumptions on `M` in Proposition 9.6 bundled into a structure. -/
structure normed_spectral_conditions (M : system_of_double_complexes.{u})
(m : ℕ) (k K k' ε : ℝ≥0) [fact (1 ≤ k)] [fact (1 ≤ k')] (c₀ H : ℝ≥0) [fact (0 < H)] :=
(row_exact : 0 < m → ∀ i ≤ m + 1, (M.row i).is_weak_bounded_exact k K (m-1) c₀)
(col_exact : ∀ j ≤ m, (M.col j).is_weak_bounded_exact k K m c₀)
(htpy : normed_spectral_homotopy (M.row_map 0 1) m k' ε c₀ H)
-- ergonomics: we bundle this assumption, instead of passing it around separately
(admissible : M.admissible)
.
namespace normed_spectral_conditions
variables {M : system_of_double_complexes.{u}}
variables {m : ℕ} {k K k' ε k₀ : ℝ≥0}
variables [fact (1 ≤ k)] [fact (1 ≤ k₀)] [fact (k₀ ≤ k')] [fact (1 ≤ k')]
variables {c₀ H : ℝ≥0} [fact (0 < H)]
lemma truncate_admissible (condM : M.normed_spectral_conditions m k K k' ε c₀ H) :
(truncate.obj M).admissible :=
truncate.admissible _ condM.admissible
variables (condM : M.normed_spectral_conditions (m+1) k K k' ε c₀ H)
include condM
lemma col_zero_exact :
((truncate.obj M).col 0).is_weak_bounded_exact (k*k*k) (K*(K*K+1)) m c₀ :=
begin
apply weak_normed_snake (M.col 0) (M.col 1) ((truncate.obj M).col 0)
(M.col_map 0 1) (truncate.quotient_map M)
(condM.col_exact 0 dec_trivial) (condM.col_exact 1 dec_trivial)
(condM.admissible.col 1),
{ intros c p, exact condM.admissible.d'_norm_noninc c p 0 1 },
{ intros c hc i hi x,
apply le_of_forall_pos_le_add,
intros ε' hε',
-- should we factor out a dedicated `weak_bounded_in_degrees_le_zero` lemma?
simpa only [exists_prop, row_res, d'_self_apply, exists_eq_left, sub_zero,
exists_and_distrib_left, zero_add, row_d, exists_eq_left', exists_const]
using condM.row_exact (nat.zero_lt_succ _) i hi c hc 0 (nat.zero_le _) x ε' hε' },
{ intros c i, apply quotient_add_group.ker_mk },
{ intros c p, exact SemiNormedGroup.coker.π_is_quotient }
end
-- morally `q'` is `q + 1`
def h_truncate : Π (q : ℕ) {q' : ℕ} {c : ℝ≥0},
(truncate.obj M).X (k' * c) 0 q' ⟶ (truncate.obj M).X c 1 q
| 0 1 c := condM.htpy.h 1 ≫ SemiNormedGroup.coker.π
| (q+1) (q'+1) c := condM.htpy.h (q+2)
| _ _ _ := 0
@[simp]
lemma h_truncate_zero {c : ℝ≥0} (x : (truncate.obj M).X (k' * c) 0 1) :
condM.h_truncate 0 x = SemiNormedGroup.coker.π (condM.htpy.h 1 x) := rfl
lemma norm_h_truncate_le : ∀ (q q' : ℕ), q ≤ m → q+1 = q' → ∀ (c : ℝ≥0), fact (c₀ ≤ c) →
∥(condM.h_truncate q : (truncate.obj M).X (k' * c) 0 q' ⟶ _)∥ ≤ H
| (q+1) (q'+1) hq rfl := condM.htpy.norm_h_le _ _ (nat.succ_le_succ hq)
(by simp only [nat.add_def, add_zero])
| 0 1 hq rfl :=
begin
introsI c hc,
refine normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg H) (λ x, _),
calc ∥SemiNormedGroup.coker.π (condM.htpy.h 1 x)∥
≤ ∥condM.htpy.h 1 x∥ : SemiNormedGroup.coker.π_is_quotient.norm_le _
... ≤ H * ∥x∥ : normed_group_hom.le_of_op_norm_le _ (condM.htpy.norm_h_le 1 2 dec_trivial rfl c) x
end
def δ_truncate (c : ℝ≥0) :
((truncate.obj M).row 0).obj (op $ c) ⟶ ((truncate.obj M).row 1).obj (op $ k' * c) :=
SemiNormedGroup.truncate.map (condM.htpy.δ c)
lemma hδ_truncate (c : ℝ≥0) [fact (c₀ ≤ c)] : ∀ (q : ℕ) (hq : q ≤ m),
(truncate.obj M).res ≫ (condM.δ_truncate c).f q = (d _ 0 1) ≫ (truncate.obj M).res +
(d' _ q (q+1)) ≫ condM.h_truncate q + (condM.h_truncate (q-1)) ≫ d' _ (q-1) q
| 1 h := condM.htpy.hδ _ _ (nat.succ_le_succ h)
| (q+2) h := condM.htpy.hδ _ _ (nat.succ_le_succ h)
| 0 h :=
begin
ext1 x, dsimp,
let π := λ c p, @SemiNormedGroup.coker.π _ _ (@d' M c p 0 1),
obtain ⟨x, rfl⟩ : ∃ x', π _ _ x' = x := SemiNormedGroup.coker.π_surjective x,
transitivity π _ _ ((condM.htpy.δ c).f 1 (M.res x)), { refl },
erw condM.htpy.hδ_apply _ _ (nat.succ_le_succ h) x,
simp only [nat.zero_sub, d'_self_apply, add_zero, row_d,
truncate.d_π, truncate.res_π, truncate.d'_zero_one, h_truncate_zero,
normed_group_hom.map_add, SemiNormedGroup.coker.pi_apply_dom_eq_zero],
refl
end
lemma norm_δ_truncate_le (c : ℝ≥0) [fact (c₀ ≤ c)] :
∀ (q : ℕ) (hq : q ≤ m), ∥(condM.δ_truncate c).f q∥ ≤ ε
| (q+1) h := condM.htpy.norm_δ_le c (q+2) (nat.succ_le_succ h)
| 0 h :=
begin
refine SemiNormedGroup.coker.norm_lift_le
(normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg ε) (λ x, _)),
refine (SemiNormedGroup.coker.π_norm_noninc _).trans _,
exact normed_group_hom.le_of_op_norm_le _ (condM.htpy.norm_δ_le c _ (nat.succ_le_succ h)) _
end
def truncate :
(truncate.obj M).normed_spectral_conditions m (k*k*k) (K*(K*K+1)) k' ε c₀ H :=
{ row_exact :=
begin
intros hm i hi,
cases m, { exact (nat.not_lt_zero _ hm).elim },
suffices : ((truncate.obj M).row i).is_weak_bounded_exact k K m c₀,
{ apply this.of_le (condM.truncate_admissible.row i) _ _ le_rfl ⟨le_rfl⟩;
apply_instance },
rw truncate.row,
apply (M.row i).truncate_is_weak_bounded_exact,
{ refine condM.row_exact (nat.zero_lt_succ _) i (hi.trans (nat.le_succ _)), }
end,
col_exact :=
begin
rintro (j|j) hj,
{ exact condM.col_zero_exact },
{ rw truncate.col_pos,
refine (condM.col_exact (j+2) (nat.succ_le_succ hj)).of_le
(condM.admissible.col (j+2)) _ _ m.le_succ ⟨le_rfl⟩;
apply_instance }
end,
htpy :=
{ h := condM.h_truncate,
norm_h_le := condM.norm_h_truncate_le,
δ := condM.δ_truncate,
hδ := condM.hδ_truncate,
norm_δ_le := condM.norm_δ_truncate_le },
admissible := condM.truncate_admissible }
omit condM
variables {m_ : ℕ} {k_ K_ : ℝ≥0} [fact (1 ≤ k_)]
variables {ε_ : ℝ≥0} {k₀_ : ℝ≥0} [fact (1 ≤ k₀_)]
variables [fact (k₀_ ≤ k')] {c₀_ H_ : ℝ≥0} [fact (0 < H_)]
def of_le (cond : M.normed_spectral_conditions m k K k' ε c₀ H)
(hm : m_ ≤ m) (hk : fact (k ≤ k_)) (hK : fact (K ≤ K_)) (hε : ε ≤ ε_)
(hc₀ : fact (c₀ ≤ c₀_)) (hH : H ≤ H_) :
M.normed_spectral_conditions m_ k_ K_ k' ε_ c₀_ H_ :=
{ col_exact := λ j hj, (cond.col_exact j (hj.trans hm)).of_le (cond.admissible.col j) hk hK hm hc₀,
row_exact := λ hm_ i hi,
(cond.row_exact (hm_.trans_le hm) i (hi.trans $ nat.succ_le_succ hm)).of_le
(cond.admissible.row i) hk hK (nat.pred_le_pred hm) hc₀,
htpy :=
{ h := cond.htpy.h,
norm_h_le := λ q q' hq hq' c hc, have fact (c₀ ≤ c) := ⟨hc₀.out.trans hc.out⟩, by exactI
begin
refine normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg H_) (λ x, _),
calc ∥cond.htpy.h q x∥ ≤ H * ∥x∥ :
normed_group_hom.le_of_op_norm_le _ (cond.htpy.norm_h_le q q' (hq.trans hm) hq' c) x
... ≤ H_ * ∥x∥ : mul_le_mul_of_nonneg_right hH (norm_nonneg x),
end,
δ := cond.htpy.δ,
hδ := λ c hc q hq, have fact (c₀ ≤ c) := ⟨hc₀.out.trans hc.out⟩,
by exactI cond.htpy.hδ c q (hq.trans hm),
norm_δ_le := λ c hc q hq, have fact (c₀ ≤ c) := ⟨hc₀.out.trans hc.out⟩, by exactI
begin
refine normed_group_hom.op_norm_le_bound _ (nnreal.coe_nonneg ε_) (λ x, _),
refine normed_group_hom.le_of_op_norm_le _ _ x,
exact le_trans (cond.htpy.norm_δ_le c q (hq.trans hm)) hε,
end },
admissible := cond.admissible }
end normed_spectral_conditions
namespace normed_spectral
/-- Base case of the induction for Proposition 9.6. -/
theorem base (c₀ H : ℝ≥0) [fact (0 < H)] (M : system_of_double_complexes.{u})
(k K k' : ℝ≥0) [hk : fact (1 ≤ k)] [hK : fact (1 ≤ K)] [fact (k₀ 0 k ≤ k')] [fact (1 ≤ k')]
(cond : M.normed_spectral_conditions 0 k K k' (ε 0 K) c₀ H) :
(M.row 0).is_weak_bounded_exact (k' * k') (2 * K₀ 0 K * H) 0 c₀ :=
begin
dsimp [k₀, K₀],
introsI c hc i hi,
interval_cases i, clear hi,
intros x ε' hε',
let φ : ℝ := ε' / 2,
have hφ : 0 < φ := div_pos hε' zero_lt_two,
have hδφ : ε' = φ + φ, { dsimp [φ], rw [← add_div, half_add_self] },
haveI : fact (k' * (k' * c) ≤ k' * k' * c) := by { rw mul_assoc, exact ⟨le_rfl⟩ },
have Hx1 := (cond.col_exact 0 le_rfl).of_le
(cond.admissible.col 0) ‹_› ⟨le_rfl⟩ le_rfl ⟨le_rfl⟩ c hc 0 le_rfl,
have Hx2 := normed_group_hom.le_of_op_norm_le _ (cond.htpy.norm_δ_le c 0 le_rfl) (M.res x),
have aux := cond.htpy.hδ_apply c 0 le_rfl (M.res x),
erw [res_res] at aux,
rw aux at Hx2,
simp only [row_d, col_d, d_self_apply, d'_self_apply, sub_zero, add_zero, smul_zero,
d_res, d'_res, res_res, one_div, row_res, units.coe_one, one_smul, row_map_apply] at Hx1 Hx2 ⊢,
refine ⟨0, 1, rfl, rfl, 0, _⟩,
obtain ⟨i, j, hi, hj, y1, hx1⟩ := Hx1 (M.res x) φ hφ,
simp [← eq_neg_iff_add_eq_zero] at hi hj, subst i, subst j,
simp only [d_self_apply, d'_self_apply, sub_zero,
nnreal.coe_mul, nnreal.coe_bit0, nnreal.coe_one, d_res] at hx1 ⊢,
erw [res_res] at hx1,
clear y1 Hx1,
replace Hx1 := mul_le_mul_of_nonneg_left hx1 (ε 0 K).coe_nonneg,
replace Hx2 := (norm_le_add_norm_add _ _).trans (add_le_add (Hx2.trans Hx1) le_rfl),
dsimp [ε] at Hx2,
have K0 : (K:ℝ) ≠ 0 := ne_of_gt (lt_of_lt_of_le zero_lt_one hK.out),
simp only [mul_add, add_assoc, mul_inv', mul_assoc, inv_mul_cancel_left' K0] at Hx2,
simp only [← div_eq_inv_mul, sub_half, ← sub_le_iff_le_add'] at Hx2,
simp only [sub_le_iff_le_add', div_le_iff' (zero_lt_two : (0:ℝ) < 2)] at Hx2,
replace Hx2 := mul_le_mul_of_nonneg_left Hx2 K.coe_nonneg,
simp only [mul_add, div_eq_inv_mul, add_comm φ,
mul_inv_cancel_left' (two_ne_zero : (2:ℝ) ≠ 0), mul_inv_cancel_left' K0] at Hx2,
refine hx1.trans _,
simp only [mul_comm (2:ℝ) K, mul_assoc, hδφ, ← add_assoc, ← mul_add, add_le_add_iff_right],
refine Hx2.trans _,
simp only [add_le_add_iff_right],
refine (mul_le_mul_of_nonneg_left _ K.coe_nonneg),
refine (mul_le_mul_of_nonneg_left _ zero_le_two),
refine le_trans (normed_group_hom.le_of_op_norm_le _ (cond.htpy.norm_h_le _ _ le_rfl rfl _) _) _,
refine mul_le_mul_of_nonneg_left (le_of_eq _) H.coe_nonneg,
apply norm_res_of_eq,
rw mul_assoc
end
.
end normed_spectral
open normed_spectral
/-- Proposition 9.6 in [Analytic] -/
theorem normed_spectral {m : ℕ} {c₀ H : ℝ≥0} [fact (0 < H)]
{M : system_of_double_complexes.{u}} {k K k' : ℝ≥0}
[fact (1 ≤ k)] [hK : fact (1 ≤ K)] [fact (k₀ m k ≤ k')] [fact (1 ≤ k')]
(cond : M.normed_spectral_conditions m k K k' (ε m K) c₀ H) :
(M.row 0).is_weak_bounded_exact (k' * k') (2 * K₀ m K * H) m c₀ :=
begin
unfreezingI { revert M k K k' },
induction m with m IH, { exact base c₀ H },
dsimp [ε, k₀, K₀],
introsI M k K k' _ _ _ _ cond,
rw ← system_of_complexes.truncate_is_weak_bounded_exact_iff,
{ exact IH cond.truncate },
{ refine @IH M (k*k*k) (K*(K*K+1)) k' _ _ _ _ (cond.of_le (m.le_succ) _ _ le_rfl ⟨le_rfl⟩ le_rfl),
all_goals { apply_instance } }
end
end system_of_double_complexes
|
4a6187f58b8e88553a62735ab7f771ecbb8461bb | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /src/07_Negation/01_homework_key.lean | 1f65abd11cc8bb745e3071c9e30b3eaca1b81175 | [] | no_license | kevinsullivan/cs-dm-lean | b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124 | a06a94e98be77170ca1df486c8189338b16cf6c6 | refs/heads/master | 1,585,948,743,595 | 1,544,339,346,000 | 1,544,339,346,000 | 155,570,767 | 1 | 3 | null | 1,541,540,372,000 | 1,540,995,993,000 | Lean | UTF-8 | Lean | false | false | 2,934 | lean | /-
-/
section homework
variables P Q R S : Prop
example : (P → (Q → R)) → (P ∧ Q → R) :=
sorry
example : P ∧ (P → Q) → Q :=
assume h : P ∧ (P → Q),
have p : P := h.left,
show Q,
from h.right p
example : P → ¬ (¬ P ∧ Q) :=
assume p: P,
assume c: (¬ P ∧ Q),
have np: ¬ P := c.left,
show false,
from np p
example : ¬ (P ∧ Q) → (P → ¬ Q) :=
assume h : ¬ (P ∧ Q),
assume p : P,
sorry
example (h₁ : P ∨ Q) (h₂ : P → R) (h₃ : Q → S) : R ∨ S :=
sorry
example (h : ¬ P ∧ ¬ Q) : ¬ (P ∨ Q) :=
sorry
example : ¬ (P ↔ ¬ P) :=
sorry
/-
Prove P → ¬ ¬ P without using
the axiom of the excluded middle.
Can you prove ¬ ¬ P → P without using
the axiom of the excluded middle. Explain.
Can you prove (P → Q) → (¬ Q → ¬ P)
"intuitionistically" (without relying
directly or indirectly on the axiom
of the excluded middle)? If so, prove
it intuitionistically. If not, explain
exactly where you get stuck and then
prove it "classically" (where you can
use, directly or indirectly, the axiom
of the excluded middle).
Can you prove (¬ Q → ¬ P) → (P → Q)
"intuitionistically" (without relying
directly or indirectly on the axiom
of the excluded middle)? If so, prove
it intuitionistically. If not, explain
exactly where you get stuck and then
prove it "classically" (where you can
use, directly or indirectly, the axiom
of the excluded middle).
-/
Commutativity of ∧: A∧B↔B∧A
Commutativity of ∨: A∨B↔B∨A
Associativity of ∧: (A∧B)∧C↔A∧(B∧C)
Associativity of ∨ (A∨B)∨C↔A∨(B∨C)
Distributivity of ∧ over ∨: A∧(B∨C)↔(A∧B)∨(A∧C)
Distributivity of ∨ over ∧: A∨(B∧C)↔(A∨B)∧(A∨C)
(A→(B→C))↔(A∧B→C).
(A→B)→((B→C)→(A→C))
((A∨B)→C)↔(A→C)∧(B→C)
¬(A∨B)↔¬A∧¬B
¬(A∧B)↔¬A∨¬B
¬(A∧¬A)
¬(A→B)↔A∧¬B
¬A→(A→B)
(¬A∨B)↔(A→B)
A∨⊥↔A
A∧⊥↔⊥
A∨¬A
¬(A↔¬A)
(A→B)↔(¬B→¬A)
(A→C∨D)→((A→C)∨(A→D))
(((A→B)→A)→A)
Give a natural deduction proof of ¬(A∧B)→(A→¬B).
Give a natural deduction proof of (A→C)∧(B→¬C)→¬(A∧B).
Give a natural deduction proof of (A∧B)→((A→C)→¬(B→¬C)).
Take another look at Exercise 3 in the last chapter. Using propositional variables A, B, and C for “Alan likes kangaroos,” “Betty likes frogs” and “Carl likes hamsters,” respectively, express the three hypotheses in the previous problem as symbolic formulas, and then derive a contradiction from them in natural deduction.
Give a natural deduction proof of A∨B→B∨A.
Give a natural deduction proof of ¬A∧¬B→¬(A∨B)
Give a natural deduction proof of ¬(A∧B) from ¬A∨¬B. (You do not need to use proof by contradiction.)
Give a natural deduction proof of ¬(A↔¬A).
Give a natural deduction proof of (¬A↔¬B) from hypothesis A↔B.
end homework |
b58e2ae6b07fa645112478c4adcc583e9ef64b23 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/data/finsupp/basic.lean | a1441fdc14f0cd22439ad4409032b48b67ac7131 | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 77,701 | 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, Scott Morrison
-/
import algebra.group.pi
import algebra.big_operators.order
import algebra.module.basic
import group_theory.submonoid.basic
import data.fintype.card
import data.finset.preimage
import data.multiset.antidiagonal
import data.indicator_function
/-!
# Type of functions with finite support
For any type `α` and a type `M` with zero, we define the type `finsupp α M` (notation: `α →₀ M`)
of finitely supported functions from `α` to `M`, i.e. the functions which are zero everywhere
on `α` except on a finite set.
Functions with finite support are used (at least) in the following parts of the library:
* `monoid_algebra R M` and `add_monoid_algebra R M` are defined as `M →₀ R`;
* polynomials and multivariate polynomials are defined as `add_monoid_algebra`s, hence they use
`finsupp` under the hood;
* the linear combination of a family of vectors `v i` with coefficients `f i` (as used, e.g., to
define linearly independent family `linear_independent`) is defined as a map
`finsupp.total : (ι → M) → (ι →₀ R) →ₗ[R] M`.
Some other constructions are naturally equivalent to `α →₀ M` with some `α` and `M` but are defined
in a different way in the library:
* `multiset α ≃+ α →₀ ℕ`;
* `free_abelian_group α ≃+ α →₀ ℤ`.
Most of the theory assumes that the range is a commutative additive monoid. This gives us the big
sum operator as a powerful way to construct `finsupp` elements.
Many constructions based on `α →₀ M` use `semireducible` type tags to avoid reusing unwanted type
instances. E.g., `monoid_algebra`, `add_monoid_algebra`, and types based on these two have
non-pointwise multiplication.
## Notations
This file adds `α →₀ M` as a global notation for `finsupp α M`. We also use the following convention
for `Type*` variables in this file
* `α`, `β`, `γ`: types with no additional structure that appear as the first argument to `finsupp`
somewhere in the statement;
* `ι` : an auxiliary index type;
* `M`, `M'`, `N`, `P`: types with `has_zero` or `(add_)(comm_)monoid` structure; `M` is also used
for a (semi)module over a (semi)ring.
* `G`, `H`: groups (commutative or not, multiplicative or additive);
* `R`, `S`: (semi)rings.
## TODO
* This file is currently ~2K lines long, so possibly it should be splitted into smaller chunks;
* Add the list of definitions and important lemmas to the module docstring.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## Notation
This file defines `α →₀ β` as notation for `finsupp α β`.
-/
noncomputable theory
open_locale classical big_operators
open finset
variables {α β γ ι M M' N P G H R S : Type*}
/-- `finsupp α M`, denoted `α →₀ M`, is the type of functions `f : α → M` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (M : Type*) [has_zero M] :=
(support : finset α)
(to_fun : α → M)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
/-! ### Basic declarations about `finsupp` -/
section basic
variable [has_zero M]
instance : has_coe_to_fun (α →₀ M) := ⟨λ _, α → M, to_fun⟩
@[simp] lemma coe_mk (f : α → M) (s : finset α) (h : ∀ a, a ∈ s ↔ f a ≠ 0) :
⇑(⟨s, f, h⟩ : α →₀ M) = f := rfl
instance : has_zero (α →₀ M) := ⟨⟨∅, (λ _, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma coe_zero : ⇑(0 : α →₀ M) = (λ _, (0:M)) := rfl
lemma zero_apply {a : α} : (0 : α →₀ M) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ M).support = ∅ := rfl
instance : inhabited (α →₀ M) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ M} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
@[simp] lemma fun_support_eq (f : α →₀ M) : function.support f = f.support :=
set.ext $ λ x, mem_support_iff.symm
lemma not_mem_support_iff {f : α →₀ M} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
lemma coe_fn_injective : function.injective (λ (f : α →₀ M) (x : α), f x)
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
change f = g at h, subst h,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
@[ext] lemma ext {f g : α →₀ M} (h : ∀a, f a = g a) : f = g := coe_fn_injective (funext h)
lemma ext_iff {f g : α →₀ M} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
lemma ext_iff' {f g : α →₀ M} : f = g ↔ f.support = g.support ∧ ∀ x ∈ f.support, f x = g x :=
⟨λ h, h ▸ ⟨rfl, λ _ _, rfl⟩, λ ⟨h₁, h₂⟩, ext $ λ a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, from not_mem_support_iff.1 h,
have hg : g a = 0, by rwa [h₁, not_mem_support_iff] at h,
by rw [hf, hg]⟩
@[simp] lemma support_eq_empty {f : α →₀ M} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext_iff.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
lemma card_support_eq_zero {f : α →₀ M} : card f.support = 0 ↔ f = 0 :=
by simp
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq M] : decidable_eq (α →₀ M) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a)) ext_iff'.symm
lemma finite_supp (f : α →₀ M) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ M} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, not_imp_comm)
/-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
def equiv_fun_on_fintype [fintype α] : (α →₀ M) ≃ (α → M) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ,
iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
/-! ### Declarations about `single` -/
section single
variables [has_zero M] {a a' : α} {b : M}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : M) : α →₀ M :=
⟨if b = 0 then ∅ else {a}, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : single a b a' = if a = a' then b else 0 :=
rfl
lemma single_eq_indicator : ⇑(single a b) = set.indicator {a} (λ _, b) :=
by { ext, simp [single_apply, set.indicator, @eq_comm _ a] }
@[simp] lemma single_eq_same : (single a b : α →₀ M) a = b :=
if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ M) a' = 0 :=
if_neg h
lemma single_eq_update : ⇑(single a b) = function.update 0 a b :=
by rw [single_eq_indicator, ← set.piecewise_eq_indicator, set.piecewise_singleton]
@[simp] lemma single_zero : (single a 0 : α →₀ M) = 0 :=
coe_fn_injective $ by simpa only [single_eq_update, coe_zero]
using function.update_eq_self a (0 : α → M)
lemma single_of_single_apply (a a' : α) (b : M) :
single a ((single a' b) a) = single a' (single a' b) a :=
begin
rw [single_apply, single_apply],
ext,
split_ifs,
{ rw h, },
{ rw [zero_apply, single_apply, if_t_t], },
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma single_apply_mem (x) : single a b x ∈ ({0, b} : set M) :=
by rcases em (a = x) with (rfl|hx); [simp, simp [single_eq_of_ne hx]]
lemma range_single_subset : set.range (single a b) ⊆ {0, b} :=
set.range_subset_iff.2 single_apply_mem
lemma single_injective (a : α) : function.injective (single a : M → α →₀ M) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ M) a = (single a b₂ : α →₀ M) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_apply_eq_zero {a x : α} {b : M} : single a b x = 0 ↔ (x = a → b = 0) :=
by simp [single_eq_indicator]
lemma mem_support_single (a a' : α) (b : M) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
by simp [single_apply_eq_zero, not_or_distrib]
lemma eq_single_iff {f : α →₀ M} {a b} : f = single a b ↔ f.support ⊆ {a} ∧ f a = b :=
begin
refine ⟨λ h, h.symm ▸ ⟨support_single_subset, single_eq_same⟩, _⟩,
rintro ⟨h, rfl⟩,
ext x,
by_cases hx : a = x; simp only [hx, single_eq_same, single_eq_of_ne, ne.def, not_false_iff],
exact not_mem_support_iff.1 (mt (λ hx, (mem_singleton.1 (h hx)).symm) hx)
end
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : M) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (single_injective a₂).eq_iff] at eq },
{ rw [ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_left_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa only [h, single_eq_single_iff,
and_false, or_false, eq_self_iff_true, and_true] using H,
λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [single_eq_same, zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap (a₁ a₂ : α) (b : M) : single a₁ b a₂ = single a₂ b a₁ :=
by simp only [single_apply]; ac_refl
instance [nonempty α] [nontrivial M] : nontrivial (α →₀ M) :=
begin
inhabit α,
rcases exists_ne (0 : M) with ⟨x, hx⟩,
exact nontrivial_of_ne (single (default α) x) 0 (mt single_eq_zero.1 hx)
end
lemma unique_single [unique α] (x : α →₀ M) : x = single (default α) (x (default α)) :=
ext $ unique.forall_iff.2 single_eq_same.symm
lemma unique_ext [unique α] {f g : α →₀ M} (h : f (default α) = g (default α)) : f = g :=
ext $ λ a, by rwa [unique.eq_default a]
lemma unique_ext_iff [unique α] {f g : α →₀ M} : f = g ↔ f (default α) = g (default α) :=
⟨λ h, h ▸ rfl, unique_ext⟩
@[simp] lemma unique_single_eq_iff [unique α] {b' : M} :
single a b = single a' b' ↔ b = b' :=
by rw [unique_ext_iff, unique.eq_default a, unique.eq_default a', single_eq_same, single_eq_same]
lemma support_eq_singleton {f : α →₀ M} {a : α} :
f.support = {a} ↔ f a ≠ 0 ∧ f = single a (f a) :=
⟨λ h, ⟨mem_support_iff.1 $ h.symm ▸ finset.mem_singleton_self a,
eq_single_iff.2 ⟨subset_of_eq h, rfl⟩⟩, λ h, h.2.symm ▸ support_single_ne_zero h.1⟩
lemma support_eq_singleton' {f : α →₀ M} {a : α} :
f.support = {a} ↔ ∃ b ≠ 0, f = single a b :=
⟨λ h, let h := support_eq_singleton.1 h in ⟨_, h.1, h.2⟩,
λ ⟨b, hb, hf⟩, hf.symm ▸ support_single_ne_zero hb⟩
lemma card_support_eq_one {f : α →₀ M} : card f.support = 1 ↔ ∃ a, f a ≠ 0 ∧ f = single a (f a) :=
by simp only [card_eq_one, support_eq_singleton]
lemma card_support_eq_one' {f : α →₀ M} : card f.support = 1 ↔ ∃ a (b ≠ 0), f = single a b :=
by simp only [card_eq_one, support_eq_singleton']
end single
/-! ### Declarations about `on_finset` -/
section on_finset
variables [has_zero M]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def on_finset (s : finset α) (f : α → M) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ M :=
⟨s.filter (λa, f a ≠ 0), f, by simpa⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → M} {hf a} :
(on_finset s f hf : α →₀ M) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → M} {hf} :
(on_finset s f hf).support ⊆ s :=
filter_subset _ _
@[simp] lemma mem_support_on_finset
{s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) {a : α} :
a ∈ (finsupp.on_finset s f hf).support ↔ f a ≠ 0 :=
by rw [finsupp.mem_support_iff, finsupp.on_finset_apply]
lemma support_on_finset
{s : finset α} {f : α → M} (hf : ∀ (a : α), f a ≠ 0 → a ∈ s) :
(finsupp.on_finset s f hf).support = s.filter (λ a, f a ≠ 0) :=
rfl
end on_finset
/-! ### Declarations about `map_range` -/
section map_range
variables [has_zero M] [has_zero N]
/-- The composition of `f : M → N` and `g : α →₀ M` is
`map_range f hf g : α →₀ N`, well-defined when `f 0 = 0`. -/
def map_range (f : M → N) (hf : f 0 = 0) (g : α →₀ M) : α →₀ N :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : M → N} {hf : f 0 = 0} {g : α →₀ M} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : M → N} {hf : f 0 = 0} : map_range f hf (0 : α →₀ M) = 0 :=
ext $ λ a, by simp only [hf, zero_apply, map_range_apply]
lemma support_map_range {f : M → N} {hf : f 0 = 0} {g : α →₀ M} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : M → N} {hf : f 0 = 0} {a : α} {b : M} :
map_range f hf (single a b) = single a (f b) :=
ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
/-! ### Declarations about `emb_domain` -/
section emb_domain
variables [has_zero M] [has_zero N]
/-- Given `f : α ↪ β` and `v : α →₀ M`, `emb_domain f v : β →₀ M`
is the finitely supported function whose value at `f a : β` is `v a`.
For a `b : β` outside the range of `f`, it is zero. -/
def emb_domain (f : α ↪ β) (v : α →₀ M) : β →₀ M :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.injective hb) },
{ assume a₂,
split_ifs,
{ simp only [h, true_iff, ne.def],
rw [← not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp only [h, ne.def, ne_self_iff_false] } }
end
@[simp] lemma support_emb_domain (f : α ↪ β) (v : α →₀ M) :
(emb_domain f v).support = v.support.map f :=
rfl
@[simp] lemma emb_domain_zero (f : α ↪ β) : (emb_domain f 0 : β →₀ M) = 0 :=
rfl
@[simp] lemma emb_domain_apply (f : α ↪ β) (v : α →₀ M) (a : α) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α → M) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α ↪ β) (v : α →₀ M) (a : β) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_injective (f : α ↪ β) :
function.injective (emb_domain f : (α →₀ M) → (β →₀ M)) :=
λ l₁ l₂ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a)
@[simp] lemma emb_domain_inj {f : α ↪ β} {l₁ l₂ : α →₀ M} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
(emb_domain_injective f).eq_iff
@[simp] lemma emb_domain_eq_zero {f : α ↪ β} {l : α →₀ M} :
emb_domain f l = 0 ↔ l = 0 :=
(emb_domain_injective f).eq_iff' $ emb_domain_zero f
lemma emb_domain_map_range
(f : α ↪ β) (g : M → N) (p : α →₀ M) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α →₀ M) (f : α ↪ β) (a : β) (b : M) (hb : b ≠ 0)
(h : l.emb_domain f = single a b) :
∃ x, l = single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = {a},
by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp only [h_map_support, finset.mem_singleton],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp only [eq.symm h_cases, hc₂, single_eq_same] },
{ rw [single_apply, single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.injective (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
/-! ### Declarations about `zip_with` -/
section zip_with
variables [has_zero M] [has_zero N] [has_zero P]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/
def zip_with (f : M → N → P) (hf : f 0 0 = 0) (g₁ : α →₀ M) (g₂ : α →₀ N) : (α →₀ P) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H,
begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
lemma support_zip_with {f : M → N → P} {hf : f 0 0 = 0} {g₁ : α →₀ M} {g₂ : α →₀ N} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
/-! ### Declarations about `erase` -/
section erase
variables [has_zero M]
/-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to
`0`. -/
def erase (a : α) (f : α →₀ M) : α →₀ M :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase {a : α} {f : α →₀ M} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same {a : α} {f : α →₀ M} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne {a a' : α} {f : α →₀ M} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
@[simp] lemma erase_single {a : α} {b : M} : (erase a (single a b)) = 0 :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same], refl },
{ rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) }
end
lemma erase_single_ne {a a' : α} {b : M} (h : a ≠ a') : (erase a (single a' b)) = single a' b :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same, single_eq_of_ne (h.symm)] },
{ rw [erase_ne hs] }
end
@[simp] lemma erase_zero (a : α) : erase a (0 : α →₀ M) = 0 :=
by rw [← support_eq_empty, support_erase, support_zero, erase_empty]
end erase
/-!
### Declarations about `sum` and `prod`
In most of this section, the domain `β` is assumed to be an `add_monoid`.
-/
section sum_prod
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero M] [add_comm_monoid N] (f : α →₀ M) (g : α → M → N) : N :=
∑ a in f.support, g a (f a)
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero M] [comm_monoid N] (f : α →₀ M) (g : α → M → N) : N :=
∏ a in f.support, g a (f a)
variables [has_zero M] [has_zero M'] [comm_monoid N]
@[to_additive]
lemma prod_of_support_subset (f : α →₀ M) {s : finset α}
(hs : f.support ⊆ s) (g : α → M → N) (h : ∀ i ∈ s, g i 0 = 1) :
f.prod g = ∏ x in s, g x (f x) :=
finset.prod_subset hs $ λ x hxs hx, h x hxs ▸ congr_arg (g x) $ not_mem_support_iff.1 hx
@[to_additive]
lemma prod_fintype [fintype α] (f : α →₀ M) (g : α → M → N) (h : ∀ i, g i 0 = 1) :
f.prod g = ∏ i, g i (f i) :=
f.prod_of_support_subset (subset_univ _) g (λ x _, h x)
@[simp, to_additive]
lemma prod_single_index {a : α} {b : M} {h : α → M → N} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
calc (single a b).prod h = ∏ x in {a}, h x (single a b x) :
prod_of_support_subset _ support_single_subset h $ λ x hx, (mem_singleton.1 hx).symm ▸ h_zero
... = h a b : by simp
@[to_additive]
lemma prod_map_range_index {f : M → M'} {hf : f 0 = 0} {g : α →₀ M} {h : α → M' → N}
(h0 : ∀a, h a 0 = 1) : (map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[simp, to_additive]
lemma prod_zero_index {h : α → M → N} : (0 : α →₀ M).prod h = 1 := rfl
@[to_additive]
lemma prod_comm (f : α →₀ M) (g : β →₀ M') (h : α → M → β → M' → N) :
f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) :=
finset.prod_comm
@[simp, to_additive]
lemma prod_ite_eq (f : α →₀ M) (a : α) (b : α → M → N) :
f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, }
/-- A restatement of `prod_ite_eq` with the equality test reversed. -/
@[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."]
lemma prod_ite_eq' (f : α →₀ M) (a : α) (b : α → M → N) :
f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', }
@[simp] lemma prod_pow [fintype α] (f : α →₀ ℕ) (g : α → N) :
f.prod (λ a b, g a ^ b) = ∏ a, g a ^ (f a) :=
f.prod_fintype _ $ λ a, pow_zero _
/-- If `g` maps a second argument of 0 to 1, then multiplying it over the
result of `on_finset` is the same as multiplying it over the original
`finset`. -/
@[to_additive "If `g` maps a second argument of 0 to 0, summing it over the
result of `on_finset` is the same as summing it over the original
`finset`."]
lemma on_finset_prod {s : finset α} {f : α → M} {g : α → M → N}
(hf : ∀a, f a ≠ 0 → a ∈ s) (hg : ∀ a, g a 0 = 1) :
(on_finset s f hf).prod g = ∏ a in s, g a (f a) :=
finset.prod_subset support_on_finset_subset $ by simp [*] { contextual := tt }
end sum_prod
/-!
### Additive monoid structure on `α →₀ M`
-/
section add_monoid
variables [add_monoid M]
instance : has_add (α →₀ M) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma coe_add (f g : α →₀ M) : ⇑(f + g) = f + g := rfl
lemma add_apply {g₁ g₂ : α →₀ M} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a := rfl
lemma support_add {g₁ g₂ : α →₀ M} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ M} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : M} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ M) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
/-- `finsupp.single` as an `add_monoid_hom`.
See `finsupp.lsingle` for the stronger version as a linear map.
-/
@[simps] def single_add_hom (a : α) : M →+ α →₀ M :=
⟨single a, single_zero, λ _ _, single_add⟩
/-- Evaluation of a function `f : α →₀ M` at a point as an additive monoid homomorphism.
See `finsupp.lapply` for the stronger version as a linear map. -/
@[simps apply]
def apply_add_hom (a : α) : (α →₀ M) →+ M := ⟨λ g, g a, zero_apply, λ _ _, add_apply⟩
lemma single_add_erase (a : α) (f : α →₀ M) : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single (a : α) (f : α →₀ M) : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[simp] lemma erase_add (a : α) (f f' : α →₀ M) : erase a (f + f') = erase a f + erase a f' :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] },
rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply],
end
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ M) → Prop} (f : α →₀ M)
(h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ M) → Prop} (f : α →₀ M)
(h0 : p 0) (ha : ∀a b (f : α →₀ M), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ M), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
@[simp] lemma add_closure_Union_range_single :
add_submonoid.closure (⋃ a : α, set.range (single a : M → α →₀ M)) = ⊤ :=
top_unique $ λ x hx, finsupp.induction x (add_submonoid.zero_mem _) $
λ a b f ha hb hf, add_submonoid.add_mem _
(add_submonoid.subset_closure $ set.mem_Union.2 ⟨a, set.mem_range_self _⟩) hf
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then
they are equal. -/
lemma add_hom_ext [add_monoid N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x y, f (single x y) = g (single x y)) :
f = g :=
begin
refine add_monoid_hom.eq_of_eq_on_mdense add_closure_Union_range_single (λ f hf, _),
simp only [set.mem_Union, set.mem_range] at hf,
rcases hf with ⟨x, y, rfl⟩,
apply H
end
/-- If two additive homomorphisms from `α →₀ M` are equal on each `single a b`, then
they are equal.
We formulate this using equality of `add_monoid_hom`s so that `ext` tactic can apply a type-specific
extensionality lemma after this one. E.g., if the fiber `M` is `ℕ` or `ℤ`, then it suffices to
verify `f (single a 1) = g (single a 1)`. -/
@[ext] lemma add_hom_ext' [add_monoid N] ⦃f g : (α →₀ M) →+ N⦄
(H : ∀ x, f.comp (single_add_hom x) = g.comp (single_add_hom x)) :
f = g :=
add_hom_ext $ λ x, add_monoid_hom.congr_fun (H x)
lemma mul_hom_ext [monoid N] ⦃f g : multiplicative (α →₀ M) →* N⦄
(H : ∀ x y, f (multiplicative.of_add $ single x y) = g (multiplicative.of_add $ single x y)) :
f = g :=
monoid_hom.ext $ add_monoid_hom.congr_fun $
@add_hom_ext α M (additive N) _ _ f.to_additive'' g.to_additive'' H
@[ext] lemma mul_hom_ext' [monoid N] {f g : multiplicative (α →₀ M) →* N}
(H : ∀ x, f.comp (single_add_hom x).to_multiplicative =
g.comp (single_add_hom x).to_multiplicative) :
f = g :=
mul_hom_ext $ λ x, monoid_hom.congr_fun (H x)
lemma map_range_add [add_monoid N]
{f : M → N} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ M) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
ext $ λ a, by simp only [hf', add_apply, map_range_apply]
end add_monoid
end finsupp
@[to_additive]
lemma mul_equiv.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P]
(h : N ≃* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
@[to_additive]
lemma monoid_hom.map_finsupp_prod [has_zero M] [comm_monoid N] [comm_monoid P]
(h : N →* P) (f : α →₀ M) (g : α → M → N) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
lemma ring_hom.map_finsupp_sum [has_zero M] [semiring R] [semiring S]
(h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.sum g) = f.sum (λ a b, h (g a b)) :=
h.map_sum _ _
lemma ring_hom.map_finsupp_prod [has_zero M] [comm_semiring R] [comm_semiring S]
(h : R →+* S) (f : α →₀ M) (g : α → M → R) : h (f.prod g) = f.prod (λ a b, h (g a b)) :=
h.map_prod _ _
namespace finsupp
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ :=
begin
ext f,
by_cases h : (a = f),
{ rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] },
rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h]
end
-- These next two lemmas are used in developing
-- the partial derivative on `mv_polynomial`.
lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, },
{ simp [h], }
end
lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, },
{ simp [h], }
end
end nat_sub
instance [add_comm_monoid M] : add_comm_monoid (α →₀ M) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group G] : add_group (α →₀ G) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
instance [add_comm_group G] : add_comm_group (α →₀ G) :=
{ add_comm := add_comm, ..finsupp.add_group }
lemma single_multiset_sum [add_comm_monoid M] (s : multiset M) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid M] (s : finset ι) (f : ι → M) (a : α) :
single a (∑ b in s, f b) = ∑ b in s, single a (f b) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero M] [add_comm_monoid N] (s : ι →₀ M) (f : ι → M → N) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group G] [comm_monoid M] {g : α →₀ G} {h : α → G → M}
(h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group G] {g : α →₀ G} {a : α} : (- g) a = - g a :=
rfl
@[simp] lemma sub_apply [add_group G] {g₁ g₂ : α →₀ G} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma support_neg [add_group G] {f : α →₀ G} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
@[simp] lemma sum_apply [has_zero M] [add_comm_monoid N]
{f : α →₀ M} {g : α → M → β →₀ N} {a₂ : β} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(apply_add_hom a₂ : (β →₀ N) →+ _).map_sum _ _
lemma support_sum [has_zero M] [add_comm_monoid N]
{f : α →₀ M} {g : α → M → (β →₀ N)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀ c, f.sum (λ a b, g a b c) ≠ 0 → (∃ a, f a ≠ 0 ∧ ¬ (g a (f a)) c = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop]
@[simp] lemma sum_zero [has_zero M] [add_comm_monoid N] {f : α →₀ M} :
f.sum (λa b, (0 : N)) = 0 :=
finset.sum_const_zero
@[simp, to_additive]
lemma prod_mul [has_zero M] [comm_monoid N] {f : α →₀ M} {h₁ h₂ : α → M → N} :
f.prod (λa b, h₁ a b * h₂ a b) = f.prod h₁ * f.prod h₂ :=
finset.prod_mul_distrib
@[simp, to_additive]
lemma prod_inv [has_zero M] [comm_group G] {f : α →₀ M}
{h : α → M → G} : f.prod (λa b, (h a b)⁻¹) = (f.prod h)⁻¹ :=
(((monoid_hom.id G)⁻¹).map_prod _ _).symm
@[simp] lemma sum_sub [has_zero M] [add_comm_group G] {f : α →₀ M}
{h₁ h₂ : α → M → G} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
finset.sum_sub_distrib
@[to_additive]
lemma prod_add_index [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M}
{h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have hf : f.prod h = ∏ a in f.support ∪ g.support, h a (f a),
from f.prod_of_support_subset (subset_union_left _ _) _ $ λ a ha, h_zero a,
have hg : g.prod h = ∏ a in f.support ∪ g.support, h a (g a),
from g.prod_of_support_subset (subset_union_right _ _) _ $ λ a ha, h_zero a,
have hfg : (f + g).prod h = ∏ a in f.support ∪ g.support, h a ((f + g) a),
from (f + g).prod_of_support_subset support_add _ $ λ a ha, h_zero a,
by simp only [*, add_apply, prod_mul_distrib]
@[simp]
lemma sum_add_index' [add_comm_monoid M] [add_comm_monoid N] {f g : α →₀ M} (h : α → M →+ N) :
(f + g).sum (λ x, h x) = f.sum (λ x, h x) + g.sum (λ x, h x) :=
sum_add_index (λ a, (h a).map_zero) (λ a, (h a).map_add)
@[simp]
lemma prod_add_index' [add_comm_monoid M] [comm_monoid N] {f g : α →₀ M}
(h : α → multiplicative M →* N) :
(f + g).prod (λ a b, h a (multiplicative.of_add b)) =
f.prod (λ a b, h a (multiplicative.of_add b)) * g.prod (λ a b, h a (multiplicative.of_add b)) :=
prod_add_index (λ a, (h a).map_one) (λ a, (h a).map_mul)
/-- The canonical isomorphism between families of additive monoid homomorphisms `α → (M →+ N)`
and monoid homomorphisms `(α →₀ M) →+ N`. -/
def lift_add_hom [add_comm_monoid M] [add_comm_monoid N] : (α → M →+ N) ≃+ ((α →₀ M) →+ N) :=
{ to_fun := λ F,
{ to_fun := λ f, f.sum (λ x, F x),
map_zero' := finset.sum_empty,
map_add' := λ _ _, sum_add_index (λ x, (F x).map_zero) (λ x, (F x).map_add) },
inv_fun := λ F x, F.comp $ single_add_hom x,
left_inv := λ F, by { ext, simp },
right_inv := λ F, by { ext, simp },
map_add' := λ F G, by { ext, simp } }
@[simp] lemma lift_add_hom_apply [add_comm_monoid M] [add_comm_monoid N]
(F : α → M →+ N) (f : α →₀ M) :
lift_add_hom F f = f.sum (λ x, F x) :=
rfl
@[simp] lemma lift_add_hom_symm_apply [add_comm_monoid M] [add_comm_monoid N]
(F : (α →₀ M) →+ N) (x : α) :
lift_add_hom.symm F x = F.comp (single_add_hom x) :=
rfl
lemma lift_add_hom_symm_apply_apply [add_comm_monoid M] [add_comm_monoid N]
(F : (α →₀ M) →+ N) (x : α) (y : M) :
lift_add_hom.symm F x y = F (single x y) :=
rfl
@[simp] lemma lift_add_hom_single_add_hom [add_comm_monoid M] :
lift_add_hom (single_add_hom : α → M →+ α →₀ M) = add_monoid_hom.id _ :=
lift_add_hom.to_equiv.apply_eq_iff_eq_symm_apply.2 rfl
@[simp] lemma sum_single [add_comm_monoid M] (f : α →₀ M) :
f.sum single = f :=
add_monoid_hom.congr_fun lift_add_hom_single_add_hom f
@[simp] lemma lift_add_hom_apply_single [add_comm_monoid M] [add_comm_monoid N]
(f : α → M →+ N) (a : α) (b : M) :
lift_add_hom f (single a b) = f a b :=
sum_single_index (f a).map_zero
@[simp] lemma lift_add_hom_comp_single [add_comm_monoid M] [add_comm_monoid N] (f : α → M →+ N)
(a : α) :
(lift_add_hom f).comp (single_add_hom a) = f a :=
add_monoid_hom.ext $ λ b, lift_add_hom_apply_single f a b
lemma comp_lift_add_hom [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P]
(g : N →+ P) (f : α → M →+ N) :
g.comp (lift_add_hom f) = lift_add_hom (λ a, g.comp (f a)) :=
lift_add_hom.symm_apply_eq.1 $ funext $ λ a,
by rw [lift_add_hom_symm_apply, add_monoid_hom.comp_assoc, lift_add_hom_comp_single]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
(lift_add_hom (λ a, add_monoid_hom.of_map_sub (h a) (h_sub a))).map_sub f g
@[to_additive]
lemma prod_emb_domain [has_zero M] [comm_monoid N] {v : α →₀ M} {f : α ↪ β} {g : β → M → N} :
(v.emb_domain f).prod g = v.prod (λ a b, g (f a) b) :=
begin
rw [prod, prod, support_emb_domain, finset.prod_map],
simp_rw emb_domain_apply,
end
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid M] [comm_monoid N]
{s : finset ι} {g : ι → α →₀ M}
{h : α → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
∏ i in s, (g i).prod h = (∑ i in s, g i).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid M] [add_comm_monoid N] [comm_monoid P]
{f : α →₀ M} {g : α → M → β →₀ N}
{h : β → N → P} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid M] [add_comm_monoid N]
(f : multiset (α →₀ M)) (h : α → M → N)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : M), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ M, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero M] {f : α →₀ M} {m : β → γ} {h : α → M → multiset β} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(f.support.sum_hom _).symm
lemma multiset_sum_sum [has_zero M] [add_comm_monoid N] {f : α →₀ M} {h : α → M → multiset N} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(f.support.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid M] [add_comm_monoid N] (f : M →+ N)
/--
Composition with a fixed additive homomorphism is itself an additive homomorphism on functions.
-/
def map_range.add_monoid_hom : (α →₀ M) →+ (α →₀ N) :=
{ to_fun := (map_range f f.map_zero : (α →₀ M) → (α →₀ N)),
map_zero' := map_range_zero,
map_add' := λ a b, map_range_add f.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ M)) :
map_range f f.map_zero m.sum = (m.map $ λx, map_range f f.map_zero x).sum :=
(m.sum_hom (map_range.add_monoid_hom f)).symm
lemma map_range_finset_sum (s : finset ι) (g : ι → (α →₀ M)) :
map_range f f.map_zero (∑ x in s, g x) = ∑ x in s, map_range f f.map_zero (g x) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
/-! ### Declarations about `map_domain` -/
section map_domain
variables [add_comm_monoid M] {v v₁ v₂ : α →₀ M}
/-- Given `f : α → β` and `v : α →₀ M`, `map_domain f v : β →₀ M`
is the finitely supported function whose value at `a : β` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α → β) (v : α →₀ M) : β →₀ M :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α → β} (hf : function.injective f) (x : α →₀ M) (a : α) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ assume h, rw [not_mem_support_iff.1 h, single_zero, zero_apply] }
end
lemma map_domain_notin_range {f : α → β} (x : α →₀ M) (a : β) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v :=
sum_single _
lemma map_domain_comp {f : α → β} {g : β → γ} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → β} {a : α} {b : M} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → β} : map_domain f (0 : α →₀ M) = (0 : β →₀ M) :=
sum_zero_index
lemma map_domain_congr {f g : α → β} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → β} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → β} {s : finset ι} {v : ι → α →₀ M} :
map_domain f (∑ i in s, v i) = ∑ i in s, map_domain f (v i) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero N] {f : α → β} {s : α →₀ N} {v : α → N → α →₀ M} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → β} {s : α →₀ M} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(map_domain f s).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α ↪ β) (v : α →₀ M) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply f.injective, emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
@[to_additive]
lemma prod_map_domain_index_inj [comm_monoid N] {f : α → β} {s : α →₀ M}
{h : β → M → N} (hf : function.injective f) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
by rw [←function.embedding.coe_fn_mk f hf, ←emb_domain_eq_map_domain, prod_emb_domain]
lemma map_domain_injective {f : α → β} (hf : function.injective f) :
function.injective (map_domain f : (α →₀ M) → (β →₀ M)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α → β`, `l : β →₀ M` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function
from `α` to `M` given by composing `l` with `f`. -/
def comap_domain [has_zero M] (f : α → β) (l : β →₀ M) (hf : set.inj_on f (f ⁻¹' ↑l.support)) :
α →₀ M :=
{ support := l.support.preimage f hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
@[simp]
lemma comap_domain_apply [has_zero M] (f : α → β) (l : β →₀ M)
(hf : set.inj_on f (f ⁻¹' ↑l.support)) (a : α) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain [has_zero M] [add_comm_monoid N]
(f : α → β) (l : β →₀ M) (g : β → M → N)
(hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
(comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g :=
begin
simp only [sum, comap_domain_apply, (∘)],
simp [comap_domain, finset.sum_preimage_of_bij f _ _ (λ x, g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero [add_comm_monoid M]
(f : α → β) (l : β →₀ M) (hf : set.bij_on f (f ⁻¹' ↑l.support) ↑l.support) :
comap_domain f l hf.inj_on = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext_iff, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain [add_comm_monoid M] (f : α → β) (l : β →₀ M)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (hf.inj_on _)) = l :=
begin
ext a,
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) }
end
end comap_domain
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero M] (p : α → Prop) (f : α →₀ M)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ M) : α →₀ M :=
{ to_fun := λ a, if p a then f a else 0,
support := f.support.filter (λ a, p a),
mem_support_to_fun := λ a, by split_ifs; { simp only [h, mem_filter, mem_support_iff], tauto } }
lemma filter_apply (a : α) : f.filter p a = if p a then f a else 0 := rfl
lemma filter_eq_indicator : ⇑(f.filter p) = set.indicator {x | p x} f := rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p := rfl
lemma filter_zero : (0 : α →₀ M).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : M} (h : p a) : (single a b).filter p = single a b :=
coe_fn_injective $ by simp [filter_eq_indicator, set.subset_def, mem_support_single, h]
@[simp] lemma filter_single_of_neg
{a : α} {b : M} (h : ¬ p a) : (single a b).filter p = 0 :=
ext $ by simp [filter_eq_indicator, single_apply_eq_zero, @imp.swap (p _), h]
end has_zero
lemma filter_pos_add_filter_neg [add_monoid M] (f : α →₀ M) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
coe_fn_injective $ set.indicator_self_add_compl {x | p x} f
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero M]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ M) : finset M := finset.image f f.support
theorem mem_frange {f : α →₀ M} {y : M} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ M} : (0:M) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : M} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
/-! ### Declarations about `subtype_domain` -/
section subtype_domain
section zero
variables [has_zero M] {p : α → Prop}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ M) : (subtype p →₀ M) :=
⟨f.support.subtype p, f ∘ coe, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ M} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ M} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ M) = 0 :=
rfl
lemma subtype_domain_eq_zero_iff' {f : α →₀ M} :
f.subtype_domain p = 0 ↔ ∀ x, p x → f x = 0 :=
by simp_rw [← support_eq_empty, support_subtype_domain, subtype_eq_empty, not_mem_support_iff]
lemma subtype_domain_eq_zero_iff {f : α →₀ M} (hf : ∀ x ∈ f.support , p x) :
f.subtype_domain p = 0 ↔ f = 0 :=
subtype_domain_eq_zero_iff'.trans ⟨λ H, ext $ λ x,
if hx : p x then H x hx else not_mem_support_iff.1 $ mt (hf x) hx, λ H x _, by simp [H]⟩
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid N] {v : α →₀ M}
{h : α → M → N} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid M] {p : α → Prop} {v v' : α →₀ M}
@[simp] lemma subtype_domain_add {v v' : α →₀ M} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ M) → subtype p →₀ M) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
/-- `finsupp.filter` as an `add_monoid_hom`. -/
def filter_add_hom (p : α → Prop) : (α →₀ M) →+ (α →₀ M) :=
{ to_fun := filter p,
map_zero' := filter_zero p,
map_add' := λ f g, coe_fn_injective $ set.indicator_add {x | p x} f g }
@[simp] lemma filter_add {v v' : α →₀ M} : (v + v').filter p = v.filter p + v'.filter p :=
(filter_add_hom p).map_add v v'
end monoid
section comm_monoid
variables [add_comm_monoid M] {p : α → Prop}
lemma subtype_domain_sum {s : finset ι} {h : ι → α →₀ M} :
(∑ c in s, h c).subtype_domain p = ∑ c in s, (h c).subtype_domain p :=
eq.symm (s.sum_hom _)
lemma subtype_domain_finsupp_sum [has_zero N] {s : β →₀ N} {h : β → N → α →₀ M} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset ι) (f : ι → α →₀ M) :
(∑ a in s, f a).filter p = ∑ a in s, filter p (f a) :=
(filter_add_hom p : (α →₀ M) →+ _).map_sum f s
lemma filter_eq_sum (p : α → Prop) (f : α →₀ M) :
f.filter p = ∑ i in f.support.filter p, single i (f i) :=
(f.filter p).sum_single.symm.trans $ finset.sum_congr rfl $
λ x hx, by rw [filter_apply_pos _ _ (mem_filter.1 hx).2]
end comm_monoid
section group
variables [add_group G] {p : α → Prop} {v v' : α →₀ G}
@[simp] lemma subtype_domain_neg : (- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
/-! ### Declarations relating `finsupp` to `multiset` -/
section multiset
/-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. We define this function as an `add_equiv`. -/
def to_multiset : (α →₀ ℕ) ≃+ multiset α :=
{ to_fun := λ f, f.sum (λa n, n •ℕ {a}),
inv_fun := λ s, ⟨s.to_finset, λ a, s.count a, λ a, by simp⟩,
left_inv := λ f, ext $ λ a,
suffices (if f a = 0 then 0 else f a) = f a,
by simpa [finsupp.sum, multiset.count_sum', multiset.count_cons],
by split_ifs with h; [rw h, refl],
right_inv := λ s, by simp [finsupp.sum],
map_add' := λ f g, sum_add_index (λ a, zero_nsmul _) (λ a, add_nsmul _) }
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
to_multiset.map_add m n
lemma to_multiset_apply (f : α →₀ ℕ) : f.to_multiset = f.sum (λ a n, n •ℕ {a}) := rfl
@[simp] lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = n •ℕ {a} :=
by rw [to_multiset_apply, sum_single_index]; apply zero_nsmul
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
by simp [to_multiset_apply, add_monoid_hom.map_finsupp_sum, function.id_def]
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_nsmul (multiset.map g)],
refl }
end
@[simp] lemma prod_to_multiset [comm_monoid M] (f : M →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
@[simp] lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_nsmul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint.mono_left support_single_subset _,
rwa [finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (n •ℕ {x} : multiset α).count a) :
(f.support.sum_hom $ multiset.count a).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x ::ₘ 0 : multiset α).count a) : rfl
... = f a * (a ::ₘ 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
lemma mem_support_multiset_sum [add_comm_monoid M]
{s : multiset (α →₀ M)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ M).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid M]
{s : finset ι} {h : ι → α →₀ M} (a : α) (ha : a ∈ (∑ c in s, h c).support) :
∃ c ∈ s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
@[simp] lemma mem_to_multiset (f : α →₀ ℕ) (i : α) :
i ∈ f.to_multiset ↔ i ∈ f.support :=
by rw [← multiset.count_ne_zero, finsupp.count_to_multiset, finsupp.mem_support_iff]
end multiset
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
variables [add_comm_monoid M] [add_comm_monoid N]
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry (f : (α × β) →₀ M) : α →₀ (β →₀ M) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index (f : (α × β) →₀ M) (g : α → β → M → N)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `M`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `M`. -/
protected def uncurry (f : α →₀ (β →₀ M)) : (α × β) →₀ M :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ M)` and `(α →₀ (β →₀ M))` given by
currying and uncurrying. -/
def finsupp_prod_equiv : ((α × β) →₀ M) ≃ (α →₀ (β →₀ M)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry (f : α × β →₀ M) (p : α → Prop) :
(f.filter (λa:α×β, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum, filter_sum, support_filter,
sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry (f : α × β →₀ M) : f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [group G] [mul_action G α] [add_comm_monoid M]
/--
Scalar multiplication by a group element g,
given by precomposition with the action of g⁻¹ on the domain.
-/
def comap_has_scalar : has_scalar G (α →₀ M) :=
{ smul := λ g f, f.comap_domain (λ a, g⁻¹ • a)
(λ a a' m m' h, by simpa [←mul_smul] using (congr_arg (λ a, g • a) h)) }
local attribute [instance] comap_has_scalar
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is multiplicative in g.
-/
def comap_mul_action : mul_action G (α →₀ M) :=
{ one_smul := λ f, by { ext, dsimp [(•)], simp, },
mul_smul := λ g g' f, by { ext, dsimp [(•)], simp [mul_smul], }, }
local attribute [instance] comap_mul_action
/--
Scalar multiplication by a group element,
given by precomposition with the action of g⁻¹ on the domain,
is additive in the second argument.
-/
def comap_distrib_mul_action :
distrib_mul_action G (α →₀ M) :=
{ smul_zero := λ g, by { ext, dsimp [(•)], simp, },
smul_add := λ g f f', by { ext, dsimp [(•)], simp, }, }
/--
Scalar multiplication by a group element on finitely supported functions on a group,
given by precomposition with the action of g⁻¹. -/
def comap_distrib_mul_action_self :
distrib_mul_action G (G →₀ M) :=
@finsupp.comap_distrib_mul_action G M G _ (mul_action.regular G) _
@[simp]
lemma comap_smul_single (g : G) (a : α) (b : M) :
g • single a b = single (g • a) b :=
begin
ext a',
dsimp [(•)],
by_cases h : g • a = a',
{ subst h, simp [←mul_smul], },
{ simp [single_eq_of_ne h], rw [single_eq_of_ne],
rintro rfl, simpa [←mul_smul] using h, }
end
@[simp]
lemma comap_smul_apply (g : G) (f : α →₀ M) (a : α) :
(g • f) a = f (g⁻¹ • a) := rfl
end
section
instance [semiring R] [add_comm_monoid M] [semimodule R M] : has_scalar R (α →₀ M) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α M)
/-!
Throughout this section, some `semiring` arguments are specified with `{}` instead of `[]`.
See note [implicit instance arguments].
-/
@[simp] lemma smul_apply' {_:semiring R} [add_comm_monoid M] [semimodule R M]
{a : α} {b : R} {v : α →₀ M} : (b • v) a = b • (v a) :=
rfl
instance [semiring R] [add_comm_monoid M] [semimodule R M] : semimodule R (α →₀ M) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, ext $ λ _, zero_smul _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
variables {α M} {R}
lemma support_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M] {b : R} {g : α →₀ M} :
(b • g).support ⊆ g.support :=
λ a, by simp only [smul_apply', mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {p : α → Prop}
@[simp] lemma filter_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M]
{b : R} {v : α →₀ M} : (b • v).filter p = b • v.filter p :=
coe_fn_injective $ set.indicator_smul {x | p x} b v
end
lemma map_domain_smul {_ : semiring R} [add_comm_monoid M] [semimodule R M]
{f : α → β} (b : R) (v : α →₀ M) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] },
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {_ : semiring R} [add_comm_monoid M] [semimodule R M]
(c : R) (a : α) (b : M) : c • finsupp.single a b = finsupp.single a (c • b) :=
map_range_single
@[simp] lemma smul_single' {_ : semiring R}
(c : R) (a : α) (b : R) : c • finsupp.single a b = finsupp.single a (c * b) :=
smul_single _ _ _
lemma smul_single_one [semiring R] (a : α) (b : R) : b • single a 1 = single a b :=
by rw [smul_single, smul_eq_mul, mul_one]
end
@[simp] lemma smul_apply [semiring R] {a : α} {b : R} {v : α →₀ R} :
(b • v) a = b • (v a) :=
rfl
lemma sum_smul_index [semiring R] [add_comm_monoid M] {g : α →₀ R} {b : R} {h : α → R → M}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
lemma sum_smul_index' [semiring R] [add_comm_monoid M] [semimodule R M] [add_comm_monoid N]
{g : α →₀ M} {b : R} {h : α → M → N} (h0 : ∀i, h i 0 = 0) :
(b • g).sum h = g.sum (λi c, h i (b • c)) :=
finsupp.sum_map_range_index h0
section
variables [semiring R] [semiring S]
lemma sum_mul (b : S) (s : α →₀ R) {f : α → R → S} :
(s.sum f) * b = s.sum (λ a c, (f a c) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : S) (s : α →₀ R) {f : α → R → S} :
b * (s.sum f) = s.sum (λ a c, b * (f a c)) :=
by simp only [finsupp.sum, finset.mul_sum]
instance unique_of_right [subsingleton R] : unique (α →₀ R) :=
{ uniq := λ l, ext $ λ i, subsingleton.elim _ _,
.. finsupp.inhabited }
end
/-- Given an `add_comm_monoid M` and `s : set α`, `restrict_support_equiv s M` is the `equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
def restrict_support_equiv (s : set α) (M : Type*) [add_comm_monoid M] :
{f : α →₀ M // ↑f.support ⊆ s } ≃ (s →₀ M):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
/-- Given `add_comm_monoid M` and `e : α ≃ β`, `dom_congr e` is the corresponding `equiv` between
`α →₀ M` and `β →₀ M`. -/
protected def dom_congr [add_comm_monoid M] (e : α ≃ β) : (α →₀ M) ≃+ (β →₀ M) :=
{ to_fun := map_domain e,
inv_fun := map_domain e.symm,
left_inv := begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
right_inv := begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end,
map_add' := λ a b, map_domain_add, }
end finsupp
namespace finsupp
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero M] (l : (Σ i, αs i) →₀ M)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `M` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `M`. -/
def split (i : ι) : αs i →₀ M :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def split_support : finset ι := l.support.image sigma.fst
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def,
← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty],
simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right,
mem_support_iff, sigma.exists, ne.def]
end
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def split_comp [has_zero N] (g : Π i, (αs i →₀ M) → N)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ N :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw [mem_split_support_iff_nonzero, not_iff_not, hg],
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp only [finset.ext_iff, split_support, split, comap_domain, mem_image,
mem_preimage, sigma.forall, mem_sigma]; tauto
lemma sigma_sum [add_comm_monoid N] (f : (Σ (i : ι), αs i) → M → N) :
l.sum f = ∑ i in split_support l, (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b) :=
by simp only [sum, sigma_support, sum_sigma, split_apply]
end sigma
end finsupp
/-! ### Declarations relating `multiset` to `finsupp` -/
namespace multiset
/-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
def to_finsupp : multiset α ≃+ (α →₀ ℕ) := finsupp.to_multiset.symm
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset :=
rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
to_finsupp s a = s.count a :=
rfl
lemma to_finsupp_zero : to_finsupp (0 : multiset α) = 0 := add_equiv.map_zero _
lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
to_finsupp.map_add s t
@[simp] lemma to_finsupp_singleton (a : α) : to_finsupp (a ::ₘ 0) = finsupp.single a 1 :=
finsupp.to_multiset.symm_apply_eq.2 $ by simp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
finsupp.to_multiset.apply_symm_apply s
lemma to_finsupp_eq_iff {s : multiset α} {f : α →₀ ℕ} : s.to_finsupp = f ↔ s = f.to_multiset :=
finsupp.to_multiset.symm_apply_eq
end multiset
@[simp] lemma finsupp.to_multiset_to_finsupp (f : α →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
finsupp.to_multiset.symm_apply_apply f
/-! ### Declarations about order(ed) instances on `finsupp` -/
namespace finsupp
instance [preorder M] [has_zero M] : preorder (α →₀ M) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order M] [has_zero M] : partial_order (α →₀ M) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_add_comm_monoid M] : add_left_cancel_semigroup (α →₀ M) :=
{ add_left_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid M] : add_right_cancel_semigroup (α →₀ M) :=
{ add_right_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_add_comm_monoid M] : ordered_cancel_add_comm_monoid (α →₀ M) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_def [preorder M] [has_zero M] {f g : α →₀ M} : f ≤ g ↔ ∀ x, f x ≤ g x := iff.rfl
lemma le_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
@[simp] lemma add_eq_zero_iff [canonically_ordered_add_monoid M] (f g : α →₀ M) :
f + g = 0 ↔ f = 0 ∧ g = 0 :=
by simp [ext_iff, forall_and_distrib]
/-- `finsupp.to_multiset` as an order isomorphism. -/
def order_iso_multiset : (α →₀ ℕ) ≃o multiset α :=
{ to_equiv := to_multiset.to_equiv,
map_rel_iff' := λ f g, by simp [multiset.le_iff_count, le_def] }
@[simp] lemma coe_order_iso_multiset : ⇑(@order_iso_multiset α) = to_multiset := rfl
@[simp] lemma coe_order_iso_multiset_symm :
⇑(@order_iso_multiset α).symm = multiset.to_finsupp := rfl
lemma to_multiset_strict_mono : strict_mono (@to_multiset α) :=
order_iso_multiset.strict_mono
lemma sum_id_lt_of_lt (m n : α →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (α)
/-- The order on `σ →₀ ℕ` is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (α →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (α →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {α}
/-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of
`s : α →₀ ℕ` consists of all pairs `(t₁, t₂) : (α →₀ ℕ) × (α →₀ ℕ)` such that `t₁ + t₂ = s`.
The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/
def antidiagonal (f : α →₀ ℕ) : ((α →₀ ℕ) × (α →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
@[simp] lemma mem_antidiagonal_support {f : α →₀ ℕ} {p : (α →₀ ℕ) × (α →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
rcases p with ⟨p₁, p₂⟩,
simp [antidiagonal, ← and.assoc, ← finsupp.to_multiset.apply_eq_iff_eq]
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : α →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : α →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa only [mem_antidiagonal_support, add_comm, prod.swap] using hf
/-- Let `n : α →₀ ℕ` be a finitely supported function.
The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`,
is a finite set. -/
lemma finite_le_nat (n : α →₀ ℕ) : set.finite {m | m ≤ n} :=
begin
let I := {i // i ∈ n.support},
let k : ℕ := ∑ i in n.support, n i,
let f : (α →₀ ℕ) → (I → fin (k + 1)) := λ m i, m i,
have hf : ∀ m ≤ n, ∀ i, (f m i : ℕ) = m i,
{ intros m hm i,
apply fin.coe_coe_of_lt,
calc m i ≤ n i : hm i
... < k + 1 : nat.lt_succ_iff.mpr (single_le_sum (λ _ _, nat.zero_le _) i.2) },
have f_im : set.finite (f '' {m | m ≤ n}) := set.finite.of_fintype _,
suffices f_inj : set.inj_on f {m | m ≤ n},
{ exact set.finite_of_finite_image f_inj f_im },
intros m₁ h₁ m₂ h₂ h,
ext i,
by_cases hi : i ∈ n.support,
{ replace h := congr_fun h ⟨i, hi⟩,
rwa [fin.ext_iff, hf m₁ h₁, hf m₂ h₂] at h },
{ rw not_mem_support_iff at hi,
specialize h₁ i,
specialize h₂ i,
rw [hi, nat.le_zero_iff] at h₁ h₂,
rw [h₁, h₂] }
end
/-- Let `n : α →₀ ℕ` be a finitely supported function.
The set of `m : α →₀ ℕ` that are coordinatewise less than or equal to `n`,
but not equal to `n` everywhere, is a finite set. -/
lemma finite_lt_nat (n : α →₀ ℕ) : set.finite {m | m < n} :=
(finite_le_nat n).subset $ λ m, le_of_lt
end finsupp
namespace multiset
lemma to_finsuppstrict_mono : strict_mono (@to_finsupp α) :=
finsupp.order_iso_multiset.symm.strict_mono
end multiset
|
da3d4aa1c6c6a73155611923fac933067e2e434e | c777c32c8e484e195053731103c5e52af26a25d1 | /src/topology/instances/rat_lemmas.lean | fe0059dec2da3140d7742c1ffc6b56555b101ffb | [
"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 | 3,277 | lean | /-
Copyright (c) 2022 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import topology.instances.irrational
import topology.instances.rat
import topology.alexandroff
/-!
# Additional lemmas about the topology on rational numbers
The structure of a metric space on `ℚ` (`rat.metric_space`) is introduced elsewhere, induced from
`ℝ`. In this file we prove some properties of this topological space and its one-point
compactification.
## Main statements
- `rat.totally_disconnected_space`: `ℚ` is a totally disconnected space;
- `rat.not_countably_generated_nhds_infty_alexandroff`: the filter of neighbourhoods of infinity in
`alexandroff ℚ` is not countably generated.
## Notation
- `ℚ∞` is used as a local notation for `alexandroff ℚ`
-/
open set metric filter topological_space
open_locale topology alexandroff
local notation `ℚ∞` := alexandroff ℚ
namespace rat
variables {p q : ℚ} {s t : set ℚ}
lemma interior_compact_eq_empty (hs : is_compact s) :
interior s = ∅ :=
dense_embedding_coe_real.to_dense_inducing.interior_compact_eq_empty dense_irrational hs
lemma dense_compl_compact (hs : is_compact s) : dense sᶜ :=
interior_eq_empty_iff_dense_compl.1 (interior_compact_eq_empty hs)
instance cocompact_inf_nhds_ne_bot : ne_bot (cocompact ℚ ⊓ 𝓝 p) :=
begin
refine (has_basis_cocompact.inf (nhds_basis_opens _)).ne_bot_iff.2 _,
rintro ⟨s, o⟩ ⟨hs, hpo, ho⟩, rw inter_comm,
exact (dense_compl_compact hs).inter_open_nonempty _ ho ⟨p, hpo⟩
end
lemma not_countably_generated_cocompact : ¬is_countably_generated (cocompact ℚ) :=
begin
introI H,
rcases exists_seq_tendsto (cocompact ℚ ⊓ 𝓝 0) with ⟨x, hx⟩,
rw tendsto_inf at hx, rcases hx with ⟨hxc, hx0⟩,
obtain ⟨n, hn⟩ : ∃ n : ℕ, x n ∉ insert (0 : ℚ) (range x),
from (hxc.eventually hx0.is_compact_insert_range.compl_mem_cocompact).exists,
exact hn (or.inr ⟨n, rfl⟩)
end
lemma not_countably_generated_nhds_infty_alexandroff :
¬is_countably_generated (𝓝 (∞ : ℚ∞)) :=
begin
introI,
have : is_countably_generated (comap (coe : ℚ → ℚ∞) (𝓝 ∞)), by apply_instance,
rw [alexandroff.comap_coe_nhds_infty, coclosed_compact_eq_cocompact] at this,
exact not_countably_generated_cocompact this
end
lemma not_first_countable_topology_alexandroff :
¬first_countable_topology ℚ∞ :=
by { introI, exact not_countably_generated_nhds_infty_alexandroff infer_instance }
lemma not_second_countable_topology_alexandroff :
¬second_countable_topology ℚ∞ :=
by { introI, exact not_first_countable_topology_alexandroff infer_instance }
instance : totally_disconnected_space ℚ :=
begin
refine ⟨λ s hsu hs x hx y hy, _⟩, clear hsu,
by_contra' H : x ≠ y,
wlog hlt : x < y,
{ exact this s hs y hy x hx H.symm (H.lt_or_lt.resolve_left hlt) },
rcases exists_irrational_btwn (rat.cast_lt.2 hlt) with ⟨z, hz, hxz, hzy⟩,
have := hs.image coe continuous_coe_real.continuous_on,
rw [is_preconnected_iff_ord_connected] at this,
have : z ∈ coe '' s := this.out (mem_image_of_mem _ hx) (mem_image_of_mem _ hy) ⟨hxz.le, hzy.le⟩,
exact hz (image_subset_range _ _ this)
end
end rat
|
fe6b70321126990204813337abc0df59a6b7b3d4 | 32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7 | /src/Lean/Attributes.lean | 90116861a9831709e547e569565e059c1de48866 | [
"Apache-2.0"
] | permissive | walterhu1015/lean4 | b2c71b688975177402758924eaa513475ed6ce72 | 2214d81e84646a905d0b20b032c89caf89c737ad | refs/heads/master | 1,671,342,096,906 | 1,599,695,985,000 | 1,599,695,985,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 20,863 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Scopes
import Lean.Syntax
import Lean.CoreM
namespace Lean
inductive AttributeApplicationTime
| afterTypeChecking | afterCompilation | beforeElaboration
def AttributeApplicationTime.beq : AttributeApplicationTime → AttributeApplicationTime → Bool
| AttributeApplicationTime.afterTypeChecking, AttributeApplicationTime.afterTypeChecking => true
| AttributeApplicationTime.afterCompilation, AttributeApplicationTime.afterCompilation => true
| AttributeApplicationTime.beforeElaboration, AttributeApplicationTime.beforeElaboration => true
| _, _ => false
instance AttributeApplicationTime.hasBeq : HasBeq AttributeApplicationTime := ⟨AttributeApplicationTime.beq⟩
-- TODO: after we delete the old frontend, we should use `EIO` with a richer exception kind at AttributeImpl.
-- We must perform a similar modification at `PersistentEnvExtension`
structure AttributeImpl :=
(name : Name)
(descr : String)
(add (decl : Name) (args : Syntax) (persistent : Bool) : CoreM Unit)
/-
(addScoped (env : Environment) (decl : Name) (args : Syntax) : IO Environment
:= throw (IO.userError ("attribute '" ++ toString name ++ "' does not support scopes")))
(erase (env : Environment) (decl : Name) (persistent : Bool) : IO Environment
:= throw (IO.userError ("attribute '" ++ toString name ++ "' does not support removal")))
(activateScoped (env : Environment) (scope : Name) : IO Environment := pure env)
(pushScope (env : Environment) : IO Environment := pure env)
(popScope (env : Environment) : IO Environment := pure env)
-/
(applicationTime := AttributeApplicationTime.afterTypeChecking)
instance AttributeImpl.inhabited : Inhabited AttributeImpl :=
⟨{ name := arbitrary _, descr := arbitrary _, add := fun env _ _ _ => pure () }⟩
open Std (PersistentHashMap)
def mkAttributeMapRef : IO (IO.Ref (PersistentHashMap Name AttributeImpl)) :=
IO.mkRef {}
@[init mkAttributeMapRef]
constant attributeMapRef : IO.Ref (PersistentHashMap Name AttributeImpl) := arbitrary _
/- Low level attribute registration function. -/
def registerBuiltinAttribute (attr : AttributeImpl) : IO Unit := do
m ← attributeMapRef.get;
when (m.contains attr.name) $ throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attr.name ++ "' has already been used"));
initializing ← IO.initializing;
unless initializing $ throw (IO.userError ("failed to register attribute, attributes can only be registered during initialization"));
attributeMapRef.modify (fun m => m.insert attr.name attr)
abbrev AttributeImplBuilder := List DataValue → Except String AttributeImpl
abbrev AttributeImplBuilderTable := Std.HashMap Name AttributeImplBuilder
def mkAttributeImplBuilderTable : IO (IO.Ref AttributeImplBuilderTable) := IO.mkRef {}
@[init mkAttributeImplBuilderTable] constant attributeImplBuilderTableRef : IO.Ref AttributeImplBuilderTable := arbitrary _
def registerAttributeImplBuilder (builderId : Name) (builder : AttributeImplBuilder) : IO Unit := do
table ← attributeImplBuilderTableRef.get;
when (table.contains builderId) $ throw (IO.userError ("attribute implementation builder '" ++ toString builderId ++ "' has already been declared"));
attributeImplBuilderTableRef.modify $ fun table => table.insert builderId builder
def mkAttributeImplOfBuilder (builderId : Name) (args : List DataValue) : IO AttributeImpl := do
table ← attributeImplBuilderTableRef.get;
match table.find? builderId with
| none => throw (IO.userError ("unknown attribute implementation builder '" ++ toString builderId ++ "'"))
| some builder => IO.ofExcept $ builder args
inductive AttributeExtensionOLeanEntry
| decl (declName : Name) -- `declName` has type `AttributeImpl`
| builder (builderId : Name) (args : List DataValue)
structure AttributeExtensionState :=
(newEntries : List AttributeExtensionOLeanEntry := [])
(map : PersistentHashMap Name AttributeImpl)
abbrev AttributeExtension := PersistentEnvExtension AttributeExtensionOLeanEntry (AttributeExtensionOLeanEntry × AttributeImpl) AttributeExtensionState
instance AttributeExtensionState.inhabited : Inhabited AttributeExtensionState := ⟨{ map := {} }⟩
private def AttributeExtension.mkInitial : IO AttributeExtensionState := do
map ← attributeMapRef.get;
pure { map := map }
unsafe def mkAttributeImplOfConstantUnsafe (env : Environment) (declName : Name) : Except String AttributeImpl :=
match env.find? declName with
| none => throw ("unknow constant '" ++ toString declName ++ "'")
| some info =>
match info.type with
| Expr.const `Lean.AttributeImpl _ _ => env.evalConst AttributeImpl declName
| _ => throw ("unexpected attribute implementation type at '" ++ toString declName ++ "' (`AttributeImpl` expected")
@[implementedBy mkAttributeImplOfConstantUnsafe]
constant mkAttributeImplOfConstant (env : Environment) (declName : Name) : Except String AttributeImpl := arbitrary _
def mkAttributeImplOfEntry (env : Environment) (e : AttributeExtensionOLeanEntry) : IO AttributeImpl :=
match e with
| AttributeExtensionOLeanEntry.decl declName => IO.ofExcept $ mkAttributeImplOfConstant env declName
| AttributeExtensionOLeanEntry.builder builderId args => mkAttributeImplOfBuilder builderId args
private def AttributeExtension.addImported (env : Environment) (es : Array (Array AttributeExtensionOLeanEntry)) : IO AttributeExtensionState := do
map ← attributeMapRef.get;
map ← es.foldlM
(fun map entries =>
entries.foldlM
(fun (map : PersistentHashMap Name AttributeImpl) entry => do
attrImpl ← mkAttributeImplOfEntry env entry;
pure $ map.insert attrImpl.name attrImpl)
map)
map;
pure { map := map }
private def AttributeExtension.addEntry (s : AttributeExtensionState) (e : AttributeExtensionOLeanEntry × AttributeImpl) : AttributeExtensionState :=
{ s with map := s.map.insert e.2.name e.2, newEntries := e.1 :: s.newEntries }
def mkAttributeExtension : IO AttributeExtension :=
registerPersistentEnvExtension {
name := `attrExt,
mkInitial := AttributeExtension.mkInitial,
addImportedFn := AttributeExtension.addImported,
addEntryFn := AttributeExtension.addEntry,
exportEntriesFn := fun s => s.newEntries.reverse.toArray,
statsFn := fun s => format "number of local entries: " ++ format s.newEntries.length
}
@[init mkAttributeExtension]
def attributeExtension : AttributeExtension := arbitrary _
/- Return true iff `n` is the name of a registered attribute. -/
@[export lean_is_attribute]
def isBuiltinAttribute (n : Name) : IO Bool := do
m ← attributeMapRef.get; pure (m.contains n)
/- Return the name of all registered attributes. -/
def getBuiltinAttributeNames : IO (List Name) := do
m ← attributeMapRef.get; pure $ m.foldl (fun r n _ => n::r) []
def getBuiltinAttributeImpl (attrName : Name) : IO AttributeImpl := do
m ← attributeMapRef.get;
match m.find? attrName with
| some attr => pure attr
| none => throw (IO.userError ("unknown attribute '" ++ toString attrName ++ "'"))
@[export lean_attribute_application_time]
def getBuiltinAttributeApplicationTime (n : Name) : IO AttributeApplicationTime := do
attr ← getBuiltinAttributeImpl n;
pure attr.applicationTime
def isAttribute (env : Environment) (attrName : Name) : Bool :=
(attributeExtension.getState env).map.contains attrName
def getAttributeNames (env : Environment) : List Name :=
let m := (attributeExtension.getState env).map;
m.foldl (fun r n _ => n::r) []
def getAttributeImpl (env : Environment) (attrName : Name) : Except String AttributeImpl :=
let m := (attributeExtension.getState env).map;
match m.find? attrName with
| some attr => pure attr
| none => throw ("unknown attribute '" ++ toString attrName ++ "'")
def registerAttributeOfDecl (env : Environment) (attrDeclName : Name) : Except String Environment := do
attrImpl ← mkAttributeImplOfConstant env attrDeclName;
if isAttribute env attrImpl.name then
throw ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used")
else
pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.decl attrDeclName, attrImpl)
def registerAttributeOfBuilder (env : Environment) (builderId : Name) (args : List DataValue) : IO Environment := do
attrImpl ← mkAttributeImplOfBuilder builderId args;
if isAttribute env attrImpl.name then
throw (IO.userError ("invalid builtin attribute declaration, '" ++ toString attrImpl.name ++ "' has already been used"))
else
pure $ attributeExtension.addEntry env (AttributeExtensionOLeanEntry.builder builderId args, attrImpl)
namespace Environment
/- Add attribute `attr` to declaration `decl` with arguments `args`. If `persistent == true`, then attribute is saved on .olean file.
It throws an error when
- `attr` is not the name of an attribute registered in the system.
- `attr` does not support `persistent == false`.
- `args` is not valid for `attr`. -/
@[export lean_add_attribute]
def addAttribute (env : Environment) (decl : Name) (attrName : Name) (args : Syntax := Syntax.missing) (persistent := true) : IO Environment := do
attr ← IO.ofExcept $ getAttributeImpl env attrName;
(_, s) ← (attr.add decl args persistent).toIO {} { env := env };
pure s.env
/-
/- Add a scoped attribute `attr` to declaration `decl` with arguments `args` and scope `decl.getPrefix`.
Scoped attributes are always persistent.
It returns `Except.error` when
- `attr` is not the name of an attribute registered in the system.
- `attr` does not support scoped attributes.
- `args` is not valid for `attr`.
Remark: the attribute will not be activated if `decl` is not inside the current namespace `env.getNamespace`. -/
@[export lean_add_scoped_attribute]
def addScopedAttribute (env : Environment) (decl : Name) (attrName : Name) (args : Syntax := Syntax.missing) : IO Environment := do
attr ← getAttributeImpl attrName;
attr.addScoped env decl args
/- Remove attribute `attr` from declaration `decl`. The effect is the current scope.
It returns `Except.error` when
- `attr` is not the name of an attribute registered in the system.
- `attr` does not support erasure.
- `args` is not valid for `attr`. -/
@[export lean_erase_attribute]
def eraseAttribute (env : Environment) (decl : Name) (attrName : Name) (persistent := true) : IO Environment := do
attr ← getAttributeImpl attrName;
attr.erase env decl persistent
/- Activate the scoped attribute `attr` for all declarations in scope `scope`.
We use this function to implement the command `open foo`. -/
@[export lean_activate_scoped_attribute]
def activateScopedAttribute (env : Environment) (attrName : Name) (scope : Name) : IO Environment := do
attr ← getAttributeImpl attrName;
attr.activateScoped env scope
/- Activate all scoped attributes at `scope` -/
@[export lean_activate_scoped_attributes]
def activateScopedAttributes (env : Environment) (scope : Name) : IO Environment := do
attrs ← attributeArrayRef.get;
attrs.foldlM (fun env attr => attr.activateScoped env scope) env
-/
/- We use this function to implement commands `namespace foo` and `section foo`.
It activates scoped attributes in the new resulting namespace. -/
@[export lean_push_scope]
def pushScope (env : Environment) (header : Name) (isNamespace : Bool) : IO Environment := do
let env := env.pushScopeCore header isNamespace;
let ns := env.getNamespace;
-- attrs ← attributeArrayRef.get;
-- attrs.foldlM (fun env attr => do env ← attr.pushScope env; if isNamespace then attr.activateScoped env ns else pure env) env
pure env
/- We use this function to implement commands `end foo` for closing namespaces and sections. -/
@[export lean_pop_scope]
def popScope (env : Environment) : IO Environment := do
let env := env.popScopeCore;
-- attrs ← attributeArrayRef.get;
-- attrs.foldlM (fun env attr => attr.popScope env) env
pure env
end Environment
/--
Tag attributes are simple and efficient. They are useful for marking declarations in the modules where
they were defined.
The startup cost for this kind of attribute is very small since `addImportedFn` is a constant function.
They provide the predicate `tagAttr.hasTag env decl` which returns true iff declaration `decl`
is tagged in the environment `env`. -/
structure TagAttribute :=
(attr : AttributeImpl)
(ext : PersistentEnvExtension Name Name NameSet)
def registerTagAttribute (name : Name) (descr : String) (validate : Name → CoreM Unit := fun _ => pure ()) : IO TagAttribute := do
ext : PersistentEnvExtension Name Name NameSet ← registerPersistentEnvExtension {
name := name,
mkInitial := pure {},
addImportedFn := fun _ _ => pure {},
addEntryFn := fun (s : NameSet) n => s.insert n,
exportEntriesFn := fun es =>
let r : Array Name := es.fold (fun a e => a.push e) #[];
r.qsort Name.quickLt,
statsFn := fun s => "tag attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
};
let attrImpl : AttributeImpl := {
name := name,
descr := descr,
add := fun decl args persistent => do
when args.hasArgs $ throwError ("invalid attribute '" ++ toString name ++ "', unexpected argument");
unless persistent $ throwError ("invalid attribute '" ++ toString name ++ "', must be persistent");
env ← getEnv;
unless (env.getModuleIdxFor? decl).isNone $
throwError ("invalid attribute '" ++ toString name ++ "', declaration is in an imported module");
validate decl;
env ← getEnv;
setEnv $ ext.addEntry env decl
};
registerBuiltinAttribute attrImpl;
pure { attr := attrImpl, ext := ext }
namespace TagAttribute
instance : Inhabited TagAttribute := ⟨{attr := arbitrary _, ext := arbitrary _}⟩
def hasTag (attr : TagAttribute) (env : Environment) (decl : Name) : Bool :=
match env.getModuleIdxFor? decl with
| some modIdx => (attr.ext.getModuleEntries env modIdx).binSearchContains decl Name.quickLt
| none => (attr.ext.getState env).contains decl
end TagAttribute
/--
A `TagAttribute` variant where we can attach parameters to attributes.
It is slightly more expensive and consumes a little bit more memory than `TagAttribute`.
They provide the function `pAttr.getParam env decl` which returns `some p` iff declaration `decl`
contains the attribute `pAttr` with parameter `p`. -/
structure ParametricAttribute (α : Type) :=
(attr : AttributeImpl)
(ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α))
def registerParametricAttribute {α : Type} [Inhabited α] (name : Name) (descr : String)
(getParam : Name → Syntax → CoreM α)
(afterSet : Name → α → CoreM Unit := fun env _ _ => pure ())
(appTime := AttributeApplicationTime.afterTypeChecking)
: IO (ParametricAttribute α) := do
ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := name,
mkInitial := pure {},
addImportedFn := fun _ _ => pure {},
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2,
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[];
r.qsort (fun a b => Name.quickLt a.1 b.1),
statsFn := fun s => "parametric attribute" ++ Format.line ++ "number of local entries: " ++ format s.size
};
let attrImpl : AttributeImpl := {
name := name,
descr := descr,
applicationTime := appTime,
add := fun decl args persistent => do
unless persistent $ throwError ("invalid attribute '" ++ toString name ++ "', must be persistent");
env ← getEnv;
unless (env.getModuleIdxFor? decl).isNone $
throwError ("invalid attribute '" ++ toString name ++ "', declaration is in an imported module");
val ← getParam decl args;
let env' := ext.addEntry env (decl, val);
setEnv env';
catch (afterSet decl val) (fun _ => setEnv env)
};
registerBuiltinAttribute attrImpl;
pure { attr := attrImpl, ext := ext }
namespace ParametricAttribute
instance {α : Type} : Inhabited (ParametricAttribute α) := ⟨{attr := arbitrary _, ext := arbitrary _}⟩
def getParam {α : Type} [Inhabited α] (attr : ParametricAttribute α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setParam {α : Type} (attr : ParametricAttribute α) (env : Environment) (decl : Name) (param : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, declaration is in an imported module")
else if ((attr.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attr.attr.name ++ "'.setParam, attribute has already been set")
else
Except.ok (attr.ext.addEntry env (decl, param))
end ParametricAttribute
/-
Given a list `[a₁, ..., a_n]` of elements of type `α`, `EnumAttributes` provides an attribute `Attr_i` for
associating a value `a_i` with an declaration. `α` is usually an enumeration type.
Note that whenever we register an `EnumAttributes`, we create `n` attributes, but only one environment extension. -/
structure EnumAttributes (α : Type) :=
(attrs : List AttributeImpl)
(ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α))
def registerEnumAttributes {α : Type} [Inhabited α] (extName : Name) (attrDescrs : List (Name × String × α))
(validate : Name → α → CoreM Unit := fun _ _ => pure ())
(applicationTime := AttributeApplicationTime.afterTypeChecking) : IO (EnumAttributes α) := do
ext : PersistentEnvExtension (Name × α) (Name × α) (NameMap α) ← registerPersistentEnvExtension {
name := extName,
mkInitial := pure {},
addImportedFn := fun _ _ => pure {},
addEntryFn := fun (s : NameMap α) (p : Name × α) => s.insert p.1 p.2,
exportEntriesFn := fun m =>
let r : Array (Name × α) := m.fold (fun a n p => a.push (n, p)) #[];
r.qsort (fun a b => Name.quickLt a.1 b.1),
statsFn := fun s => "enumeration attribute extension" ++ Format.line ++ "number of local entries: " ++ format s.size
};
let attrs := attrDescrs.map $ fun ⟨name, descr, val⟩ => {
name := name,
descr := descr,
applicationTime := applicationTime,
add := (fun decl args persistent => do
unless persistent $ throwError ("invalid attribute '" ++ toString name ++ "', must be persistent");
env ← getEnv;
unless (env.getModuleIdxFor? decl).isNone $
throwError ("invalid attribute '" ++ toString name ++ "', declaration is in an imported module");
validate decl val;
setEnv $ ext.addEntry env (decl, val))
: AttributeImpl
};
attrs.forM registerBuiltinAttribute;
pure { ext := ext, attrs := attrs }
namespace EnumAttributes
instance {α : Type} : Inhabited (EnumAttributes α) := ⟨{attrs := [], ext := arbitrary _}⟩
def getValue {α : Type} [Inhabited α] (attr : EnumAttributes α) (env : Environment) (decl : Name) : Option α :=
match env.getModuleIdxFor? decl with
| some modIdx =>
match (attr.ext.getModuleEntries env modIdx).binSearch (decl, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with
| some (_, val) => some val
| none => none
| none => (attr.ext.getState env).find? decl
def setValue {α : Type} (attrs : EnumAttributes α) (env : Environment) (decl : Name) (val : α) : Except String Environment :=
if (env.getModuleIdxFor? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, declaration is in an imported module")
else if ((attrs.ext.getState env).find? decl).isSome then
Except.error ("invalid '" ++ toString attrs.ext.name ++ "'.setValue, attribute has already been set")
else
Except.ok (attrs.ext.addEntry env (decl, val))
end EnumAttributes
/--
Helper function for converting a Syntax object representing attribute parameters into an identifier.
It returns `none` if the parameter is not a simple identifier.
Remark: in the future, attributes should define their own parsers, and we should use `match_syntax` to
decode the Syntax object. -/
def attrParamSyntaxToIdentifier (s : Syntax) : Option Name :=
match s with
| Syntax.node k args =>
if k == nullKind && args.size == 1 then match args.get! 0 with
| Syntax.ident _ _ id _ => some id
| _ => none
else
none
| _ => none
end Lean
|
27063cb67be4d48f2de4625bd21f3a5ecb3264e3 | ff5230333a701471f46c57e8c115a073ebaaa448 | /library/data/lazy_list.lean | d2c40bd014514c4b99f3bb1240895918c26e0c93 | [
"Apache-2.0"
] | permissive | stanford-cs242/lean | f81721d2b5d00bc175f2e58c57b710d465e6c858 | 7bd861261f4a37326dcf8d7a17f1f1f330e4548c | refs/heads/master | 1,600,957,431,849 | 1,576,465,093,000 | 1,576,465,093,000 | 225,779,423 | 0 | 3 | Apache-2.0 | 1,575,433,936,000 | 1,575,433,935,000 | null | UTF-8 | Lean | false | false | 2,230 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
universes u v w
inductive lazy_list (α : Type u) : Type u
| nil {} : lazy_list
| cons (hd : α) (tl : thunk lazy_list) : lazy_list
namespace lazy_list
variables {α : Type u} {β : Type v} {δ : Type w}
def singleton : α → lazy_list α
| a := cons a nil
def of_list : list α → lazy_list α
| [] := nil
| (h::t) := cons h (of_list t)
def to_list : lazy_list α → list α
| nil := []
| (cons h t) := h :: to_list (t ())
def head [inhabited α] : lazy_list α → α
| nil := default α
| (cons h t) := h
def tail : lazy_list α → lazy_list α
| nil := nil
| (cons h t) := t ()
def append : lazy_list α → thunk (lazy_list α) → lazy_list α
| nil l := l ()
| (cons h t) l := cons h (@append (t ()) l)
def map (f : α → β) : lazy_list α → lazy_list β
| nil := nil
| (cons h t) := cons (f h) (map (t ()))
def map₂ (f : α → β → δ) : lazy_list α → lazy_list β → lazy_list δ
| nil _ := nil
| _ nil := nil
| (cons h₁ t₁) (cons h₂ t₂) := cons (f h₁ h₂) (map₂ (t₁ ()) (t₂ ()))
def zip : lazy_list α → lazy_list β → lazy_list (α × β) :=
map₂ prod.mk
def join : lazy_list (lazy_list α) → lazy_list α
| nil := nil
| (cons h t) := append h (join (t ()))
def for (l : lazy_list α) (f : α → β) : lazy_list β :=
map f l
def approx : nat → lazy_list α → list α
| 0 l := []
| _ nil := []
| (a+1) (cons h t) := h :: approx a (t ())
def filter (p : α → Prop) [decidable_pred p] : lazy_list α → lazy_list α
| nil := nil
| (cons h t) := if p h then cons h (filter (t ())) else filter (t ())
def nth : lazy_list α → nat → option α
| nil n := none
| (cons a l) 0 := some a
| (cons a l) (n+1) := nth (l ()) n
/- This definition must be meta because it uses unbounded recursion -/
meta def iterates (f : α → α) : α → lazy_list α
| x := cons x (iterates (f x))
meta def iota (i : nat) : lazy_list nat :=
iterates nat.succ i
end lazy_list
|
7b5cb3b84c6432f5a5549ca9b230a3f0429d5c30 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebraic_topology/dold_kan/faces.lean | ee62e3c18ed85c385502be05c24abb77ed2b8a1d | [
"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 | 9,209 | 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.homotopies
import tactic.ring_exp
/-!
# Study of face maps for the Dold-Kan correspondence
TODO (@joelriou) continue adding the various files referenced below
In this file, we obtain the technical lemmas that are used in the file
`projections.lean` in order to get basic properties of the endomorphisms
`P q : K[X] ⟶ K[X]` with respect to face maps (see `homotopies.lean` for the
role of these endomorphisms in the overall strategy of proof).
The main lemma in this file is `higher_faces_vanish.induction`. It is based
on two technical lemmas `higher_faces_vanish.comp_Hσ_eq` and
`higher_faces_vanish.comp_Hσ_eq_zero`.
-/
open nat
open category_theory
open category_theory.limits
open category_theory.category
open category_theory.preadditive
open category_theory.simplicial_object
open_locale simplicial dold_kan
namespace algebraic_topology
namespace dold_kan
variables {C : Type*} [category C] [preadditive C]
variables {X : simplicial_object C}
/-- A morphism `φ : Y ⟶ X _[n+1]` satisfies `higher_faces_vanish q φ`
when the compositions `φ ≫ X.δ j` are `0` for `j ≥ max 1 (n+2-q)`. When `q ≤ n+1`,
it basically means that the composition `φ ≫ X.δ j` are `0` for the `q` highest
possible values of a nonzero `j`. Otherwise, when `q ≥ n+2`, all the compositions
`φ ≫ X.δ j` for nonzero `j` vanish. See also the lemma `comp_P_eq_self_iff` in
`projections.lean` which states that `higher_faces_vanish q φ` is equivalent to
the identity `φ ≫ (P q).f (n+1) = φ`. -/
def higher_faces_vanish {Y : C} {n : ℕ} (q : ℕ) (φ : Y ⟶ X _[n+1]) : Prop :=
∀ (j : fin (n+1)), (n+1 ≤ (j : ℕ) + q) → φ ≫ X.δ j.succ = 0
namespace higher_faces_vanish
@[reassoc]
lemma comp_δ_eq_zero {Y : C} {n : ℕ} {q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (j : fin (n+2)) (hj₁ : j ≠ 0) (hj₂ : n+2 ≤ (j : ℕ) + q) :
φ ≫ X.δ j = 0 :=
begin
obtain ⟨i, hi⟩ := fin.eq_succ_of_ne_zero hj₁,
subst hi,
apply v i,
rw [← @nat.add_le_add_iff_right 1, add_assoc],
simpa only [fin.coe_succ, add_assoc, add_comm 1] using hj₂,
end
lemma of_succ {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish (q+1) φ) : higher_faces_vanish q φ :=
λ j hj, v j (by simpa only [← add_assoc] using le_add_right hj)
lemma of_comp {Y Z : C} {q n : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (f : Z ⟶ Y) :
higher_faces_vanish q (f ≫ φ) := λ j hj,
by rw [assoc, v j hj, comp_zero]
lemma comp_Hσ_eq {Y : C} {n a q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (hnaq : n=a+q) : φ ≫ (Hσ q).f (n+1) =
- φ ≫ X.δ ⟨a+1, nat.succ_lt_succ (nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm))⟩ ≫
X.σ ⟨a, nat.lt_succ_iff.mpr (nat.le.intro hnaq.symm)⟩ :=
begin
have hnaq_shift : Π d : ℕ, n+d=(a+d)+q,
{ intro d, rw [add_assoc, add_comm d, ← add_assoc, hnaq], },
rw [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl),
hσ'_eq hnaq (c_mk (n+1) n rfl), hσ'_eq (hnaq_shift 1) (c_mk (n+2) (n+1) rfl)],
simp only [alternating_face_map_complex.obj_d_eq, eq_to_hom_refl,
comp_id, comp_sum, sum_comp, comp_add],
simp only [comp_zsmul, zsmul_comp, ← assoc, ← mul_zsmul],
/- cleaning up the first sum -/
rw [← fin.sum_congr' _ (hnaq_shift 2).symm, fin.sum_trunc], swap,
{ rintro ⟨k, hk⟩,
suffices : φ ≫ X.δ (⟨a+2+k, by linarith⟩ : fin (n+2)) = 0,
{ simp only [this, fin.nat_add_mk, fin.cast_mk, zero_comp, smul_zero], },
convert v ⟨a+k+1, by linarith⟩ (by { rw fin.coe_mk, linarith, }),
rw [nat.succ_eq_add_one],
linarith, },
/- cleaning up the second sum -/
rw [← fin.sum_congr' _ (hnaq_shift 3).symm, @fin.sum_trunc _ _ (a+3)], swap,
{ rintros ⟨k, hk⟩,
rw [assoc, X.δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero],
{ intro h,
rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h,
dsimp at h,
linarith, },
{ dsimp,
simp only [fin.coe_pred, fin.coe_mk, succ_add_sub_one],
linarith, },
{ dsimp,
linarith, }, },
/- leaving out three specific terms -/
conv_lhs { congr, skip, rw [fin.sum_univ_cast_succ, fin.sum_univ_cast_succ], },
rw fin.sum_univ_cast_succ,
simp only [fin.last, fin.cast_le_mk, fin.coe_cast, fin.cast_mk,
fin.coe_cast_le, fin.coe_mk, fin.cast_succ_mk, fin.coe_cast_succ],
/- the purpose of the following `simplif` is to create three subgoals in order
to finish the proof -/
have simplif : ∀ (a b c d e f : Y ⟶ X _[n+1]), b=f → d+e=0 → c+a=0 → a+b+(c+d+e) = f,
{ intros a b c d e f h1 h2 h3,
rw [add_assoc c d e, h2, add_zero, add_comm a b, add_assoc,
add_comm a c, h3, add_zero, h1], },
apply simplif,
{ /- b=f -/
rw [← pow_add, odd.neg_one_pow, neg_smul, one_zsmul],
use a,
linarith, },
{ /- d+e = 0 -/
rw [assoc, assoc, X.δ_comp_σ_self' (fin.cast_succ_mk _ _ _).symm,
X.δ_comp_σ_succ' (fin.succ_mk _ _ _).symm],
simp only [comp_id, pow_add _ (a+1) 1, pow_one, mul_neg, mul_one, neg_smul,
add_right_neg], },
{ /- c+a = 0 -/
rw ← finset.sum_add_distrib,
apply finset.sum_eq_zero,
rintros ⟨i, hi⟩ h₀,
have hia : (⟨i, by linarith⟩ : fin (n+2)) ≤ fin.cast_succ (⟨a, by linarith⟩ : fin (n+1)) :=
by simpa only [fin.le_iff_coe_le_coe, fin.coe_mk, fin.cast_succ_mk, ← lt_succ_iff] using hi,
simp only [fin.coe_mk, fin.cast_le_mk, fin.cast_succ_mk, fin.succ_mk, assoc, fin.cast_mk,
← δ_comp_σ_of_le X hia, add_eq_zero_iff_eq_neg, ← neg_zsmul],
congr,
ring_exp, },
end
lemma comp_Hσ_eq_zero {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) (hqn : n<q) : φ ≫ (Hσ q).f (n+1) = 0 :=
begin
simp only [Hσ, homotopy.null_homotopic_map'_f (c_mk (n+2) (n+1) rfl) (c_mk (n+1) n rfl)],
rw [hσ'_eq_zero hqn (c_mk (n+1) n rfl), comp_zero, zero_add],
by_cases hqn' : n+1<q,
{ rw [hσ'_eq_zero hqn' (c_mk (n+2) (n+1) rfl), zero_comp, comp_zero], },
{ simp only [hσ'_eq (show n+1=0+q, by linarith) (c_mk (n+2) (n+1) rfl),
pow_zero, fin.mk_zero, one_zsmul, eq_to_hom_refl, comp_id,
comp_sum, alternating_face_map_complex.obj_d_eq],
rw [← fin.sum_congr' _ (show 2+(n+1)=n+1+2, by linarith), fin.sum_trunc],
{ simp only [fin.sum_univ_cast_succ, fin.sum_univ_zero, zero_add, fin.last,
fin.cast_le_mk, fin.cast_mk, fin.cast_succ_mk],
simp only [fin.mk_zero, fin.coe_zero, pow_zero, one_zsmul, fin.mk_one,
fin.coe_one, pow_one, neg_smul, comp_neg],
erw [δ_comp_σ_self, δ_comp_σ_succ, add_right_neg], },
{ intro j,
rw [comp_zsmul, comp_zsmul, δ_comp_σ_of_gt', v.comp_δ_eq_zero_assoc, zero_comp, zsmul_zero],
{ intro h,
rw [fin.pred_eq_iff_eq_succ, fin.ext_iff] at h,
dsimp at h,
linarith, },
{ dsimp,
simp only [fin.cast_nat_add, fin.coe_pred, fin.coe_add_nat, add_succ_sub_one],
linarith, },
{ rw fin.lt_iff_coe_lt_coe,
dsimp,
linarith, }, }, },
end
lemma induction {Y : C} {n q : ℕ} {φ : Y ⟶ X _[n+1]}
(v : higher_faces_vanish q φ) : higher_faces_vanish (q+1) (φ ≫ (𝟙 _ + Hσ q).f (n+1)) :=
begin
intros j hj₁,
dsimp,
simp only [comp_add, add_comp, comp_id],
-- when n < q, the result follows immediately from the assumption
by_cases hqn : n<q,
{ rw [v.comp_Hσ_eq_zero hqn, zero_comp, add_zero, v j (by linarith)], },
-- we now assume that n≥q, and write n=a+q
cases nat.le.dest (not_lt.mp hqn) with a ha,
rw [v.comp_Hσ_eq (show n=a+q, by linarith), neg_comp, add_neg_eq_zero, assoc, assoc],
cases n with m hm,
-- the boundary case n=0
{ simpa only [nat.eq_zero_of_add_eq_zero_left ha, fin.eq_zero j,
fin.mk_zero, fin.mk_one, δ_comp_σ_succ, comp_id], },
-- in the other case, we need to write n as m+1
-- then, we first consider the particular case j = a
by_cases hj₂ : a = (j : ℕ),
{ simp only [hj₂, fin.eta, δ_comp_σ_succ, comp_id],
congr,
ext,
simp only [fin.coe_succ, fin.coe_mk], },
-- now, we assume j ≠ a (i.e. a < j)
have haj : a<j := (ne.le_iff_lt hj₂).mp (by linarith),
have hj₃ := j.is_lt,
have ham : a≤m,
{ by_contradiction,
rw [not_le, ← nat.succ_le_iff] at h,
linarith, },
rw [X.δ_comp_σ_of_gt', j.pred_succ], swap,
{ rw fin.lt_iff_coe_lt_coe,
simpa only [fin.coe_mk, fin.coe_succ, add_lt_add_iff_right] using haj, },
obtain (ham' | ham'') := ham.lt_or_eq,
{ -- case where `a<m`
rw ← X.δ_comp_δ''_assoc, swap,
{ rw fin.le_iff_coe_le_coe,
dsimp,
linarith, },
simp only [← assoc, v j (by linarith), zero_comp], },
{ -- in the last case, a=m, q=1 and j=a+1
rw X.δ_comp_δ_self'_assoc, swap,
{ ext,
dsimp,
have hq : q = 1 := by rw [← add_left_inj a, ha, ham'', add_comm],
linarith, },
simp only [← assoc, v j (by linarith), zero_comp], },
end
end higher_faces_vanish
end dold_kan
end algebraic_topology
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.